blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
394d74a1b74264a9326005b4df0e41a7a7baeb8c
sekR4/ML_SageMaker_Studies
/Project_Plagiarism_Detection/helpers.py
8,199
3.53125
4
import operator import re import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer # Add 'datatype' column that indicates if the record is original wiki answer as 0, training data 1, test data 2, onto # the dataframe - uses stratified random sampling (with seed) to sample by task & plagiarism amount # Use function to label datatype for training 1 or test 2 def create_datatype( df, train_value, test_value, datatype_var, compare_dfcolumn, operator_of_compare, value_of_compare, sampling_number, sampling_seed, ): # Subsets dataframe by condition relating to statement built from: # 'compare_dfcolumn' 'operator_of_compare' 'value_of_compare' df_subset = df[operator_of_compare(df[compare_dfcolumn], value_of_compare)] df_subset = df_subset.drop(columns=[datatype_var]) # Prints counts by task and compare_dfcolumn for subset df # print("\nCounts by Task & " + compare_dfcolumn + ":\n", df_subset.groupby(['Task', compare_dfcolumn]).size().reset_index(name="Counts") ) # Sets all datatype to value for training for df_subset df_subset.loc[:, datatype_var] = train_value # Performs stratified random sample of subset dataframe to create new df with subset values df_sampled = df_subset.groupby(["Task", compare_dfcolumn], group_keys=False).apply( lambda x: x.sample(min(len(x), sampling_number), random_state=sampling_seed) ) df_sampled = df_sampled.drop(columns=[datatype_var]) # Sets all datatype to value for test_value for df_sampled df_sampled.loc[:, datatype_var] = test_value # Prints counts by compare_dfcolumn for selected sample # print("\nCounts by "+ compare_dfcolumn + ":\n", df_sampled.groupby([compare_dfcolumn]).size().reset_index(name="Counts") ) # print("\nSampled DF:\n",df_sampled) # Labels all datatype_var column as train_value which will be overwritten to # test_value in next for loop for all test cases chosen with stratified sample for index in df_sampled.index: # Labels all datatype_var columns with test_value for straified test sample df_subset.loc[index, datatype_var] = test_value # print("\nSubset DF:\n",df_subset) # Adds test_value and train_value for all relevant data in main dataframe for index in df_subset.index: # Labels all datatype_var columns in df with train_value/test_value based upon # stratified test sample and subset of df df.loc[index, datatype_var] = df_subset.loc[index, datatype_var] # returns nothing because dataframe df already altered def train_test_dataframe(clean_df, random_seed=100): new_df = clean_df.copy() # Initialize datatype as 0 initially for all records - after function 0 will remain only for original wiki answers new_df.loc[:, "Datatype"] = 0 # Creates test & training datatypes for plagiarized answers (1,2,3) create_datatype( new_df, 1, 2, "Datatype", "Category", operator.gt, 0, 1, random_seed ) # Creates test & training datatypes for NON-plagiarized answers (0) create_datatype( new_df, 1, 2, "Datatype", "Category", operator.eq, 0, 2, random_seed ) # creating a dictionary of categorical:numerical mappings for plagiarsm categories mapping = {0: "orig", 1: "train", 2: "test"} # traversing through dataframe and replacing categorical data new_df.Datatype = [mapping[item] for item in new_df.Datatype] return new_df # helper function for pre-processing text given a file # def process_file(file): # # put text in all lower case letters # all_text = file.read().lower() # # remove all non-alphanumeric chars # all_text = re.sub(r"[^a-zA-Z0-9]", " ", all_text) # # remove newlines/tabs, etc. so it's easier to match phrases, later # all_text = re.sub(r"\t", " ", all_text) # all_text = re.sub(r"\n", " ", all_text) # all_text = re.sub(" ", " ", all_text) # all_text = re.sub(" ", " ", all_text) # return all_text def process_file(file): # put text in all lower case letters all_text = file.read() return clean_text(all_text) def clean_text(txt: str): all_text = txt.lower() # remove all non-alphanumeric chars all_text = re.sub(r"[^a-zA-Z0-9]", " ", all_text) # remove newlines/tabs, etc. so it's easier to match phrases, later all_text = re.sub(r"\t", " ", all_text) all_text = re.sub(r"\n", " ", all_text) all_text = re.sub(" ", " ", all_text) all_text = re.sub(" ", " ", all_text) return all_text def create_text_column(df, file_directory="data/"): """Reads in the files, listed in a df and returns that df with an additional column, `Text`. :param df: A dataframe of file information including a column for `File` :param file_directory: the main directory where files are stored :return: A dataframe with processed text""" # create copy to modify text_df = df.copy() # store processed text text = [] # for each file (row) in the df, read in the file for row_i in df.index: filename = df.iloc[row_i]["File"] # print(filename) file_path = file_directory + filename with open(file_path, "r", encoding="utf-8", errors="ignore") as file: # standardize text using helper function file_text = process_file(file) # append processed text to list text.append(file_text) # add column to the copied dataframe text_df["Text"] = text return text_df def lcs_normalized(a: str, s: str, verbose=False) -> float: """Calculates normalized longest common subsequence between two sequences. Parameters ---------- a : str First sequence, answer (matrix rows) b : str Second sequence, source (matrix columns) verbose : bool, optional Prints out sequence matrices in different states, by default False Returns ------- float normalized longest common subsequence """ a_text, s_text = a.split(), s.split() len_a, len_s = len(a_text), len(s_text) # 1. Create empty matrix word_matrix = np.zeros((len_s + 1, len_a + 1), dtype=int) # 2. Fill matrix for s_idx, s_word in enumerate(s_text, 1): for a_idx, a_word in enumerate(a_text, 1): if s_word == a_word: word_matrix[s_idx][a_idx] = word_matrix[s_idx - 1][a_idx - 1] + 1 else: word_matrix[s_idx][a_idx] = max( word_matrix[s_idx - 1][a_idx], word_matrix[s_idx][a_idx - 1] ) return word_matrix[len_s][len_a] / len_a def calculate_containment(df: pd.DataFrame, n: int, answer_filename: str) -> float: """Calculates the containment between a given answer text and its associated source text. This function creates a count of ngrams (of a size, n) for each text file in our data.Then calculates the containment by finding the ngram count for a given answer text, and its associated source text, and calculating the normalized intersection of those counts. Parameters ---------- df : pd.DataFrame Dataframe with columns: 'File', 'Task', 'Category', 'Class', 'Text', 'Datatype' n : int An integer that defines the ngram size answer_filename : str A filename for an answer text in the df, ex. 'g0pB_taskd.txt' Returns ------- float A single containment value that represents the similarity between an answer text and its source text. """ # 1. Get student answer 'a' a = df[df.File == answer_filename].Text.iloc[0] # 2. Get wikipedia source 's' f1 = df.Datatype == "orig" f2 = df.File.str.split("_").apply(lambda x: x[-1]) == answer_filename.split("_")[-1] s = df[f1 & f2].Text.iloc[0] # 3. Create N-gram counts = CountVectorizer(ngram_range=(n, n)) ngram_array = counts.fit_transform([a, s]).toarray() # 4. Calculate containment intersection = sum([min(i, j) for i, j in zip(ngram_array[0], ngram_array[1])]) return intersection / sum(ngram_array[0]) if __name__ == "__main__": pass
57943b92c083b740e40dba6a555c41aae242da39
mollinaca/ac
/code/speedrun_001/3.py
200
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- n = int(input()) a = list(map(int,input().split())) for i in range(len(a)): print (a[i], end="") if not i+1 == len(a): print (",",end="")
af4c5f576a243d64a4ac69bb1acc0dd7a6915380
alicevillar/python-lab-challenges
/functions/functions_exercise2.py
1,487
4.34375
4
#################################################################################################################### # Functions - Lab Exercise 2 # # Write a function called odds_or_evens that takes a boolean and a list of integers as parameters. # If the boolean parameter is True, return a list of only even numbers. # If the boolean parameter isFalse, return a list of only odd numbers. # # Expected Output: # If the function call is odds_or_evens(True, [8, 13, 22, 31]), the the function would return [22, 8] # If the function call is odds_or_evens(False, [8, 13, 22, 31]), the the function would return [13, 31] # #################################################################################################################### def odds_or_evens(boolean, my_list): if boolean: for i in my_list: if i % 2 != 0: my_list.remove(i) else: for i in my_list: if i % 2 == 0: my_list.remove(i) return my_list print(odds_or_evens(True, [8, 13, 22, 31])) #Output => [22, 8] # If the function call is odds_or_evens(False, [13, 22, 8, 31]): def odds_or_evens(boolean, my_list): if boolean: for i in my_list: if i % 2 != 0: my_list.remove(i) else: for i in my_list: if i % 2 == 0: my_list.remove(i) return my_list print(odds_or_evens(False, [8, 13, 22, 31])) #Output => [13, 31]
5a3826655c4f936cf3eead4f40c6539cea9d332a
VinodMeganathan/Guvi
/Print_Minimum_And_Maximum_In_A_List.py
134
4.09375
4
''' PROGRAM TO PRINT MINIMUM AN MAXIMUM IN A GIVEN ELEMENTS ''' a=int(input()) istring=input() b=istring.split() print(min(b),max(b))
9b95a9819a47e6e8836f80ecd1f2f1c10b5ce7c5
sithon512/oop-microbial-growth
/petri.py
5,459
4.0625
4
""" The classes contained in this module define a petri dish instance. """ from microbe import Microbe from nutrient import Nutrient class PetriCell: """ This class defines a cell in the grid that makes up the petri dish. Cells are acrive classes that handle the interaction between nutrients and microbes. """ def __init__(self): """ Initialize the class instance. Initialization simply sets the instance variables to None and []. """ self.microbe = None self.nutrients = [] def __str__(self): """ String representation takes the form "M#N" where 'M' is only present if a microbe is present, otherwise it is replaced by '_', and '#' is replaced by the number of nutrients in the cell. """ if self.hasMicrobe(): return f'M{len(self.nutrients)}N' else: return f'_{len(self.nutrients)}N' def getMicrobe(self): """ Returns the value of the microbe attribute. """ return self.microbe def hasMicrobe(self): """ Returns whether or not the cell has a microbe sitting in it. """ return self.microbe != None def createMicrobe(self): """ Creates a new microbe instance and places it in the cell. This should take place during initialization and the reproduction stage of the simulation. """ self.microbe = Microbe() def hasNutrients(self): """ Returns true if the nutrients instance variable has any nutrients and false otherwise. """ return len(self.nutrients) != 0 def getNutrient(self): """ Removes a nutrient from the list of nutrients and returns it. Returns None if there are no nutrients. """ if not self.hasNutrients(): return None else: # chose to use queue style arbitrarily, LIFO would have worked fine return self.nutrients.pop(0) def getUnmoved(self): """ Removes all nutrients from the cell that have not moved and returns them in a list. """ # get list of unmoved nutrients unmoveds = [nutrient for nutrient in self.nutrients if not nutrient.getMoved()] # remove unmoved nutrients from nutrients instance variable self.nutrients = [nutrient for nutrient in self.nutrients if nutrient not in unmoveds] # return the list of unmoveds return unmoveds def clearAllMoved(self): """ Calls the `clearMoved` method on each nutrient contained in `nutrients`. """ for nutrient in self.nutrients: nutrient.clearMoved() def placeNutrient(self, nutrient): """ Adds the given `nutrient` to the list of nutrients in the cell. """ self.nutrients.append(nutrient) class PetriDish: """ This class defines the dish grid in which `PetriCell` instances sit. """ def __init__(self, x, y, concentration, microbes): """ Initialize the class instance. Create the grid as a 2D list, place PetriCell instances in each index, then begin assigning nutrients to PetriCells based on concentration. Finally, place microbes according to the locations described in the list of tuples passed as the `microbes` argument. """ # define base grid self.grid = [[None for j in range(y)] for i in range(x)] # record x and y for easy reference later self.x = x self.y = y # populate grid with lists of PetriCells for i in range(x): # self.grid[i] = [] for j in range(y): self.grid[i][j] = PetriCell() # import random for nutrient placement from random import randint # calculate number of nutrients nutrients_to_place = int(concentration * x * y) # place nutrients, may overlap for i in range(nutrients_to_place): place_x = randint(0, x-1) place_y = randint(0, y-1) self.grid[place_x][place_y].placeNutrient(Nutrient()) # place microbes for coordx, coordy in microbes: # note: ignores duplicate coords self.grid[coordx][coordy].createMicrobe() def __str__(self): """ Prints the grid of cells. """ output = '' # x should iterate within y to create rows for j in range(self.y): row = '' for i in range(self.x): row += f'{self.grid[i][j]} ' row = f'{row.strip()}\n' output += row return output def moveNutrients(self): """ Iterate through each cell in grid, moving nutrients that have not moved yet. """ from random import randint def coord_in_bounds(x, y): """ Checks if a position is on the grid or out of bounds. """ # if one of these conditions is true, then coord is not in bounds return not (x < 0 or y < 0 or x > self.x - 1 or y > self.y - 1) for i in range(self.x): for j in range(self.y): for nutrient in self.grid[i][j].getUnmoved(): shiftx = randint(-1, 1) shifty = randint(-1, 1) # if the coord was invalid, re-roll it while not coord_in_bounds(i + shiftx, j + shifty): shiftx = randint(-1, 1) shifty = randint(-1, 1) # place nutrient into the selected adjacent cell self.grid[i+shiftx][j+shifty].placeNutrient(nutrient) # mark the nutrient as having moved nutrient.setMoved() def checkMicrobes(self): """ For each microbe, check if it has a nutrient or has a nutrient in its cell. If a nutrient is found, consume it. Records the position of the offspring, then moves on to the next microbe. Once all microbes have had a chance to try reproduction, the new microbes are placed onto the grid. """ return def step(self, iterations): """ Run through a number of iterations where one iteration is a call to `moveNutrients` followed by a call to `checkMicrobes`. """ return
7249574ddce16f7586b80bf51dc3412196a31ff4
techkids-c4e/c4e5
/Ha Tran/buoi 2_19.6/ve hinh.py
267
3.875
4
from turtle import* color('black','white') for side in range(7,2,-1): if (side%2==0): color("blue","green") else: color("red","yellow") begin_fill() for i in range(side): forward(100) left(360/side) end_fill()
736cf50cfb5a1ba835e8fb17d6f7759335ad93cd
MONICA-Project/sfn
/WP5/KU/SharedResources/get_incrementer.py
1,056
4
4
# get_incrementer.py """Helper function to create counter strings with a set length throughout.""" __version__ = '0.2' __author__ = 'Rob Dupre (KU)' def get_incrementer(num, num_digits): if num >= 10**num_digits: print('NUMBER IS LARGER THAN THE MAX POSSIBLE BASED ON num_digits') return -1 else: if num > 9999999: number_length = 8 elif num > 999999: number_length = 7 elif num > 99999: number_length = 6 elif num > 9999: number_length = 5 elif num > 999: number_length = 4 elif num > 99: number_length = 3 elif num > 9: number_length = 2 else: number_length = 1 char = '' for i in range(num_digits - number_length): char = char + '0' return char + str(num) def get_num_length(num): if type(num) == int: return len(str(num)) else: print('Number is not an Int. Length will include the decimal') return len(str(num))
91ebc537033942c138162609c3cf34bfac8f2230
sindusistla/Algorithms-and-Datastructures
/Algorithms/Brackets.py
3,511
3.578125
4
def CheckTheExpression(expression,exp_len): retVal=False for i in range (0,int(exp_len/2)): #print(expression[i],expression[exp_len-i-1]) if (expression[i] == "{" and expression[exp_len-i-1] =="}" ): retVal = True elif(expression[i] == "[" and expression[exp_len-i-1] =="]"): retVal = True elif (expression[i] == "(" and expression[exp_len-i-1] ==")"): retVal = True else: retVal = False break; return retVal; def CheckAdjacentBracket(Visited,Bracket): exp_len_visited=len(Visited) retValue=False if(exp_len_visited>0): if (Bracket=="}" and Visited[exp_len_visited-1] == "{"): #pop the opening bracket from the list Visited.remove(Visited[exp_len_visited-1]); retValue = True; elif (Bracket==")" and Visited[exp_len_visited-1] == "("): #pop the opening bracket from the list Visited.remove(Visited[exp_len_visited-1]); retValue = True; elif (Bracket=="]" and Visited[exp_len_visited-1] == "["): #pop the opening bracket from the list Visited.remove(Visited[exp_len_visited-1]); retValue = True; ##else: # append the closing bracket to the Visited list #Visited.append(Bracket); return retValue def is_matched(expression,exp_len): Visited=[]; retValue=True; for i in range(0,exp_len): if(expression[i]=="{" or expression[i]=="[" or expression[i]=="("): # All opening brackets push into visited #print(Visited) Visited.append(expression[i]); elif (expression[i]=="}" or expression[i]=="]" or expression[i]==")"): # if closing braces #Visited.append(expression[i]); #print(Visited) retValue=CheckAdjacentBracket(Visited,expression[i]); print(Visited) if (len(Visited)>0): retValue= CheckTheExpression(Visited, len(Visited)) return retValue def isMatched(expression,exp_len): Stack=[] retValue=False; for i in range(0, exp_len): if (expression[i] == "{" or expression[i] == "[" or expression[i] == "("): # All opening brackets push into visited # print(Visited) Stack.append(expression[i]); elif (expression[i] == "}" or expression[i] == "]" or expression[i] == ")"): if(len(Stack)==0): retValue=False; break; last_one=Stack.pop(); #print(last_one,expression[i]) if (expression[i] == "}" and last_one == "{"): # pop the opening bracket from the list retValue = True; elif (expression[i]==")" and last_one == "("): # pop the opening bracket from the list retValue = True; elif (expression[i]=="]" and last_one == "["): # pop the opening bracket from the list retValue = True; else: retValue=False; break; #print(Stack) if(len(Stack)!=0): retValue=False; return retValue; t = int(input().strip()) for a0 in range(t): expression = list(input().strip()); exp_len=len(expression) if (exp_len%2==0): if isMatched(expression,exp_len) == True: print("YES") else: print("NO") else: print("NO")
71f945453045440650923fc513112259bfc9ab8a
craghack55/HackerRank
/Python Track/Strings/FindString.py
138
3.9375
4
#!/bin/python import sys import re def count_substring(string, sub_string): return len(re.findall("(?=" + sub_string + ")", string))
9db938e3ee51d18deb92c117c5a0c8b7e28ab16a
Azjargal13/python-scripts-fun
/problems/mergetools.py
405
3.59375
4
def mergeTool(string, k): n = len(string) r = n//k for i in range(r): subs = string[:k] string = string.replace(subs,'') d=removeSame(subs) print(''.join(str(key) for key in d.keys())) def removeSame(substring): dict_={} for i in range(len(substring)): dict_[substring[i]] = substring[i] return dict_ mergeTool('AABCAAADA', 3)
bf366aa9e88861aadca1be85b351870bac3d3d16
debugu/python
/算法/打印字符串里的所有排列.py
1,805
4
4
import copy def string_to_list(string): ls = [] for char in string: ls.append(char) return ls def add_char_to_er_list(newchar, ls): # 向二维数组中插入数据 newls = [] for i in range(0, len(ls) + 1): temp = copy.deepcopy(ls) # 使用 a[:], list(a), # a*1, copy.copy(a)四种方式复制列表 # 结果都可以得到一个新的列表,但是如果列表中含有列表,所有 # b, c, d, e四个新列表的子列表都是指引到同一个对象上。 # 只有使用copy.deepcopy(a)方法得到的新列表f才是包括子列表 # 在内的完全复制。 temp.insert(i, newchar) newls.append(temp) return newls def add_char_to_san_list(newchar, ls): # 向三维数组中插入数据 newls = [[]] if len(ls) == 0: temp = [1] temp[0] = newchar newls[0] = temp return newls newls = [] for er_ls in ls: temp = add_char_to_er_list(newchar, er_ls) for tls in temp: newls.append(tls) return newls print_string = input("请输入待打印的字符串:") print_char_list = string_to_list(print_string) # 将待打印的字符串转成字符数组 print_string_list = [] # 存放所有的可能的字符数组排列组合 print_content = [] # 将字符数组转化成字符串数组 for i in range(0, len(print_char_list)): print_string_list = add_char_to_san_list(print_char_list[i], print_string_list) for content in print_string_list: print_content.append("".join(content)) print_content.sort() print("共{}种排列,打印如下:".format(len(print_content))) for i in range(0, len(print_content)): print("{}:{}".format(i + 1, print_content[i]))
aded92486c519a2c2891201d02301da382713bc9
samuelveigarangel/CursoemVideo
/ex14_ConversorTemp.py
123
3.859375
4
c = float(input('Digite a temperatura em Celsius: ')) print(f'Temp em celsius {c} convertida para fahrenheit {(c*1.8)+32}')
1cabd8fe3c1e030ec1f35fb29efa13b18395a102
soicem/favorite-things-update-check
/database/db.py
1,598
3.5
4
import sqlite3 import time class dbConnection: def __init__(self): self.datatimeFormat = "%04d-%02d-%02d %02d:%02d:%02d" def insertIntoFavoriteUpdate(self, name, url): with sqlite3.connect("test.db") as conn: now = time.localtime() s = self.datatimeFormat % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) print(s) cur = conn.cursor() # conn.execute('''create table favoriteUpdate( # id integer primary key autoincrement, # name text not null, # url text, # date datetime);''') InsertCommand = "INSERT INTO favoriteUpdate values(null, '%s', '%s', '%s')" % (name, url, s) print(InsertCommand) conn.execute(InsertCommand) cur.execute("select * from favoriteUpdate") for row in cur.fetchall(): print(row) def printAll(self): ret = [] with sqlite3.connect("test.db") as conn: cur = conn.cursor() cur.execute("select * from favoriteUpdate;") for row in cur.fetchall(): print(row) ret.append(row) return ret def createTable(self): with sqlite3.connect("test.db") as conn: conn.execute('''create table favoriteUpdate( id integer primary key autoincrement, name text not null, url text, date datetime);''')
8c200faf14e77b05b96b7ba292b43c53cdfdccd0
mBortell88/PRG105
/MobileServicePlanBill.py
1,792
4.15625
4
# Write program that calculates the customer's monthly bill. # Ask which package the customer has purchased and how many minutes were used. # Display the total amount due. Use a dollar sign and two decimal places for currency. # Variables package_plan = input('Which package are you subscribed to: Package A, Package B or Package C? ') if package_plan == "Package A": max_minutes_per_month = 450 std_month_bill = 39.99 over_max_min_fee = 0.45 mins_used = float(input('How many minutes were used this month?')) if mins_used <= max_minutes_per_month: print('$', format(std_month_bill, ',.2f')) elif mins_used > max_minutes_per_month: bill_for_month = std_month_bill + ((mins_used - max_minutes_per_month) * over_max_min_fee) print('$', format(bill_for_month, ',.2f')) elif package_plan == "Package B": max_minutes_per_month = 900 std_month_bill = 59.99 over_max_min_fee = 0.40 mins_used = float(input('How many minutes were used this month?')) if mins_used <= max_minutes_per_month: print('$', format(std_month_bill, ',.2f')) elif mins_used > max_minutes_per_month: bill_for_month = ((mins_used - max_minutes_per_month) * over_max_min_fee) + std_month_bill print('$', format(bill_for_month, ',.2f')) elif package_plan == "Package C": max_minutes_per_month = 'unlimited' std_month_bill = 69.99 over_max_min_fee = 0.00 mins_used = float(input('How many minutes were used this month?')) bill_for_month = (mins_used * over_max_min_fee) + std_month_bill print('$', format(bill_for_month, ',.2f')) else: print('Error! Please enter one of the three following packages for further details:' ' Package A, Package B or Package C')
bc770e7fe8f4e67a519eb0192dc87af9b7c86370
MrLao9038/GuessMyPass
/GuessMyPass.py
2,015
3.890625
4
#!/usr/bin/env python3 #Select interpreter for BASH import random #Module for generating pseudo-random number print(" ") print("Let me Guess The Password You") print("--------------------------------") #Ascii Art print("8eeee8 8 8 8eeee 8eeee8 8eeee8") print("8 8 8 8 8 8 8 ") print("8 8 8 8eeee 8eeeee 8eeeee") print("8 eee 8 8 88 88 88") print("8 8 8 8 88 e 88 e 88") print("88eee8 88ee8 88eee 8eee88 8eee88") print("--------------------------------") print(" ") uppercase_letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] lowercase_letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] numbers = ["0","1","2","3","4","5","6","7","8","9"] special_characters = ["@","%","+","|","?","!","#","$","^","?",":",",","(",")","{","}","[","]","~","_","-",".","/","\\"] #List of letters, numbers, and special characters for password char_list = uppercase_letters+ lowercase_letters + numbers + special_characters #Combining all the lists into one large list real_password = str(input("Please Enter Password: ")) #Input function to allow user input guess_password = "" #Empty string to store our random generated password while guess_password != list(real_password): guess_password = random.choices(char_list, k=len(real_password)) #Return "k" sized list of elements chosen from the char_list with replacement print("Attempting to Guess Password: " + str(guess_password)) #Showcase all the random guess password combination attempts if guess_password == list(real_password): print("Your Password is: " + "".join(guess_password)) break #Break out of the loop once password has been guess correctly
21f3f838995f574f198202768c78ad9bd915256e
webturing/PythonProgramming_20DS123
/lec03-branch2/while.py
76
3.65625
4
print("hello1") if 4>3: print("hello2") while True: print("hello3")
aebde83399de1778a236d51c75ccae3ce1900edf
StevenM42/cp1404practicals
/prac_03/gopher_population_simulator.py
712
4.0625
4
""" CP1404/CP5632 - Practical Gopher Population Simulator using random number generation """ import random population = 1000 total_years = 10 current_year = 0 min_birth_rate = 10 max_birth_rate = 20 min_death_rate = 5 max_death_rate = 25 print('Welcome to the Gopher Population Simulator!') while total_years > current_year: current_year += 1 birth_rate = population * (random.randint(min_birth_rate, max_birth_rate) / 100) death_rate = population * (random.randint(min_death_rate, max_death_rate) / 100) population += birth_rate - death_rate print(f'{birth_rate:.0f} gophers were born. {death_rate:.0f} died.') print(f'Population: {population:.0f}') print(f'Year {current_year}')
7f77522cc445d6d3fcbb7b8a373f14477a7409fa
imamol555/Machine-Learning
/DecisionTree_SKLearn_Fruits .py
1,004
4.1875
4
#=================================================== #Title : Decision Tree Classifier for classifying a type of fruit #Author : Amol Patil # #======================================= #classes - Apple and Orange #Features = [weight, texture] #Texture- Smooth =1 # Bumpy =0 #Labels - Apple =0 # orange=1 from sklearn import tree features = [[140,1],[130,1],[150,0],[170,0]] labels = [0,0,1,1] #selecting a type of classfier #initially a classifier is nothing but a box of rules clf = tree.DecisionTreeClassifier() #Now the classifier will find a pattern to classify our data #fit() method takes our train data and builds up a classifier #it's a training algorithm which can be applied on classifier object clf #creating a decision tree ie. setting up the classifier rules clf = clf.fit(features,labels) #predict for a random data result = clf.predict([[152,0],[139,0]]) print(result) for i in result: if (i==1):print("Orange") else:print("Apple")
d47e7c7a1985bb91c26256b654a0d99ce748f7de
mschae94/Python
/Day18/GUIEx07.py
582
4
4
#라디오 버튼(radio button) #라디오 버튼은 단 1개의 학목만 선택할 수있다. from tkinter import * root = Tk() root.title("설문조사") select = IntVar() select.set(1) language = [("Pythoin" , 1) , ("Java" , 2) , ("C" , 3)] def showChoice(): print(select.get()) Label(root , text = "원하는 언어를 선택하세요 :" , justify =LEFT).pack() #반복처리 for txt , val in language: Radiobutton(root , text = txt, padx=20, variable=select,command=showChoice, value=val).pack(anchor=W) root.mainloop()
3111a5b8d4b0702387db2accefe10c68259a02e0
SrinuBalireddy/Python_Snippets
/Programs/may/csv_json.py
586
3.5
4
# Write your code here :-) import csv #outputFile = open('example1.csv', 'w', newline='') outputFile = open('example1.csv', 'w') outputWriter = csv.writer(outputFile) outputWriter.writerow(['spam','eggs','news','heros']) outputWriter.writerow(['Hello,world','eggs','news','heros']) outputWriter.writerow(['10','11','12','13']) outputWriter.writerow(['0.1','a1i82','b&eey','heros1']) outputFile.close() inputFile = open('example.csv') inputReader = csv.reader(inputFile) #exampleReader = list(inputReader) for row in inputReader: print(str(inputReader.line_num)+' : '+ str(row))
af04db972c0e1c6a7d379329becb9127ac7c1933
tagsBag/tdx_data_server
/tcp_client.py
2,979
3.5
4
from socket import * def main(): # 1.创建tcp_client_socket 套接字对象 tcp_client_socket = socket(AF_INET,SOCK_STREAM) # 作为客户端,主动连接服务器较多,一般不需要绑定端口 # 2.连接服务器 tcp_client_socket.connect(("127.0.0.1",54572)) while True: """无限循环可以实现无限聊天""" # 3.向服务器发送数据 # 代码 市场 类型 日期格式:"2000-01-02 22:10:10"(日期和时间中间隔一个空格,日期用"-"隔开,时间用":"隔开,前置"0"都可以不用,因为会被转化为整数使用) """ #define PER_MIN5 0 //5分钟数据 #define PER_MIN15 1 //15分钟数据 #define PER_MIN30 2 //30分钟数据 #define PER_HOUR 3 //1小时数据 #define PER_DAY 4 //日线数据 #define PER_WEEK 5 //周线数据 #define PER_MONTH 6 //月线数据 #define PER_MIN1 7 //1分钟数据 #define PER_MINN 8 //多分析数据(10) #define PER_DAYN 9 //多天线数据(45) #define PER_SEASON 10 //季线数据 #define PER_YEAR 11 //年线数据 #define PER_SEC5 12 //5秒线 #define PER_SECN 13 //多秒线(15) #define PER_PRD_DIY0 14 //DIY周期 #define PER_PRD_DIY10 24 //DIY周期 #define REPORT_DAT2 102 //行情数据(第二版) #define GBINFO_DAT 103 //股本信息 #define STKINFO_DAT 105 //股票相关数据 #define TPPRICE_DAT 121 //涨跌停数据 """ if(True): #mid 发送请求命令长度 meg = "Code:600000\r\n Market:1\r\n Type:4\r\n From:2019-12-02 22:10:10\r\n To:2020-01-02 22:10:10\r\n".encode() count = len(meg) count_str = str(count) count_str = count_str.ljust(512,'\0').encode() tcp_client_socket.send(count_str) if(True): #mid 发送请求命令 tcp_client_socket.send(meg) # 在linux中默认是utf-8编码 # 在udp协议中使用的sendto() 因为udp发送的为数据报,包括ip port和数据, # 所以sendto()中需要传入address,而tcp为面向连接,再发送消息之前就已经连接上了目标主机 # 4.接收服务器返回的消息 #recv_data = tcp_client_socket.recv(1024) # 此处与udp不同,客户端已经知道消息来自哪台服务器,不需要用recvfrom了 data = tcp_client_socket.recv(512) if not data: break total_data.append(data) if recv_data: print("返回的消息为:",recv_data.decode('gbk')) else: print("对方已离线。。") break tcp_client_socket.close() if __name__ == '__main__': main()
df0977f67c970225864736848ed175ae190364dc
ZainebPenwala/Python-practice-problems
/list.py
248
3.828125
4
# sum of all elements in a list li=[1,2,3,4,5,6,7,8,9] t=0 for elem in li: t=t+elem print(t) # sum of all individual digits from a list of integer li=[11,12,13,14,15] t=0 for elem in li: for i in str(elem): t+= int(i) print(t)
6000816670eb88623b6bbd12a90690dde8e82537
goldan/machinery
/common/utils.py
3,502
4.0625
4
"""Common utility functions and constants used throughout the project.""" import collections import csv from datetime import datetime def roundto(value, digits=3): """Round value to specified number of digits. Args: value: value to round. digits: number of digits to round to. Returns: rounded value. """ return round(value, digits) def pretty_date(time=False): """ Get pretty representation of a date/time. Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc. Copied from http://stackoverflow.com/a/1551394/304209. Args: time: datetime object or epoch timestamp. Returns: date in human format, like 'an hour ago'. """ now = datetime.now() if isinstance(time, int): diff = now - datetime.fromtimestamp(time) elif isinstance(time, datetime): diff = now - time elif not time: diff = now - now second_diff = diff.seconds day_diff = diff.days if day_diff < 0: return '' if day_diff == 0: if second_diff < 10: return "just now" if second_diff < 60: return str(second_diff) + " seconds ago" if second_diff < 120: return "a minute ago" if second_diff < 3600: return str(second_diff / 60) + " minutes ago" if second_diff < 7200: return "an hour ago" if second_diff < 86400: return str(second_diff / 3600) + " hours ago" if day_diff == 1: return "Yesterday" if day_diff < 7: return str(day_diff) + " days ago" if day_diff < 31: return str(day_diff / 7) + " weeks ago" if day_diff < 365: return str(day_diff / 30) + " months ago" return str(day_diff / 365) + " years ago" def parse_classification_report(clfreport): """ Parse a sklearn classification report into a dict keyed by class name and containing a tuple (precision, recall, fscore, support) for each class. Taken from https://gist.github.com/julienr/6b9b9a03bd8224db7b4f """ lines = clfreport.split('\n') # Remove empty lines lines = filter(lambda l: not len(l.strip()) == 0, lines) # Starts with a header, then score for each class and finally an average header = lines[0] cls_lines = lines[1:-1] avg_line = lines[-1] assert header.split() == ['precision', 'recall', 'f1-score', 'support'] assert avg_line.split()[0] == 'avg' # We cannot simply use split because class names can have spaces. So instead # figure the width of the class field by looking at the indentation of the # precision header cls_field_width = len(header) - len(header.lstrip()) # Now, collect all the class names and score in a dict def parse_line(l): """Parse a line of classification_report""" cls_name = l[:cls_field_width].strip() precision, recall, fscore, support = l[cls_field_width:].split() precision = float(precision) recall = float(recall) fscore = float(fscore) support = int(support) return (cls_name, precision, recall, fscore, support) data = collections.OrderedDict() for l in cls_lines: ret = parse_line(l) cls_name = ret[0] scores = ret[1:] data[cls_name] = scores # average data['avg'] = parse_line(avg_line)[1:] return data
1c53663a06956393970bdf559415c2dde3fa8576
Zappp/ADS
/Euclid's algorithm.py
273
3.625
4
import math def euclid_algorithm(a, b): if b == 0: return a, 1, 0 else: d, x, y = euclid_algorithm(b, a % b) d, x, y = d, y, x - math.floor(a // b) * y return d, x, y d, x, y = euclid_algorithm(35, 50) print(x) print(y) print(d)
7a534ee72ca231860ab6ae0e6000d822f0354d5f
luisfeldma/python-study
/felipe14.py
197
3.8125
4
t1 = int(input("Digite o primeiro termo de uma PA: ")) razão = int(input("Digite a razão dessa PA: ")) for c in range(t1, (t1 + (10 * razão)), razão): print(c, end=" -> ") print("Acabou!")
b29b954ef68f983fe37967283a5cb461a8ad6b10
Hasil-Sharma/Spoj
/primes.py
1,756
4
4
def pow(base, exponent, mod): """\ Modular exponentiation through binary decomposition. We use the same technique as for the binary exponentiation above in order to find the modulo of our very large exponent and an arbitrary integer mod. """ exponent = bin(exponent)[2:][::-1] x = 1 power = base % mod for i in range(0, len(exponent)): if exponent[i] == '1': x = (x * power) % mod power = (power ** 2) % mod return x import random _mrpt_num_trials = 5 # number of bases to test def is_probable_prime(n): assert n >= 2 # special case 2 if n == 2: return True # ensure n is odd if n % 2 == 0: return False # write n-1 as 2**s * d # repeatedly try to divide n-1 by 2 s = 0 d = n-1 while True: quotient, remainder = divmod(d, 2) if remainder == 1: break s += 1 d = quotient assert(2**s * d == n-1) # test the base a to see whether it is a witness for the compositeness of n def try_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True # n is definitely composite for i in range(_mrpt_num_trials): a = random.randrange(2, n) if try_composite(a): return False return True # no base tested showed n as composite import sys input_data = sys.stdin.read() input_data = input_data.split('\n') input_data.remove('') input_data = map(int,input_data) t = (input_data[0]) index = 1 while index <= t : num = input_data[index] if is_probable_prime(num): print "YES" else: print "NO" index +=1
4fff70f6d083889fb8e4f75366bd0825e5b45988
sunshineatnoon/LeetCode
/500KeyboardRow.py
1,906
3.65625
4
############################## Native Solution ######################### # using dict to check if every character in a word maps to the same number # # Time taken: 39 ms/77.38% ############################################################################ class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ Row1 = ['q','w','e','r','t','y','u','i','o','p'] Row2 = ['a','s','d','f','g','h','j','k','l'] Row3 = ['z','x','c','v','b','n','m'] dic = {} for a in Row1: dic[a] = 1 for a in Row2: dic[a] = 2 for a in Row3: dic[a] = 3 ans = [] for w in words: backup = w w = w.lower() isSameRow = True prev = dic[w[0]] for i in range(1,len(w)): if(prev != dic[w[i]]): isSameRow = False prev = dic[w[i]] if(isSameRow): ans.append(backup) return ans ############################## Solution II: set ########################## # put each row in the keyboard into a set, if all characters in a word comes # # from the same row, then the word should be a subset of a set of a row # # Time taken: 52ms/26.52% # ############################################################################## class Solution(object): def findWords(self, words): ans = [] Row1 = set('qwertyuiop') Row2 = set('asdfghjkl') Row3 = set('zxcvbnm') for word in words: w = set(word.lower()) if w.issubset(Row1) or w.issubset(Row2) or w.issubset(Row3): ans.append(word) return ans s = Solution() print(s.findWords(["Hello", "Alaska", "Dad", "Peace"]))
f24e893b489b21f5f776aaf2eb14328b14f33550
qaqmander/AITMCLab
/lab2/lab2.py
3,750
4.1875
4
# Welcome to lab2, let's go through some grammars in python2 # We use keyword 'assert' to check something assert 1 == 1 # Nothing happened # assert 1 == 2 # program will exits when executing this line # You have a string, remember to use '\' to escape special character a = 'I\'m a string' # or a = "I'm a string" # Apply function 'len' to get length of string print len(a) # 12 # Use '[' ']' to slice a string print a[0] # 'I' print a[-1] # 'g' print a[-3] # 'i' print a[4:7] # 'a s' print a[:3] # "I'm" print a[-5:] # 'tring' print a[4:10:2] # 'asr' print a[::-1] # What's this??? # Tip! How to judge Palindrome string? # Notice: Here we define our own function with keyword 'def' # and control return value with keyword 'return' def judge_palindrome(s): if s[::-1] == s: return True else: return False assert judge_palindrome('ababa') == True assert judge_palindrome('abcab') == False # Concatenate string as you like a = a + '!!!!!' print a # I'm a string!!!!! # You have a list: A list is a list of things (like array in C-language) a = [1, 2, 3, 4] print len(a) # 4 # Use 'for' to go through all element of a list for i in range(len(a)): print a[i] # 1 # 2 # 3 # 4 # Use 'append' to add new element to the end of a list a.append(5) a.append(6) # Use '+' to add another list to a list a = a + [7, 8, 9, 10] # You can print a list directly! print a # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Lab2 a, b = 5, 12 x = 7 y = (a * x + b) % 26 # encryption print x, y # 7 21 from AITMCLab.libnum import invmod a_1 = invmod(a, 26) assert a * a_1 % 26 == 1 # a_1 is a^{-1} % 26!!! xx = a_1 * (y - b) % 26 # decryption assert x == xx print x, y, xx # 7 21 7 # Affine cryptography def affine(message, a, b): # y = ax + b (mod 26) cipher = '' for char in message: if 'a' <= char <= 'z': now_cipher = (a * (ord(char) - ord('a')) + b) % 26 cipher += chr(now_cipher + ord('a')) elif 'A' <= char <= 'Z': now_cipher = (a * (ord(char) - ord('A')) + b) % 26 cipher += chr(now_cipher + ord('A')) else: cipher += char return cipher # Affine cryptography - 1: # Try to findout what happen and message! message = 'flag{**********}' a, b = 7, 12 cipher = affine(message, a, b) print cipher # vlmc{ko_lgdo_MQPSALmt_doby_swaj!!} # Affine cryptography - 2: # Try to findout what happen and message without a & b!! message = 'flag{**********}' a, b = ??, ?? # We don't have a & b now !!!! hahahaha cipher = affine(message, a, b) print cipher # kyhv{pz_mzhyyl_yfez_HRIJDYhs_ezml_jtdg!!} # Hill cryptography (optional) # May be difficult! Try to findout what happen and message message = 'flag{************}' # 2-dimentional matrix A = [[1, 2, 3, 4], [0, 3, 4, 5], [1, 5, 8, 10], [2, 10, 15, 8]] B = [6, 9, 12, 15] # A_1 = [[21, 2, 2, 15], [21, 4, 1, 15], [6, 6, 8, 19], [19, 19, 19, 7]] # / 157 104 104 130 \ / 1 0 0 0 \ # | 182 131 130 156 | | 0 1 0 0 | # A * A_1 = | 364 260 261 312 | == | 0 0 1 0 | (mod 26) # \ 494 286 286 521 / \ 0 0 0 1 / buf = '' cipher = '' for char in message: if 'a' <= char <= 'z': buf += char else: cipher += char if len(buf) == 4: X = [] for ch in buf: X.append(ord(ch) - ord('a')) Y = [0, 0, 0, 0] for i in range(4): for j in range(4): Y[i] = Y[i] + A[i][j] * X[j] Y[i] = Y[i] + B[i] Y[i] = Y[i] % 26 for i in range(4): cipher += chr(Y[i] + ord('a')) buf = '' print cipher # fucb{uzpexfrygluh}
a5a360e0f8169d621b970af944331b747aef24c5
bi0morph/automate-the-boring-stuff-with-python
/chapter10.debugging/coinToss.py
930
3.671875
4
#! /usr/bin/env python3 import random import logging logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') logging.debug('Start program') guess = '' while guess not in ('heads', 'tails'): print('Guess the coin toss! Enter heads or tails:') guess = input() logging.debug('User did input: %s' % guess) toss = ['tails', 'heads'][random.randint(0, 1)] logging.debug('flip the coin: %s' % toss) if toss == guess: logging.debug('User guessed') print('You got it!') else: logging.debug('User did not guess') print('Nope! Guess again!') guess = input() logging.debug('User did input one more time: %s' % guess) if toss == guess: logging.debug('User guessed') print('You got it!') else: logging.debug('User did not guess even in second time') print('Nope. You are really bad at this game.') logging.debug('End program')
54003d9d265479162f8ca5e37da7ca7b84904158
1huangjiehua/ArithmeticPracticalTraining
/201826404105黄杰华算法实训/任务一(二分查找(循环)).py
1,007
3.59375
4
def erfenfa(lis, nun): left = 0 right = len(lis) - 1 while left <= right: #循环条件 mid = (left + right) // 2 #获取中间位置,数字的索引(序列前提是有序的) if num < lis[mid]: #如果查询数字比中间数字小,那就去二分后的左边找, right = mid - 1 #来到左边后,需要将右变的边界换为mid-1 elif num > lis[mid]: #如果查询数字比中间数字大,那么去二分后的右边找 left = mid + 1 #来到右边后,需要将左边的边界换为mid+1 else: return mid #如果查询数字刚好为中间值,返回该值得索引 return -1 #如果循环结束,左边大于了右边,代表没有找到 lis = [15,58,68,94,12,45,35,36,14,54] print(lis) lis.sort() print(lis) while 1: num = int(input('输入要查找的数:')) res = erfenfa(lis, num) print(res) if res == -1: print('未找到!') else: print('找到!')
b15b9468b254019ddec88617f0071649634921a1
abdelrahman-wael/LeetCode-30-DaysChallenge
/week 1/day 7/Determine if String Halves Are Alike.py
370
3.59375
4
class Solution: def halvesAreAlike(self, s: str) -> bool: vowels = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0, 'A':0, 'E':0, 'I':0, 'O':0, 'U':0} mid =len(s)//2 equal = 0 for i in range(mid): if s[i] in vowels: equal += 1 if s[i+mid] in vowels: equal -=1 return equal == 0
fca0875e68a5ddf3d0ffcb6e1603efb7dafa6315
aizhansapina/BFDjango
/week1/informatics/For loop/CFc.py
122
3.96875
4
import math a = int(input()) b = int(input()) for num in range (a, int(math.sqrt(b)) + 1): print(num * num, end = " ")
8422ba401258dc2ae6e48d755120bdebea442d75
chongliw/algorithm_py
/fun/mostfrequentchar.py
542
3.984375
4
def most_freq(str, n): dict = {} punc = [' ', ',', '.', '-', '?', ';' , ':'] for char in str: if not char in punc: if char in dict: dict[char] += 1 else: dict[char] = 1 keys = [] for key in dict: if dict[key] >= n: keys.append(key) keys.sort() skey = "" for char in keys: skey += char return skey if __name__ == '__main__': str = 'today is that saturday' n = 3 keys = most_freq(str, n) print(keys)
baf5eca94e8e5c3ea23f673d1732ef219de97852
arunachalamev/PythonProgramming
/Algorithms/LeetCode/L1233removeSubFolders.py
1,053
3.5
4
# Version 1 def removeSubfolders1(folder): folder.sort() res = [folder[0]] prev_folder = folder[0] prev_folder_slash = prev_folder +'/' prev_folder_n = len(prev_folder_slash) for i in range (1,len(folder)): if ((folder[i])[:prev_folder_n] == prev_folder_slash): pass else: res.append(folder[i]) prev_folder = folder[i] prev_folder_slash = prev_folder +'/' prev_folder_n = len(prev_folder_slash) return res # Version 2 def removeSubfolders2(folder): folder.sort() ans = [] for f in folder: if not ans or f[: 1 + len(ans[-1])] != ans[-1] + '/': # need '/' to ensure a parent. ans.append(f) return ans print(removeSubfolders1(["/a","/a/b","/c/d","/c/d/e","/c/f"])) # print(removeSubfolders(["/a","/a/b/c","/a/b/d"])) # print(removeSubfolders(["/a/b/c","/a/b/ca","/a/b/d"])) # print(removeSubfolders(["/abc/de","/abc/dee","/abc/def","/abc/def/gh","/abc/def/ghi","/abc/def/ghij","/abc/def/ghijk","/abc/dez"]))
f081fc76f7ff630bbedc802b058af20fbc628ada
jarek-prz/pythonalx
/kolekcje/slowniki.py
2,192
3.5
4
#list [] #tuple() #dict{} # dict print(dict()) pol_ang = { #"klucz":"wartosc" "klucz":"key", "pies": "dog", "pies": "dog" } print(pol_ang) print(pol_ang["pies"]) if "dog" in pol_ang: print(pol_ang["pies"]) print(pol_ang.get("dog")) # jeżeli klucza w slowniku n ie ma to dostajemy wartosc None print(pol_ang.get("dog", "Brak takiergo hasla")) # jeżeli klucza w slowniku n ie ma to dostajemy wartosc "Brak takiergo hasla" print(pol_ang.get("pies", "Brak takiergo hasla")) # nowy klucz w slowniku pol_ang["kot"]="cat" print(pol_ang) # kluczem moze byc int pol_ang[1]="jeden" print(pol_ang) # tupla tez moze byc kluczem print(pol_ang.keys()) # klucze (lista kluczy) print(pol_ang.values()) # wartosci (lista wartosci) print(pol_ang.items()) # klucz_wartosci (lista tupli) # inne tworzeenie slownika print(dict(krowa="cow", dom="house")) # slownik tworzony z listy tupli print(dict([("krowa","cow"), ("dom", "house")])) #usuwanie ze slownika print(pol_ang.pop("pies")) print(pol_ang) print(pol_ang.popitem()) print(pol_ang) # set {} kolekcja unikalnych nieuporządkowanuych wartości zbior = {1,2,3,4} # taki jakby slownuik, ale zlozony z samych wartosci print(zbior, type(zbior)) print(dir(zbior)) zbior2= {1,"a", 2, "b", 3, "z"} print(zbior2) zbior2.add(9) print(zbior2) lista= [1,2,2,2,2,2,2,3,3,3,3,3,] # po zrzutowaniu listy na set mamy zbior unikalnych wartosci print(set(lista)) # operacje na setach podobne do operacji na zbiorach # przy probie dodania nowego elelmnyu takiego jak ju zbyl to nie bedzie bledu, ale sie nie doda => musz a bytć unikalne A = {1,2,3,4} B = {3,4,5,6} # suma zbiorow print("suma zbiorow", A|B ) print("suma zbiorow", A.union(B) ) # roznica zbiorow print("suma zbiorow", A-B ) print("suma zbiorow", A.difference(B) ) # częśc wspolna print("suma zbiorow", A&B ) print("suma zbiorow", A.intersection(B) ) # roznica print("suma zbiorow", A-B ) print("suma zbiorow", A.difference(B) ) # roznica symetryczna - suma zbiorów minus czesc wspolna print("suma zbiorow", A ^ B ) print("suma zbiorow", A.symmetric_difference(B) ) # czy cos jest podzbiorem innego zbioru C={1,2} print("Czy jest podzbiorem:", C.issubset(A) )
a9c2da95b60a92e08a8047f7639d0e0c5759e406
sumittal/coding-practice
/python/find_equilibrium.py
1,556
3.734375
4
""" Equilibrium index of an array Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an arrya A: A[0] = -7, A[1] = 1, A[2] = 5, A[3] = 2, A[4] = -4, A[5] = 3, A[6]=0 3 is an equilibrium index, because: A[0] + A[1] + A[2] = A[4] + A[5] + A[6] 6 is also an equilibrium index, because sum of zero elements is zero, i.e., A[0] + A[1] + A[2] + A[3] + A[4] + A[5]=0 7 is not an equilibrium index, because it is not a valid index of array A. 1) Initialize leftsum as 0 2) Get the total sum of the array as sum 3) Iterate through the array and for each index i, do following. a) Update sum to get the right sum. sum = sum - arr[i] // sum is now right sum b) If leftsum is equal to sum, then return current index. c) leftsum = leftsum + arr[i] // update leftsum for next iteration. 4) return -1 // If we come out of loop without returning then // there is no equilibrium index """ def equilibrium(arr): # finding the sum of whole array total_sum = sum(arr) left_sum = 0 for i, num in enumerate(arr): # total_sum is now right sum # for index i total_sum -= num if left_sum == total_sum: return i left_sum += num # If no equilibrium index found, # then return -1 return -1 # driver code arr = [-7, 1, 5, 2, -4, 3, 0] print ('First equilibrium index is ', equilibrium(arr))
f46110aed02847ed8c78a91b8ddb4da6314bf61b
ibsom/Snake
/Diagne.py
12,784
3.609375
4
from tkinter import * from random import randrange, randint from time import sleep class Grille(Canvas): """ Spécialisation et configuration d'un Canvas tkinter pour la gestion d'une grille comportant nb_lig lignes et nb_colonnes, des marges haut, droite, bas, gauche potentiellement différentes une taille de case de largeur et de longueur potentiellement différentes """ NORD, EST, SUD, OUEST = 0, 1, 2, 3 # les 4 directions de la grille en attributs de classe def __init__(self, fen, nb_lig, nb_col, t_marges=(0, 0, 0, 0), t_case=(20, 20), **kw): """ Création des attributs privés : - nb_lig et nb_col : nombre de lignes et de colonnes de la grille - nb_cases, t_case : nombre de cases et taille en pixel de la largeur et hauteur d'une case - t_marges : valeur des marges haut, droite, bas puis gauche - width, height : largeur et hauteur en pixel de la grille """ self.__nb_lig= nb_lig self.__nb_col = nb_col self.__nb_cases = nb_lig * nb_col self.__t_case = t_case self.__t_marges = t_marges #pourquoi ne pas utiliser le qui est dans les parametres? self.__width = self.__t_case[1] * nb_col self.__height = self.__t_case[0] * nb_lig Canvas.__init__(self, fen, width = self.__width, height = self.__height, bg = "black", **kw) def get_nb_lig(self): return self.__nb_lig """ Accesseur en lecture du nombre de lignes""" def get_nb_col(self): return self.__nb_col """ Accesseur en lecture du nombre de colonnes""" def get_nb_cases(self): return self.__nb_cases """ Accesseur en lecture du nombre de cases""" def case_to_lc(self, num_case): return num_case // self.__nb_col, num_case % self.__nb_col """Calcul des numéros de ligne et de colonne à partir du numéro de case""" def lc_to_case(self, num_lig, num_col): #redondance de numéro de case return num_lig * self.__nb_col + num_col """Calcul du numéro de case à partir des numéros de ligne et de colonne""" def case_to_xy(self, num_case): x = self.__t_marges[0] + (num_case%self.__nb_col)*self.__t_case[0] y = self.__t_marges[1] + (num_case//self.__nb_col)*self.__t_case[1] return x, y """Calcul des coordonnées en pixel à partir du numéro de case""" def xy_to_case(self, x, y): return (y//self.__t_case[0])*self.__nb_col + (x//self.__t_case[1]) """Calcul du numéro de case à partir des coordonnées en pixel""" def xy_to_lc(self, x, y): return (x // self.__t_case[0])-1, (y // self.__t_case[1])-1 """Calcul des numéros de ligne et de colonne à partir des coordonnées en pixel""" def lc_to_xy(self, num_lig, num_col): return num_col * self.__t_case, num_lig * self.__t_case """Calcul des coordonnées en pixel à partir des numéros de ligne et de colonne""" def next_case(self, num_case, direction, nb_cases=1): # sur un tore """Calcul du numéro de case suivant lorque nb cases sont ajoutés dans une direction donnée Le déplacement d'effectue sur la grille considérée comme un tore (la sortie du serpent par un côté entraine la sortie du serpent par le côté opposé.""" lig, col= self.case_to_lc(num_case) # tuple(ligne, colonne) coordoné de case if direction == Grille.NORD: if lig == 0: lig = self.__nb_lig-1 return self.lc_to_case(lig,col) else: return self.lc_to_case(lig-1,col) elif direction == Grille.EST: if col == self.__nb_col-1: col = 0 return self.lc_to_case(lig,col) else: return self.lc_to_case(lig,col+1) elif direction == Grille.SUD: if lig == self.__nb_lig-1: lig = 0 return self.lc_to_case(lig,col) else: return self.lc_to_case(lig+1,col) else: #OUEST if col == 0: col = self.__nb_col-1 return self.lc_to_case(lig,col) else: return self.lc_to_case(lig,col-1) def show_case(self, num_case, color= "#f40a0a"): """ crée et retourne l'identifiant d'un rectangle de couleur color pour visualiser la case de numéro num_case""" x,y=self.case_to_xy(num_case) return self.create_oval(x, y, x + self.__t_case[0], y + self.__t_case[0] , fill = color) class GrilleSnake(Grille): """ Spécialisation et configuration d'une Grille pour la gestion d'une grille comportant nb_lig lignes et nb_colonnes, des marges haut, droite, bas, gauche identiques une taille de case de largeur et de longueur identiques et la gestion d'un serpent """ TWO_KEYS_MODE = True # paramétrage du mode de jeu def __init__(self, fen, nb_lig, nb_col, t_marges=0, t_case=5, color_snake='green', **kw): Grille.__init__(self,fen, nb_lig, nb_col) """ En plus des attributs hérités, création des attributs publics : color_snake : couleur du serpent - t_snake : nombre de cases du serpent - dir_snake : direction du serpent - pos_snake : numéro de case de la tête du serpent - snake : liste de liste de deux éléments [case élément serpent, identifiant du dessin de l'élément] - speed_snake : vitesse du serpent Le constructeur dessine le serpent dans le Canvas et associe à tous les éléments graphiques les éléménts graphiques les évènements clavier et souris """ self.color_snake = color_snake self.t_snake = 6 self.dir_snake = randrange(0,3) self.pos_snake = randint(0,self.get_nb_cases()) self.snake = [] for i in range(self.t_snake): num_case = self.pos_snake - i x,y = self.case_to_xy(num_case) self.snake.append([num_case, self.create_oval(x,y,x+20, y+20, fill = self.color_snake)]) self.speed_snake = 5 def turn_left_snake(self): """ Mode de jeu deux déplacement relatif handler de l'évènement bouton gauche ou flêche gauche modifie la direction de 180° vers la gauche""" if self.dir_snake == Grille.NORD: self.dir_snake = Grille.OUEST elif self.dir_snake == Grille.OUEST: self.dir_snake = Grille.SUD elif self.dir_snake == Grille.SUD: self.dir_snake = Grille.OUEST else: self.dir_snake = Grille.NORD def turn_right_snake(self): """ Mode de jeu deux déplacement relatif handler de l'évènement bouton droit ou flêche droite modifie la direction de 180° vers la droite""" if self.dir_snake == Grille.NORD: self.dir_snake = Grille.EST elif self.dir_snake == Grille.EST: self.dir_snake = Grille.SUD elif self.dir_snake == Grille.SUD: self.dir_snake = Grille.EST else: self.dir_snake = Grille.NORD def turn_snake(self, event): print(event.keysym) """ Mode de jeu deux déplacement absolu handler des évènements clavier haut, droite, bas ou gauche définit la direction dans le sens de la touche clavier choisie""" if self.dir_snake == Grille.NORD: if event.keysym == "Left": self.turn_left_snake() elif event.keysym == "Right": self.turn_right_snake() else: pass elif self.dir_snake == Grille.EST: if event.keysym == "Down": self.turn_right_snake() elif event.keysym == "Up": self.turn_left_snake() else: pass elif self.dir_snake == Grille.SUD: if event.keysym == "Left": self.turn_left_snake() elif event.keysym == "Right": self.turn_right_snake() else: pass else: if event.keysym == "Up": self.turn_right_snake() elif event.keysym == "Down": self.turn_left_snake() else: pass def crawling_snake(self): num_case = self.t_snake*[0] #liste de liste de la nouvelle et acienne position de chaque element du snake for i in range(self.t_snake): if i == 0: num_case[i] = self.snake[i][0] self.snake[i][0] =self.next_case(self.snake[i][0], self.dir_snake) x,y = self.case_to_xy(self.snake[i][0]) self.pos_snake = self.snake[i][0] else: num_case[i] = self.snake[i][0] self.snake[i][0] = num_case[i-1] x,y = self.case_to_xy(self.snake[i][0]) self.snake[i] = [self.snake[i][0],self.snake[i][1] ] self.coords(self.snake[i][1], x, y, x+20, y+20) """Avancement du serpent (déplacement de la queue vers la case suivant la tete dans la direction courante)""" class FenApp(Tk): """ Spécialisation et configuration de la fenêtre d'application Les attributs de classe fixent le nombre de lignes et de colonnes, la valeur des marges et de la taille en pixel d'une case, le jeu de couleurs utilisées dans l'application (fond de la grille et couleur du serpent) """ NB_LIG = 30 NB_COL = 50 MARGES = 0 T_CASE = 5 COULS = {'fond': 'black', 'serpent': 'orange'} def __init__(self): """Placement des éléments d'interface et création des attributs publics : - monde : il s'agit d'une GrilleSnake initialisée grâce aux attributs de classe - b_launch : bouton pour lancer le déplacement du serpent - b_leave : bouton pour quitter l'application - end_game, moving : booléens pour savoir si le jeu est terminé ou si le serpent est en mode déplacement Le constructeur associera également un handler à l'évènement barre espace pour gérer la pause ou la reprise des déplacements du serpent""" Tk.__init__(self) self.monde = GrilleSnake(self, nb_lig = FenApp.NB_LIG, nb_col = FenApp.NB_COL, t_marges=FenApp.MARGES, t_case=FenApp.T_CASE, color_snake = FenApp.COULS["serpent"] ) self.monde.pack(side = TOP, padx = FenApp.MARGES, pady = FenApp.MARGES) self.monde.configure(bg = FenApp.COULS["fond"]) self.panel = Frame(self, width = 100, height = 50 ) self.b_lunch = Button(self.panel, text='Lancer', command=self.launch) self.b_lunch.pack(side = LEFT) self.bind("<space>", self.stop) self.bind("<KeyPress>", self.monde.turn_snake ) self.b_stop = Button(self.panel, text='Pause', command =self.stop ) self.b_stop.pack(side = LEFT, padx = 10) self.b_leave = Button(self.panel, text='Quitter', command=self.leave) self.b_leave.pack(side = LEFT) self.panel.pack(side = BOTTOM, padx = 150) self.end_game = 0 def launch(self): print(self.end_game) while 1: if not self.end_game: self.monde.crawling_snake() self.b_lunch.configure(state = DISABLED) sleep(self.monde.speed_snake / 50) else: break self.update() """handler du bouton de lancement. Réalise une boucle d'avancement du serpent tant que le jeu n'est pas terminé et si le serpent est en mode déplacement. La fonction devra également desactiver la possibilité d'actionner le bouton de lancement. Attention, les éléments graphiques sont mis à jour par défaut APRES la boucle. Pour que les modifications tkinter soient visibles PENDANT la boucle il faut utiliser la méthode update() sur la fenêtre.""" def stop(self, event = 0): """handler de la touche space qui inverse le mode déplacement du serpent""" if not self.end_game: self.b_stop.configure(text = "Reprendre") self.end_game = 1 else: self.end_game = 0 self.b_stop.configure(text = "Pause") self.launch() def leave(self): """ handler du bouton qui permet de quitter l'application""" self.destroy() if __name__ == "__main__": """ lancement de l'application et de la boucle évenementielle""" FenApp().mainloop()
d246546b8f17a35cd2774942ce2b5305dbea610c
domtriola/software-notes
/languages/python/basic-exercises/exercises.py
229
4.0625
4
# Extending list (not idiomatic Python) class MyList(list): def each(self, func): for i in self: func(i) a = MyList([1, 2, 3, 4]) b = MyList() a.each(lambda x: b.append(x * 2)) print(b) # => [2, 4, 6, 8]
e5831b5f3b1e25a1954d26c328a71f9565706c53
wjdghrl11/python_nadoBasic
/24.py
403
3.640625
4
# 출석번호가 1 2 3 4 앞에 100을 붙이기로함 101 102 103 104[한줄 for문] students = [1,2,3,4,5] print(students) students = [i+100 for i in students] print(students) # 학생 이름을 길이로 변환 students = ["iron", "thor", "groot"] students = [len(i) for i in students] print(students) # 학생 이름을 대문자로 변환 students = [i.upper() for i in students] print(students)
a0dbfe780161be15f403f2a0fb01eb957ab2ffa7
GunnerX/leetcode
/链表汇总/面试题18. 删除链表的节点.py
1,154
4
4
# 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。 # # 返回删除后的链表的头节点。 # # 注意:此题对比原题有改动 # # 示例 1: # # 输入: head = [4,5,1,9], val = 5 # 输出: [4,1,9] # 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9. # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, head: ListNode, val: int) -> ListNode: if not head: return None sen = ListNode(None) sen.next = head p = sen while p.next: if p.next.val == val: t = p.next p.next = t.next t.next = None break p = p.next return sen.next
390398be7d97efd4b50914bd79757c160c81314d
comorina/Ducat_class_code
/p31.py
80
3.875
4
a=float(input("enter 1st num:")) b=float(input("enter 2nd num:")) print(a+b)
b1f626048f03f39f0b05398e0ebd0ecc679c5b01
2100030721/Hackerrank-Artificial-Intelligence
/Probability-Statistics-Foundations/basic-probability-puzzles-3.py
1,101
3.609375
4
# Objective # In this challenge, we practice calculating probability. # Task # There are 3 urns: X, Y and Z. # Urn X contains 4 red balls and 3 black balls. # Urn Y contains 5 red balls and 4 black balls. # Urn Z contains 4 red balls and 4 black balls. # One ball is drawn from each urn. What is the probability # that the 3 balls drawn consist of 2 red balls and 1 black ball? # Challenge: https://www.hackerrank.com/challenges/basic-probability-puzzles-3 # Reference: https://en.wikipedia.org/wiki/Probability # GitHub: https://github.com/Murillo # Developer: Murillo Grubler # Combinations #Urn X Urn Y Urn Z #red red black #black red red #red black red x_prob_red = 4/7 x_prob_black = 3/7 y_prob_red = 5/9 y_prob_black = 4/9 z_prob_red = 1/2 z_prob_black = 1/2 # We have multiplied the possibilities first_combination = x_prob_red * y_prob_red * z_prob_black second_combination = x_prob_black * y_prob_red * z_prob_red third_combination = x_prob_red * y_prob_black * z_prob_red # Result = 0.40476190476190477 = 17/42 print (first_combination + second_combination + third_combination)
a3a4c1dd15a13f440c1748bd28724a25a4c9d01e
shanidata78/Learning
/test.py
152
3.625
4
a = [11,22,33] print 22 in a b = [] b.append('aaa') b.append('bbb') b.append('ccc') b.append('ddd') b.append('eee') print b for item in b: print item
5c10c65b6cc2182bc8b11396a908f6ce8af04195
Vlas7528/Tensor-Homework
/lesson-5/6 - калькулятор базовых операций.py
3,386
4.1875
4
from decimal import Decimal result = [] def plus(n1, n2): n3 = n1 + n2 result.append(n3) return n3 def minus(n1, n2): n3 = n1 - n2 result.append(n3) return n3 def division(n1, n2): try: n3 = n1 / n2 except Exception as e: # print(e) print('На ноль делить нельзя!') calc() n3 = n1 / n2 result.append(n3) return n3 def multiplication(n1, n2): n3 = n1 * n2 result.append(n3) return n3 def exponentiation(n1, n2): n3 = n1 ** n2 result.append(n3) return n3 def calc(): while True: x1 = input ('Введите первое число:\n') x2 = input ('Введите второе число:\n') try: x1 = Decimal(x1) x2 = Decimal(x2) break except Exception as e: # print(e) - раскомментировать чтобы выводить тип ошибки print('Неверный формат данных') while True: opr = input ('Введите требуемую операцию:\n') if opr == '+': print(f'Результат: {plus(x1, x2)}') break elif opr == '-': print(f'Результат: {minus(x1, x2)}') break elif opr == '/': print(f'Результат: {division(x1, x2)}') break elif opr == '*': print(f'Результат: {multiplication(x1, x2)}') break elif opr == '**': print(f'Результат: {exponentiation(x1, x2)}') break else: print('Неверный код операции!') count = int(0) menu = True while menu == True: while True: x3 = input ('Введите следущее число (Enter чтобы завершить вычисления):\n') if not x3: print('До свидания...') menu = False break try: x3 = Decimal(x3) break except: print('Неверный формат данных') if menu == False: break while True: opr = input('Введите требуемую операцию:\n') if opr == '+': print(f'Результат: {plus(result[count], x3)}') break elif opr == '-': print(f'Результат: {minus(result[count], x3)}') break elif opr == '/': print(f'Результат: {division(result[count], x3)}') break elif opr == '*': print(f'Результат: {multiplication(result[count], x3)}') break elif opr == '**': print(f'Результат: {exponentiation(result[count], x3)}') break else: print('Неверный код операции!') count += 1 print(f'Расчёты завершены. История вычислений:{result}') calc()
1e19d66fdc4e30bb9f2cc44a4aca750664a412a6
idan57/PTML-Final_Proj
/data_containers/task.py
1,269
3.703125
4
import logging from threading import Thread class TaskResult(object): """ A class for a task's result """ def __init__(self): self.verdict = False self.result_value = None class Task(object): """ A class to represent a task """ _thread: Thread result: TaskResult def __init__(self, name, func, args=None): """ :param name: name of the task :param func: the method for executing the class :param args: any arguments needed to start the task """ self.name = name self._thread = None self._func = func self._args = args self.running = True self.result = None def _task_execution(self): logging.info(f"{self.name} is now running") if self._args: self.result = self._func(*self._args) else: self.result = self._func() self.running = False logging.info(f"{self.name} is now done!") def start_task(self): """ Start executing the task """ logging.info(f"Starting task: {self.name}") self._thread = Thread(target=self._task_execution) self._thread.start() logging.info(f"Started task: {self.name}")
505192152469949f116759400c72183b299c8625
gbarboteau/Advent-of-Code-2020
/Day10/main.py
1,003
3.828125
4
#You can find the puzzle here: https://adventofcode.com/2020/day/10 import sys #The file containing every numbers filename = sys.argv[-1] # ===================== # PART 1 # ===================== #Count the number of different jolt differences def count_jolt_differences(adaptaters_list): jolt_dif_list = [0, 0, 0] my_adaptaters_list = adaptaters_list my_adaptaters_list.sort() my_adaptaters_list.insert(0, 0) my_adaptaters_list.append(my_adaptaters_list[-1] +3) for i in range(0, len(my_adaptaters_list) -1): my_diff = my_adaptaters_list[i +1] - my_adaptaters_list[i] if my_diff >= 1 and my_diff <= 3: jolt_dif_list[my_diff -1] += 1 return jolt_dif_list #Get the expenses and put it in an array def get_adaptaters(): with open(filename) as f: listExpenses = f.read().splitlines() return list(map(int, listExpenses)) print(count_jolt_differences(get_adaptaters())[0] * count_jolt_differences(get_adaptaters())[2])
9c689e516aca0a26b910c8894dbc7c58bdb40523
YorkFish/git_study
/ProgrammerAlgorithmInterview/Chapter01/01_11_determine_if_two_linked_lists_cross_02.py
3,272
4.15625
4
#!/usr/bin/env python3 #coding:utf-8 # import 01_06_check_if_linked_list_has_ring_03 as ring # 模块名带了下划线,不好使 class LNode(object): def __init__(self, x=None): self.val = x self.next = None # 将 head1 的尾部链到 head2 的头部,形成一个有环单链表,然后可套用 01_06 的解法 def concatenate(head1, head2): cur = head1.next while cur.next: cur = cur.next cur.next = head2.next return None def isLoop(head): """ 方法功能:判断单链表是否有环 输入参数:head: 链表头结点 返回值:无环:None;有环:slow 与 fast 相遇的结点 """ if head is None or head.next is None: return None slow = fast = head.next while fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: return slow return None def findLoopNode(head, meet_node): """ 方法功能:找出环的入口点 输入参数:head: 链表头结点;meet_node: fast 与 slow 相遇的结点 返回值:fast 与 slow 相遇的结点 """ first = head.next second = meet_node while first is not second: first = first.next second = second.next return first def constructLinkedList(nums): """ 方法功能:创建单链表 输入参数:nums: 作为链表结点的数据 返回值:head: 链表头结点;tail: 链表尾结点 """ head = LNode() cur = head for num in nums: tmp = LNode() tmp.val = num cur.next = tmp cur = tmp tail = cur return head, tail # 直接返回 (head, cur) 也行,不过这样直观一点 def printLinkedList(head): """ 打印单链表 """ print("head->", end='') cur = head.next while cur: print(cur.val, end="->") cur = cur.next print("None") return None if __name__ == "__main__": head1, tail1 = constructLinkedList([1, 2, 3, 4]) head2, tail2 = constructLinkedList([5, 6, 7]) head3, tail3 = constructLinkedList([8, 9, 10]) # tail3 没有用 tail1.next = head3.next tail2.next = head3.next print("head1:", end=' ') printLinkedList(head1) print("\nhead2:", end=' ') printLinkedList(head2) """ head1->1->2->3->4 head1->1->2->3->4 \ \ ->8->9->10->None => ->8->9->10 / / | head2->5->6->7- 5->6->7- | | | --------<-------- """ concatenate(head1, head2) meet_node = isLoop(head1) if meet_node: # 若只要判断是否交叉,这里就够了;不过 meet_node 不是交点,而是快慢指针在环内的相遇点 print(f"\nTwo linked lists cross. The intersection value is {meet_node.val}.") # 若要找到交叉点,再加上这句 print(f"The intersection node's value is {findLoopNode(head1, meet_node).val}.") else: print("\nnon-intersect!")
6fde976d391c6f82a9f0b3601790755ef2cb3e5e
devmukul44/Play_Crawler
/model/thread_check.py
330
3.640625
4
import thread import time # Define a function for the thread def print_time(threadName): print threadName # Create two threads as follows try: thread.start_new_thread( print_time, ("Thread-1",) ) thread.start_new_thread( print_time, ("Thread-2",) ) except: print "Error: unable to start thread" while 1: pass
3d89bf736446d6b3a1d6b06a616a03e39594c9c7
Manoji97/Data-Structures-Algorithms-Complete
/Python/1_ProblemsolvingPatterns/1_frequencyCounter.py
310
3.53125
4
def FrequencyCounter(lst1, lst2): if len(lst1) != len(lst2): return False lst1_dict = {} for i in lst1: if i in lst1_dict: lst1_dict[i] += 1 else: lst1_dict[i] = 1 for i in lst2: if i not in lst1_dict: return False if lst1_dict[i] == 0: return False else: lst1_dict[i] -= 1 return True
0d2fa24c4814bb3b578a6c51209e15f4efbd435f
leehm00/pyexamples
/NUS_pyexercise/35.py
359
3.78125
4
# _*_ coding.utf-8 _*_ # 开发人员 : leehm # 开发时间 : 2020/7/1 18:42 # 文件名称 : 35.py # 开发工具 : PyCharm a = input() s = a.split() count = 1 for i in range(1, int(s[0])+1): if not (i % 3 == 0 or i % 5 == 0 or str(i).count('5') > 0 or str(i).count('3') > 0): print(i) count += 1 if count > int(s[1]): break
28595bc1247f7cdb9e2d594da389bfab99fee199
sculzx007/Python-practice
/小甲鱼/第九课 求100-999内水仙花数【没有理解】.py
1,056
3.78125
4
#coding=utf-8 # 原题 """ 编写一个程序,求 100~999 之间的所有水仙花数。 如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。 例如:153 = 1^3 + 5^3 + 3^3,因此 153 就是一个水仙花数。 """ # 个人答案 """ j = 0 k = 0 m = 0 i = 100* j + 10* k + m while 100 <= i <= 999: if i == j ** 3 + k ** 3 + m ** 3: print i, "是水仙数" i += 1 else: i += 1 print """ """ 输出结果:没有输出结果 """ # 参考答案 for i in range(100, 1000): sum = 0 temp = i while temp: sum = sum + (temp%10)**3 # 这是什么意思?? sum = sum + (个位数的立方)? temp //= 10  # //是浮点数的除法,等价于 temp = temp // 10 if sum == i: print i,"是水仙数"
fd63d47de1cf5682a3b53b215ae89bb10426ed29
turksoyomer/TicTacToe-AI
/codes/tictactoe.py
2,849
3.671875
4
# -*- coding: utf-8 -*- """ @author: turksoyomer """ class TicTacToe: def __init__(self): self.turn = 1 self.player1_marker = "X" self.player2_marker = "O" self.state = ["_", "_", "_", "_", "_", "_", "_", "_", "_"] self.winner = None self.action_list = list(range(9)) def reset(self): self.turn = 1 self.state = ["_", "_", "_", "_", "_", "_", "_", "_", "_"] self.winner = None def render(self): print("\n%s %s %s\n%s %s %s\n%s %s %s\n" % tuple(self.state)) def isValid(self, action): if not 0 <= action <= 8: return False if self.state[action] == "_": return True return False def step(self, action): if self.isValid(action): if self.turn == 1: self.state[action] = self.player1_marker elif self.turn == 2: self.state[action] = self.player2_marker done = self.check_winner() self.turn = 1 if self.turn == 2 else 2 return done return def check_winner(self): if self.turn == 1: if self.state[0] == self.state[4] == self.state[8] == self.player1_marker: self.winner = self.player1_marker return True elif self.state[2] == self.state[4] == self.state[6] == self.player1_marker: self.winner = self.player1_marker return True for i in range(0, 9, 3): if self.state[i+0] == self.state[i+1] == self.state[i+2] == self.player1_marker: self.winner = self.player1_marker return True for j in range(3): if self.state[j+0] == self.state[j+3] == self.state[j+6] == self.player1_marker: self.winner = self.player1_marker return True elif self.turn == 2: if self.state[0] == self.state[4] == self.state[8] == self.player2_marker: self.winner = self.player2_marker return True elif self.state[2] == self.state[4] == self.state[6] == self.player2_marker: self.winner = self.player2_marker return True for i in range(0, 9, 3): if self.state[i+0] == self.state[i+1] == self.state[i+2] == self.player2_marker: self.winner = self.player2_marker return True for j in range(3): if self.state[j+0] == self.state[j+3] == self.state[j+6] == self.player2_marker: self.winner = self.player2_marker return True if self.state.count("_") == 0: self.winner = "Tie" return True return False
8b706bfa2b809d02decf76cbf5c697cd2a8948ad
ridersw/Karumanchi--Data-Structures
/stackDeque.py
2,633
4.09375
4
#operations- #append(x) - Add x to the right side of the deque. #appendleft(x) - Add x to the left side of the deque. #clear()- Remove all elements from the deque leaving it with length 0. #copy() - Create a shallow copy of the deque. #count(x) - Count the number of deque elements equal to x. #extend(iterable) - Extend the right side of the deque by appending elements from the iterable argument. #extendleft(iterable) Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument. #index(x[, start[, stop]]) Return the position of x in the deque (at or after index start and before index stop). Returns the first match or raises ValueError if not found. #insert(i, x) - Insert x into the deque at position i. If the insertion would cause a bounded deque to grow beyond maxlen, an IndexError is raised. #pop() - Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError. #popleft() - Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError. #remove(value) - Remove the first occurrence of value. If not found, raises a ValueError. #reverse() - Reverse the elements of the deque in-place and then return None. #rotate(n=1) - Rotate the deque n steps to the right. If n is negative, rotate to the left. When the deque is not empty, rotating one step to the right is equivalent to d.appendleft(d.pop()), and rotating one step to the left is equivalent to d.append(d.popleft()). #maxlen - Maximum size of a deque or None if unbounded. from collections import deque class Stack: def __init__(self): self.container = deque() def push(self, data): self.container.append(data) def pop(self): if Stack.length(self): return self.container.pop() else: return "None, Stack is empty" def length(self): return len(self.container) def displayStack(self): return(self.container) def getLastElement(self): return self.container[-1] if __name__ == "__main__": stk = Stack() stk.push("First") #print(stk.displayStack()) stk.push("Second") #print(stk.getLastElement()) print("Current Stack: ", stk.displayStack()) print("Popped: ", stk.pop()) print("Current Stack: ", stk.displayStack()) print("Popped: ", stk.pop()) print("Current Stack: ", stk.displayStack()) print("Popped: ", stk.pop()) print("Popped: ", stk.pop()) print("Popped: ", stk.pop())
98acf53b0f0e8bf1cc399a86149952b4a7ec09c1
boboalex/LeetcodeExercise
/offer_15.py
397
3.828125
4
class Singleton(object): def __new__(cls): # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象 if not hasattr(cls, 'instance'): cls.instance = super(Singleton, cls).__new__(cls) return cls.instance obj1 = Singleton() obj2 = Singleton() obj1.attr1 = 'value1' print(obj1.attr1, obj2.attr1) print(obj1 is obj2)
c88ca837eb9b3703b37449a62ec9ff9a9524299e
aliceayres/leetcode-practice
/practice/leetcode/algorithm/796_RotateString.py
1,129
3.859375
4
""" 796. Rotate String We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. Example 1: Input: A = 'abcde', B = 'cdeab' Output: true Example 2: Input: A = 'abcde', B = 'abced' Output: false Note: A and B will have length at most 100. """ class Solution: def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool """ if len(A) != len(B): return False if len(A) == 0: return True for i in range(len(A)): if B[0] == A[i]: if i == 0: if A == B: return True else: if A[i:] + A[0:i] == B: # 0~i-1 → [0:i] return True return False if __name__ == '__main__': slt = Solution() a = 'abced' b = 'cedab' print(slt.rotateString(a,b))
3a30952ecdc154ae46b242edabe8839641fbd008
mukund7296/Python-Brushup
/19 Switch function.py
380
3.796875
4
#switch python def get_car_color(car): if car == 'ford': return ['red', 'black', 'white', 'silver', 'gold'] elif car == 'audi': return ['black', 'white'] elif car == 'volkswagen': return ['purple', 'orange', 'green'] elif car == 'mercedes': return ['black'] else: return ['pink'] print(get_car_color('audi'))
00990e80e83ac1c0e4ffdee31c736a351b6f90ef
PanMartinez/Codewars_Training
/Python Kyu6/Counting Duplicates.py
314
3.640625
4
from collections import Counter def duplicate_count(text): dubles = 0 for key,value in Counter(list(text.upper())).items(): if value > 1: dubles += 1 return dubles print(duplicate_count("abcde"), 0) print(duplicate_count("abcdea"), 1) print(duplicate_count("indivisibility"), 1)
1e2be84106093f3fad4f95e7d38b380931b6ac45
Jjschwartz/RL-an-intro
/experiments/util.py
2,667
3.859375
4
import numpy as np import matplotlib.pyplot as plt import time def run_experiment(agent, timesteps, num_episodes, verbose=True): """ Run an experiment using agent, for given number of episodes. Arguments: ---------- Agent agent : the agent to run experiment with int timesteps : number of timesteps each episode is run for int num_episodes : the number of episodes to run experiment for boolean verbose : whether to print progress messages of not Returns: -------- ndarray average_rewards : the reward for each timestep averaged over all problem runs ndarray optimal_actions_perc : the proportion of optimal actions performed for each timestep averaged over all problem runs """ if verbose: print("[+] Running Experiment") average_rewards = np.zeros(timesteps) optimal_actions_perc = np.zeros(timesteps) for p in range(num_episodes): rewards, optimal_actions = agent.run_episode() average_rewards += rewards optimal_actions_perc += optimal_actions if verbose and p % 50 == 0: print("[+] Finished Problem {0}".format(p)) average_rewards = average_rewards / num_episodes optimal_actions_perc = optimal_actions_perc / num_episodes return average_rewards, optimal_actions_perc def plot_experiment_results(rewards, optimal_actions, timesteps): """ Sets up and displays plots for average rewards and optimal action percent per timestep. Arguments: ---------- ndarray rewards : the reward for each timestep averaged over all episodes ndarray optimal_actions_perc : the proportion of optimal actions performed for each timestep averaged over all episodes int timesteps : number of timesteps each episode is run for """ tsteps = np.arange(timesteps) plt.subplot(2, 1, 1) for k in rewards.keys(): plt.plot(tsteps, rewards[k], label=k) plt.ylabel("Average reward") plt.legend() plt.subplot(2, 1, 2) for k in optimal_actions.keys(): plt.plot(tsteps, optimal_actions[k], label=k) plt.ylabel("Optimal Action proportion") plt.xlabel("Steps") plt.legend() plt.show() def compare_agent_times(agents, timesteps, episodes): """ Displays the time taken to run a list of agents. """ run_times = np.zeros(len(agents)) for i in range(len(agents)): print("=> Testing agent {0}".format(i)) start_t = time.time() run_experiment(agents[i], timesteps, episodes, verbose=False) run_times[i] = time.time() - start_t print("=> Time taken = {0}".format(run_times[i]))
968959850a0d0abd1b60289c0ecc279b18dba4db
nbenlin/beginners-python-examples
/1-Basic Python Objects and Data Structures/2_exapmle.py
222
4.28125
4
# Take the two perpendicular sides (a, b) of a right triangle from the user and try to find the length of the hypotenuse. a = int(input("a: ")) b = int(input("b: ")) c = (a ** 2 + b ** 2) ** 0.5 print("Hypotenuse: ", c)
db931420fcacf15b146461b27cf1bc85039afd5f
MorrillD/Settlers-of-Catan
/setUpFuncs.py
14,484
3.9375
4
from main import * import pygame import sys # player places first two settlements # never used after the game is set up def setUpSettlement(turn, board, screen): myfont = pygame.font.SysFont("monospace", 20, True) if turn: text = "Player 1 place a settlement" else: text = "Player 2 place a settlement" label = myfont.render(text, 1, BLACK) screen.blit(label, (800, 200)) pygame.display.update() placed = False while not placed: for event in pygame.event.get(): # player quits game if event.type == pygame.QUIT: sys.exit() # player clicks elif event.type == pygame.MOUSEBUTTONDOWN: print(event.pos) # get position of click posx, posy = event.pos row, col = get_settlement_pos(posx, posy) # if click is not out of bounds if row != 0 or col != 0: # if it is a valid location if isTwoSpaces(board, row, col): # place red piece on player 1's turn if turn: board[row][col] = R_SETTLEMENT # place blue piece on player 2's turn else: board[row][col] = B_SETTLEMENT placed = True # erases text prompt screen.fill(BLUE) draw_board(screen, board) pygame.display.update() print_board(board) # determines if a spot chosen by a player is at least two settlement spaces from another settlement or city def isTwoSpaces(board, row, col): # checks if spot selected is empty if board[row][col] != EMPTY_SETTLEMENT: return False # top most spaces elif row == 0: # checks diagonally below if board[2][col - 2] != EMPTY_SETTLEMENT or board[2][col + 2] != EMPTY_SETTLEMENT: return False else: return True # bottom most spaces elif row == 22: # check diagonally above if board[20][col - 2] != EMPTY_SETTLEMENT or board[20][col + 2] != EMPTY_SETTLEMENT: return False else: return True # using > EMPTY_SETTLEMENT(E_S) instead of == because it may be check a space == 0 not == E_S # left most spaces elif col == 0: # check above and below if board[row - 2][0] > EMPTY_SETTLEMENT or board[row + 2][0] > EMPTY_SETTLEMENT: return False # check diagonally right elif board[row - 2][2] > EMPTY_SETTLEMENT or board[row + 2][2] > EMPTY_SETTLEMENT: return False else: return True # right most spaces elif col == 20: # check above and below if board[row - 2][20] > EMPTY_SETTLEMENT or board[row + 2][20] > EMPTY_SETTLEMENT: return False # check diagonally left elif board[row - 2][18] > EMPTY_SETTLEMENT or board[row + 2][18] > EMPTY_SETTLEMENT: return False else: return True # every other space else: # check above and below if board[row - 2][col] > EMPTY_SETTLEMENT or board[row + 2][col] > EMPTY_SETTLEMENT: return False # check diagonally left elif board[row - 2][col - 2] > EMPTY_SETTLEMENT or board[row + 2][col - 2] > EMPTY_SETTLEMENT: return False # check diagonally right elif board[row - 2][col + 2] > EMPTY_SETTLEMENT or board[row + 2][col + 2] > EMPTY_SETTLEMENT: return False else: return True def placeRoad(turn, board, screen): myfont = pygame.font.SysFont("monospace", 20, True) if turn: text = "Player 1, place a road" else: text = "Player 2, place a road" label = myfont.render(text, 1, BLACK) screen.blit(label, (800, 200)) pygame.display.update() placed = False while not placed: for event in pygame.event.get(): # player quits game if event.type == pygame.QUIT: sys.exit() # player clicks elif event.type == pygame.MOUSEBUTTONDOWN: print(event.pos) # get position of click posx, posy = event.pos row, col = get_road_pos(posx, posy) if row != 0 or col != 0: # check if connected to settlement or road if isNearSR(board, row, col, turn): if turn: board[row][col] = R_ROAD else: board[row][col] = B_ROAD placed = True # blit screen.fill(BLUE) draw_board(screen, board) pygame.display.update() print_board(board) # returns true if road trying to be placed is "connected" to settlement, city, or road def isNearSR(board, r, c, turn): if turn: # check above for settlement if board[r - 1][c] == R_SETTLEMENT or board[r - 1][c] == R_CITY: return True # check below for settlement elif board[r + 1][c] == R_SETTLEMENT or board[r + 1][c] == R_CITY: return True # check left for settlement and road # column 0 will go out of bounds if c != 0: # check upper left for settlement if board[r - 1][c - 1] == R_SETTLEMENT or board[r - 1][c - 1] == R_CITY: return True # check lower left for settlement if board[r + 1][c - 1] == R_SETTLEMENT or board[r + 1][c - 1] == R_CITY: return True # check up and left for road # row 1 will go out of bounds if r != 1: if board[r - 2][c - 1] == R_ROAD: return True # check down and left for road # row 21 will go out of bounds if r != 21: if board[r + 2][c - 1] == R_ROAD: return True # check left for road # column 1 will go out of bounds if c != 1: if board[r][c - 2] == R_ROAD: return True # check right for roads and settlements # column 20 will go out of bounds if c != 20: # check upper right for settlement if board[r - 1][c + 1] == R_SETTLEMENT or board[r - 1][c + 1] == R_CITY: return True # check lower right for settlement if board[r + 1][c + 1] == R_SETTLEMENT or board[r + 1][c + 1] == R_CITY: return True # check up and right for road # row 1 will go out of bounds if r != 1: if board[r - 2][c + 1] == R_ROAD: return True # check down and right for road # row 21 will go out of bounds if r != 21: if board[r + 2][c + 1] == R_ROAD: return True # checks right for road # column 19 will go out of bounds if c != 19: if board[r][c + 2] == R_ROAD: return True # player 2 else: # check above for settlement if board[r - 1][c] == B_SETTLEMENT or board[r - 1][c] == B_CITY: return True # check below for settlement elif board[r + 1][c] == B_SETTLEMENT or board[r + 1][c] == B_CITY: return True # check left for settlement and road # column 0 will go out of bounds if c != 0: # check upper left for settlement if board[r - 1][c - 1] == B_SETTLEMENT or board[r - 1][c - 1] == B_CITY: return True # check lower left for settlement if board[r + 1][c - 1] == B_SETTLEMENT or board[r + 1][c - 1] == B_CITY: return True # check up and left for road # row 1 will go out of bounds if r != 1: if board[r + 2][c - 1] == B_ROAD: return True # check down and left for road # row 21 will go out of bounds if r != 21: if board[r - 2][c - 1] == B_ROAD: return True # check left for road # column 1 will go out of bounds if c != 1: if board[r][c - 2] == B_ROAD: return True # check right for roads and settlements # column 20 will go out of bounds if c != 20: # check upper right for settlement if board[r - 1][c + 1] == B_SETTLEMENT or board[r - 1][c + 1] == B_CITY: return True # check lower right for settlement if board[r + 1][c + 1] == B_SETTLEMENT or board[r + 1][c + 1] == B_CITY: return True # check up and right for road # row 1 will go out of bounds if r != 1: if board[r - 2][c + 1] == B_ROAD: return True # check down and right for road # row 21 will go out of bounds if r != 21: if board[r + 2][c + 1] == B_ROAD: return True # checks right for road # column 19 will go out of bounds if c != 19: if board[r][c + 2] == B_ROAD: return True # not connected to anything return False # returns true if settlement trying to be placed is connected to a road def isNearRoad(board, r, c, turn): # checks for player 1 if turn: if r != 0: # checks above if board[r - 1][c] == R_ROAD: return True # checks above left if c != 0: if board[r - 1][c - 1] == R_ROAD: return True # checks above right if c != 20: if board[r - 1][c + 1] == R_ROAD: return True if r != 22: # checks below if board[r + 1][c] == R_ROAD: return True # checks below left if c != 0: if board[r + 1][c - 1] == R_ROAD: return True # checks below right if c != 20: if board[r + 1][c + 1] == R_ROAD: return True # checks for player 2 else: if r != 0: # checks above if board[r - 1][c] == B_ROAD: return True # checks above left if c != 0: if board[r - 1][c - 1] == B_ROAD: return True # checks above right if c != 20: if board[r - 1][c + 1] == B_ROAD: return True if r != 22: # checks below if board[r + 1][c] == B_ROAD: return True # checks below left if c != 0: if board[r + 1][c - 1] == B_ROAD: return True # checks below right if c != 20: if board[r + 1][c + 1] == B_ROAD: return True # if can't place return False def placeSettlement(turn, board, screen): myfont = pygame.font.SysFont("monospace", 20, True) if turn: text = "Player 1, place a settlement" else: text = "Player 2, place a settlement" label = myfont.render(text, 1, BLACK) screen.blit(label, (800, 200)) pygame.display.update() placed = False while not placed: for event in pygame.event.get(): # player quits game if event.type == pygame.QUIT: sys.exit() # player clicks elif event.type == pygame.MOUSEBUTTONDOWN: print(event.pos) # get position of click posx, posy = event.pos row, col = get_settlement_pos(posx, posy) # if click is not out of bounds if row != 0 or col != 0: # if it is a valid location if isTwoSpaces(board, row, col) and isNearRoad(board, row, col, turn): # place red piece on player 1's turn if turn: board[row][col] = R_SETTLEMENT # place blue piece on player 2's turn else: board[row][col] = B_SETTLEMENT placed = True # erases text prompt screen.fill(BLUE) draw_board(screen, board) pygame.display.update() print_board(board) def placeCity(turn, board, screen): myfont = pygame.font.SysFont("monospace", 20, True) if turn: text = "Player 1, place a city" else: text = "Player 2, place a city" label = myfont.render(text, 1, BLACK) screen.blit(label, (800, 200)) pygame.display.update() placed = False while not placed: for event in pygame.event.get(): # player quits game if event.type == pygame.QUIT: sys.exit() # player clicks elif event.type == pygame.MOUSEBUTTONDOWN: print(event.pos) posx, posy = event.pos row, col = get_settlement_pos(posx, posy) if turn: if board[row][col] == R_SETTLEMENT: board[row][col] = R_CITY placed = True else: if board[row][col] == B_SETTLEMENT: board[row][col] = B_CITY placed = True # erases text prompt screen.fill(BLUE) draw_board(screen, board) pygame.display.update() print_board(board)
c6c04a62147cbe69cb237ac43fb41867bf72b39e
Prev/leetcode
/problems/44-wildcard-matching/solution-nm.py
2,065
3.671875
4
""" Problem: https://leetcode.com/problems/wildcard-matching/ Author: Youngsoo Lee Time complexity: O(nm) where n is length of `s` and m is length of `p`. """ from typing import List class Solution: def _search(self, s: str, p: str) -> bool: """ Search string with pattern without wildcard feature """ m = len(p) if m == 0: return 0 for i in range(len(s) - m + 1): is_matched = True for j in range(len(p)): if p[j] not in (s[i+j], '?'): is_matched = False break if is_matched: return i return -1 def isMatch(self, s: str, p: str) -> bool: if '*' not in p: return len(s) == len(p) and self._search(s, p) == 0 while '**' in p: p = p.replace('**', '*') subpatterns = p.split('*') for k in range(len(subpatterns)): subp = subpatterns[k] m = len(subp) index = self._search(s, subp) if index == -1: return False if k == 0 and index != 0: # The first pattern should be occured in the front of the string. # (Note that the leading wildcard also returns 0.) return False if k == len(subpatterns) - 1: # The last pattern should match to the end of the string. return self._search(s[len(s)-m:], subp) == 0 s = s[index+m:] if __name__ == '__main__': s = Solution() assert s.isMatch('aa', 'a') == False assert s.isMatch('aa', '*') == True assert s.isMatch('cb', '?a') == False assert s.isMatch('adceb', '*a*b') == True assert s.isMatch('acdcb', 'a*c?b') == False assert s.isMatch('aaaaaab', 'a*a*a*b') == True assert s.isMatch('acbcdabeadbad', '*a*b?d') == True assert s.isMatch('aa', '??') == True assert s.isMatch('acdqwcbqwec', '*b*') == True assert s.isMatch('aaaaaaaaaababaaa', '**********') == True
ed884d04afde74b7d090a5871b57124f26afb406
zerghua/leetcode-python
/N2217_FindPalindromeWithFixedLength.py
2,993
3.890625
4
# # Create by Hua on 7/19/22 # """ Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists. A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros. Example 1: Input: queries = [1,2,3,4,5,90], intLength = 3 Output: [101,111,121,131,141,999] Explanation: The first few palindromes of length 3 are: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ... The 90th palindrome of length 3 is 999. Example 2: Input: queries = [2,4,6], intLength = 4 Output: [1111,1331,1551] Explanation: The first six palindromes of length 4 are: 1001, 1111, 1221, 1331, 1441, and 1551. Constraints: 1 <= queries.length <= 5 * 104 1 <= queries[i] <= 109 1 <= intLength <= 15 """ class Solution(object): def kthPalindrome(self, queries, intLength): """ :type queries: List[int] :type intLength: int :rtype: List[int] thought: peeked hint: Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. if len = 1 (0 - 9) 10 if len = 2 (11,22,...99) 9 if len = 3, we have palindrome: 101, 111, 121, 131, 202, 212, ... 999 (10 - 99) len=4 1001, 1111, ... 2002, ... 9999 (10 - 99) 99-10 +1=90 len=5 10001, 10101,10201, ... 99999 (100,101,...999) 999-100+1=900 half_len = ceil(len/2) max_index = 10^half_len - 10^(half_len - 1) index start from 1 07/19/2022 14:12 Accepted 826 ms 23.6 MB python medium. find pattern, quite several cases. 20-30min. """ ret = list() if intLength == 1: # interesting, 0 is not palindrome according the test case. for n in queries: if n <= 9: ret.append(n) else: ret.append(-1) elif intLength == 2: for n in queries: if n <= 9: ret.append(n*10 + n) else: ret.append(-1) else: is_odd = True if intLength % 2 == 1 else False half_len = intLength / 2 if intLength % 2 == 0 else intLength / 2 + 1 max_index = 10**(half_len) - 10**(half_len - 1) start = 10**(half_len - 1) for n in queries: if n <= max_index: first_half = str(start + n - 1) if is_odd: num = int(first_half[:-1] + first_half[::-1]) else: num = int(first_half + first_half[::-1]) ret.append(num) else: ret.append(-1) return ret
fff5269fcd61758b1b52a966aa1667857f6a9031
frkMaky/cursopython
/gui/practicaCalculadora.py
4,368
3.71875
4
from tkinter import * # Libreria de ventanas raiz=Tk() # Se crea ventana miFrame = Frame(raiz) # Se pone frame en la ventana miFrame.pack() # Se empaqueta todo en la ventana operacion="" # Operacion a realizar variable GLOBAL resultado = 0 # Resultado de la operacion # Pantalla -------------------------------------------------- numeroPantalla=StringVar() # Nª a mostrar en la pantalla pantalla = Entry(miFrame, textvariable=numeroPantalla) # Se asocia la variable a la pantalla pantalla.grid(row=1, column=1, padx=10, pady=10, columnspan=4) # columnspan=4 para ocupar 4 columnas de ancho pantalla.config(bg="black", fg="green", justify="right") # Pulsaciones teclado ---------------------------------------- def numeroPulsado(num): global operacion # Se utiliza variable GLOBAL if operacion != "": # Si se ha pulsado operacion no se sigue concatenando numero numeroPantalla.set(num) operacion="" else: numeroPantalla.set(numeroPantalla.get() + str(num)) # El Resultado ---------------------------------------- def el_resultado(): global resultado numeroPantalla.set(resultado + int(numeroPantalla.get())) # Se pone el resultado en pantalla # Suma ---------------------------------------- def suma(num): global operacion # Se utiliza variable GLOBAL global resultado resultado += int(num) # Se suma al resultado el valor del nº en pantalla operacion="suma" numeroPantalla.set(resultado) # Se pone el resultado en pantalla # Resta ---------------------------------------- def resta(num): global operacion # Se utiliza variable GLOBAL global resultado resultado -= int(num) # Se resta al resultado el valor del nº en pantalla operacion="resta" numeroPantalla.set(resultado) # Se pone el resultado en pantalla # Multiplicacion ---------------------------------------- def producto(num): global operacion # Se utiliza variable GLOBAL global resultado resultado *= int(num) # Se resta al resultado el valor del nº en pantalla operacion="producto" numeroPantalla.set(resultado) # Se pone el resultado en pantalla # Division ---------------------------------------- def divide(num): global operacion # Se utiliza variable GLOBAL global resultado resultado /= int(num) # Se resta al resultado el valor del nº en pantalla operacion="division" numeroPantalla.set(resultado) # Se pone el resultado en pantalla # BOTONES POR FILA------------------------------------------------- # 789% ------------------------------------------------------------ boton7 = Button(miFrame,text="7",width=3, command=lambda:numeroPulsado("7")).grid(row=2,column=1) boton8 = Button(miFrame,text="8",width=3, command=lambda:numeroPulsado("8")).grid(row=2,column=2) boton9 = Button(miFrame,text="9",width=3, command=lambda:numeroPulsado("9")).grid(row=2,column=3) botonDiv = Button(miFrame,text="%",width=3, command=lambda:divide (numeroPantalla.get())).grid(row=2,column=4) # 456X -------------------------------------------------- boton4 = Button(miFrame,text="4",width=3, command=lambda:numeroPulsado("4")).grid(row=3,column=1) boton5 = Button(miFrame,text="5",width=3, command=lambda:numeroPulsado("5")).grid(row=3,column=2) boton6 = Button(miFrame,text="6",width=3, command=lambda:numeroPulsado("6")).grid(row=3,column=3) botonMult = Button(miFrame,text="X",width=3, command=lambda:producto(numeroPantalla.get())).grid(row=3,column=4) # 123- -------------------------------------------------- boton1 = Button(miFrame,text="1",width=3, command=lambda:numeroPulsado("1")).grid(row=4,column=1) boton2 = Button(miFrame,text="2",width=3, command=lambda:numeroPulsado("2")).grid(row=4,column=2) boton3 = Button(miFrame,text="3",width=3, command=lambda:numeroPulsado("3")).grid(row=4,column=3) botonRest = Button(miFrame,text="-",width=3, command=lambda:resta(numeroPantalla.get())).grid(row=4,column=4) # 0.=+ -------------------------------------------------- boton0 = Button(miFrame,text="0",width=3, command=lambda:numeroPulsado("0")).grid(row=5,column=1) botonComa = Button(miFrame,text=".",width=3).grid(row=5,column=2) botonIgual = Button(miFrame,text="=",width=3, command=lambda:el_resultado()).grid(row=5,column=3) botonSuma = Button(miFrame,text="+",width=3, command=lambda:suma(numeroPantalla.get())).grid(row=5 ,column=4) #------------------------------------------------------------------ raiz.mainloop() # Se ejecuta ventana
6ddbc235115f00e34dbaf786e0d043a3593a7254
YoChen3086/PythonPractice
/exercise14.py
992
3.609375
4
# 题目: # 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 def reduceNum(n): checkNumber(n) breakDown(n) # elif n in [1] : # print ('{}'.format(n)) # while n not in [1] : # 循环保证递归 # for index in range(2, n + 1) : # if n % index == 0: # n /= index # n 等于 n/index # if n == 1: # print (index) # else : # index 一定是素数 # print ('{} *'.format(index),) # break def checkNumber(n): if not isinstance(n, int) or n <= 0: print ('请输入一个正确的数字 !') exit(0) else: print ('%d = ' % n, end = "") def breakDown(n): if n == 1: print (n) else: while n not == 1: for index in range(2, n+1): print (n) num = int(input('請輸入某個數字 : ')) reduceNum(num) reduceNum(90) reduceNum(100)
37bb9a5016af056ca5fa64040311b1b15042cf29
ahwang16/W4111-f18
/Projects/HW1-Templates/Python/CSVTableV2-Template.py
1,896
4.125
4
import csv # Python package for reading and writing CSV files. import copy # Copy data structures. # hello import sys,os # You can change to wherever you want to place your CSV files. rel_path = os.path.realpath('./Data') class CSVTable(): # Change to wherever you want to save the CSV files. data_dir = rel_path + "/" def __init__(self, table_name, table_file, key_columns): ''' Constructor :param table_name: Logical names for the data table. :param table_file: File name of CSV file to read/write. :param key_columns: List of column names the form the primary key. ''' self.table_name = table_name self.table_file = table_file self.key_columns = key_columns def __str__(self): ''' Pretty print the table and state. :return: String ''' # with open(self.table_file, "r") as infile: pass def load(self): ''' Load information from CSV file. :return: None ''' pass def find_by_template(self, t, fields=None): ''' Return a table containing the rows matching the template and field selector. :param t: Template that the rows much match. :param fields: A list of columns to include in responses. :return: CSVTable containing the answer. ''' def save(self): ''' Write updated CSV back to the original file location. :return: None ''' def insert(self, r): ''' Insert a new row into the table. :param r: New row. :return: None. Table state is updated. ''' pass def delete(self, t): ''' Delete all tuples matching the template. :param t: Template :return: None. Table is updated. ''' pass
a6c94ee20bbd3fc35558cb022a35fb54c520cee4
TharindaNimnajith/machine-learning
/python_data_science/numpy_package.py
2,162
4.34375
4
import numpy as np # In Python, lists are used to store data. # NumPy provides an array structure for performing operations with data. # NumPy arrays are faster and more compact than lists. # NumPy arrays are homogeneous. # They can contain only a single data type, while lists can contain multiple different types of data. help(np) print(dir(np)) print(np) num_list = [18, 24, 67, 55, 42, 14, 19, 26, 33] np_array = np.array(num_list) print(np_array[3]) print(np_array.mean()) print(np_array.max(initial=None)) print(np_array.min(initial=None)) print(np_array.std()) print(np_array.var()) print(np.percentile(np_array, q=1)) print(np.percentile(np_array, q=2)) print(np.percentile(np_array, q=3)) print(np.percentile(np_array, 25)) print(np.percentile(np_array, 50)) print(np.percentile(np_array, 75)) print(np.percentile(num_list, 25)) print(np.percentile(num_list, 50)) print(np.percentile(num_list, 75)) players = [180, 172, 178, 185, 190, 195, 192, 200, 210, 190] np_array = np.array(players) std = np_array.std() mean = np_array.mean() count = 0 for player in players: if mean + std >= player >= mean - std: count += 1 print(count) # NumPy arrays are often called ndarrays, which stands for 'N-dimensional array' # They can have multiple dimensions. ndarray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]]) print(ndarray[1][2]) print(ndarray.ndim) print(ndarray.size) print(ndarray.shape) x = np.array([2, 1, 3]) x = np.append(x, 4) x = np.delete(x, 0) x = np.sort(x) print(x) print(np.arange(2, 20, 3)) print(np.arange(1, 7)) x = np.arange(1, 7) print(x.reshape(3, 2)) y = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]]) print(y.reshape(12)) print(y.flatten()) x = np.arange(1, 10) print(x[0:2]) print(x[5:]) print(x[:2]) print(x[-3:]) print(x[-1]) print(x[-1:]) print(x[-2]) print(x[:]) print(x[::]) print(x[::-1]) print(x[1:7:2]) print(x[x < 4]) print(x[(x > 5) & (x % 2 == 0)]) print(x[(x >= 8) | (x <= 3)]) print(x[x > np.mean(x)]) print(x.sum()) # NumPy understands that the given operation should be performed with each element. # This is called broadcasting. print(x * 2) print(x + 2) print(x - 2) print(x / 2)
3881317e280565430fb14c89c650f30adf131165
pramodswainn/LeetCode
/Week6/92.py
732
3.765625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: current=head array=[] while current: array.append(current.val) current=current.next i=0 j=n-1 current=head while current: if i>=m-1 and i<=n-1: current.val=array[j] j-=1 i+=1 else: current.val=array[i] i+=1 current=current.next return head
12006e693f527c96b21fa161c1e51d9526932970
lohitakshapatra/C103
/line.py
186
3.578125
4
import plotly.express as px import pandas as pd df=pd.read_csv("line_chart.csv") fig=px.line(df,x="Year",y="Per capita income",color="Country",title="Per capita income") fig.show()
a4dfa2494ef4111d64fd0ae3bb65392ac3d427d3
harshavardhanb77/ns
/8a.py
388
4
4
def highest(names,marks): if(len(marks)==len(names)): maxMark=max(marks) index=marks.index(maxMark) maxName=names[index] return(maxName,maxMark) names=[] marks=[] n=int(input("Enter the number of students")) for i in range(n): names.append(input("name")) marks.append(int(input("Marks"))) print(highest(names,marks))
979acf878605e41b9385caca9a807329ca6f66fd
shahpriyesh/PracticeCode
/HashMapQuestions/UncommonWordsFromTwoSentences.py
703
3.6875
4
from collections import Counter class Solution: def findUncommon(self, A, B): cntr_a = Counter(A.split()) cntr_b = Counter(B.split()) res = [] res.extend(self._retrieveUncommon(cntr_a, cntr_b)) res.extend(self._retrieveUncommon(cntr_b, cntr_a)) return res def _retrieveUncommon(self, cntr1, cntr2): res = [] for item, cnt in cntr1.items(): if cnt == 1: if item not in cntr2: res.append(item) return res object = Solution() A = "this apple is sweet" B = "this apple is sour" print(object.findUncommon(A, B)) A = "apple apple" B = "banana" print(object.findUncommon(A, B))
4c9821c6f9fd7e6da655f18b524ce1aa22569f69
tmdenddl/Python
/Abstraction/Change Calculator.py
744
3.828125
4
from builtins import int def calculate_change(payment, cost): change = payment - cost fifty_thousand_count = int(change / 50000) change = change % 50000 ten_thousand_count = int(change / 10000) change = change % 10000 five_thousand_count = int(change / 5000) change = change % 5000 one_thousand_count = int(change / 1000) change = change % 1000 print("50000원 지폐: %d장" % (fifty_thousand_count)) print("10000원 지폐: %d장" % (ten_thousand_count)) print("5000원 지폐: %d장" % (five_thousand_count)) print("1000원 지폐: %d장" % (one_thousand_count)) # 코드를 작성하세요. # 테스트 calculate_change(100000, 33000) print() calculate_change(500000, 378000)
20a4b5161faf42000927b1bd7edf1c2c782337b3
PratikPatni/pythoncodes
/rainbow.py
233
3.578125
4
n=int(input()) output=list() for i in range(n): s=int(input()) ls=list() ls=input().split(' ') ls2=ls ls.reverse() if(ls2==ls):output.append("yes") else:output.append("no") for i in range(output):print(i)
4c23c97551f52a8ca5ff72c120377ce3a6d7b86a
wilsonify/ThinkBayes2
/tests/test_examples/test_pair_dice.py
5,915
3.703125
4
""" The pair of dice problem Copyright 2018 Allen Downey MIT License: https://opensource.org/licenses/MIT """ import logging import numpy as np import pandas as pd from thinkbayes import Pmf, Suite from thinkbayes import thinkplot def test_BayesTable(): # ### The BayesTable class # # Here's the class that represents a Bayesian table. class BayesTable(pd.DataFrame): def __init__(self, hypo, prior=1, **options): columns = ["hypo", "prior", "likelihood", "unnorm", "posterior"] super().__init__(columns=columns, **options) self.hypo = hypo self.prior = prior def mult(self): self.unnorm = self.prior * self.likelihood def norm(self): nc = np.sum(self.unnorm) self.posterior = self.unnorm / nc return nc def update(self): self.mult() return self.norm() def reset(self): return BayesTable(self.hypo, self.posterior) # ### The pair of dice problem # # Suppose I have a box that contains one each of 4-sided, 6-sided, 8-sided, and 12-sided dice. I choose two dice at random and roll them without letting you see the die or the outcome. I report that the sum of the dice is 3. # # 1) What is the posterior probability that I rolled each possible pair of the dice? # # # 2) If I roll the same dice again, what is the probability that the sum of the dice is 11? # **Solution** # # I'll start by making a list of possible pairs of dice. sides = [4, 6, 8, 12] hypo = [] for die1 in sides: for die2 in sides: if die2 > die1: hypo.append((die1, die2)) logging.info("%r", f"hypo = {hypo}") # Here's a `BayesTable` that represents the hypotheses. table = BayesTable(hypo) # Since we didn't specify prior probabilities, the default value is equal priors for all hypotheses. They don't have to be normalized, because we have to normalize the posteriors anyway. # # Now we can specify the likelihoods: if the first die has `n1` sides and the second die has `n2` sides, the probability of getting a sum of 3 is # # `2 / n1 / n2` # # The factor of `2` is there because there are two ways the sum can be 3, either the first die is `1` and the second is `2`, or the other way around. # # So the likelihoods are: for i, row in table.iterrows(): n1, n2 = row.hypo table.loc[i, "likelihood"] = 2 / n1 / n2 logging.info("%r", f"table = {table}") # Now we can use `update` to compute the posterior probabilities: table.update() logging.info("%r", f"table = {table}") # ### Part two # # The second part of the problem asks for the (posterior predictive) probability of getting a total of 11 if we roll the same dice again. # # For this, it will be useful to write a more general function that computes the probability of getting a total, `k`, given `n1` and `n2`. # # Here's an example with the `4` and `6` sided dice: n1, n2 = 4, 6 d1 = Pmf(range(1, n1 + 1)) d2 = Pmf(range(1, n2 + 1)) total = d1 + d2 thinkplot.plot_hist_bar(total) # And here's the general function: def prob_total(k, n1, n2): d1 = Pmf(range(1, n1 + 1)) d2 = Pmf(range(1, n2 + 1)) total = d1 + d2 return total[k] # To check the results, I'll compare them to the likelihoods in the previous table: for i, row in table.iterrows(): n1, n2 = row.hypo p = prob_total(3, n1, n2) print(n1, n2, p, p == row.likelihood) # Now we can answer the second part of the question using the law of total probability. The chance of getting `11` on the second roll is the # # $\sum_{n1, n2} P(n1, n2 ~|~ D) \cdot P(11 ~|~ n1, n2)$ # # The first term is the posterior probability, which we can read from the table; the second term is `prob_total(11, n1, n2)`. # # Here's how we compute the total probability: total = 0 for i, row in table.iterrows(): n1, n2 = row.hypo p = prob_total(11, n1, n2) total += row.posterior * p logging.info("%r", f"total = {total}") # This calculation is similar to the first step of the update, so we can also compute it by # # 1) Creating a new table with the posteriors from `table`. # # 2) Adding the likelihood of getting a total of `11` on the next roll. # # 3) Computing the normalizing constant. table2 = table.reset() for i, row in table2.iterrows(): n1, n2 = row.hypo table2.loc[i, "likelihood"] = prob_total(11, n1, n2) logging.info("%r", f"table2 = {table2}") table2.update() logging.info("%r", f"table2 = {table2}") # ### Using a Suite # We can solve this problem more concisely, and more efficiently, using a `Suite`. # # First, I'll create `Pmf` object for each die. dice = {} for n in sides: dice[n] = Pmf(range(1, n + 1)) # And a `Pmf` object for the sum of each pair of dice. pairs = {} for n1 in sides: for n2 in sides: if n2 > n1: pairs[n1, n2] = dice[n1] + dice[n2] # Here's a `Dice` class that implements `Likelihood` by looking up the data, `k`, in the `Pmf` that corresponds to `hypo`: class Dice(Suite): def likelihood(self, data, hypo): """Likelihood of the data given the hypothesis. data: total of two dice hypo: pair of sides return: probability """ return pairs[hypo][data] # Here's the prior: suite = Dice(pairs.keys()) suite.print() # And the posterior: suite.update(3) suite.print() # And the posterior probability of getting `11` on the next roll. suite.update(11)
cf674c33fbe152f4a42b3c72c79e05e8b1934e6b
500poundbear/mlrecipe
/FoodIngredientRecorder.py
1,507
3.6875
4
""" Stores food and ingredient for easy lookup """ class FoodIngredientRecorder: def __init__(self): # food comes originally with an id # our internal id is represented by int self.food_int_to_id = {} self.food_id_to_int = {} self.fcount = 0 self.icount = 0 self.ingredient_int_to_name = {} self.ingredient_name_to_int = {} def process_and_record(self, fid, iname): print "fid:{} iname: {}".format(fid, iname) if fid not in self.food_id_to_int: # Add new mapping from food_id to int self.food_id_to_int[fid] = self.fcount # Add new mapping from int to food_id self.food_int_to_id[self.fcount] = fid self.fcount = self.fcount + 1 if iname not in self.ingredient_name_to_int: # Add new mapping from ingredient_name to int self.ingredient_name_to_int[iname] = self.icount # Add new mapping from int to ingredient name self.ingredient_int_to_name[self.icount] = iname self.icount = self.icount + 1 return [self.food_id_to_int[fid], self.ingredient_name_to_int[iname]] def get_food_id_to_int(self): return self.food_id_to_int def get_food_int_to_id(self): return self.food_int_to_id def get_ingredient_int_to_name(self): return self.ingredient_int_to_name def get_ingredient_name_to_int(self): return self.ingredient_name_to_int
21de5a886dbc3b90c8a0ebe95198e94274f812cb
VineeS/Python
/Assignment1/Prime_numbers.py
348
3.921875
4
import math max_num = int(input("Max Number")) primes = [2] test_num = 3 while test_num < max_num: i = 0 while primes[i] < math.sqrt(test_num): if (test_num % primes[i]) == 0: test_num += 1 break else: i += 1 else: primes.append(test_num) test_num += 1 print(primes)
c4f329dd534d58dcbb6717d0fe7c31d9bf257b2d
tyokinuhata/nlp100
/06.py
533
3.71875
4
# 06. 集合 # "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ. n_gram = lambda str: {str[i:i + 2] for i in range(len(str) - 1)} x = n_gram('paraparaparadise') y = n_gram('paragraph') # 和集合, 積集合, 差集合, xに"se"が含まれるか, yに"se"が含まれるか print(x | y, x & y, x - y, 'se' in x, 'se' in y)
8a0ba1fb7988f8911b5ff68363f855d458cbfccd
cjdeguzman95/Python-Glossary
/Other/Simple code examples.py
4,726
4.28125
4
from random import randrange import pyodbc # Palindrome function uses slicing and control flow statements to find define palindromes in a given list def palindrome(): words = ["mum", "bee", "holiday", "hannah"] for word in words: reversed_word = word[::-1] if word == reversed_word: return "is palindrome" else: return "is not a palindrome" # Function that checks largest number from user input using IF statements def largest_number(n1, n2, n3): n1 = input("Give me a number: ") n2 = input("Give me a second number: ") n3 = input("Give me a third number: ") if n1 > n2 and n3: return "The first number, {}, is the largest".format(n1) elif n2 > n1 and n3: return "The second number, {}, is the largest".format(n2) else: return "The third number, {}, is the largest".format(n3) # Uses modulus to sort range of values into evens and odds - creates and returns sorted lists numbers = range(20) even_numbers = [] odd_numbers = [] for number in numbers: if number % 2 == 0: even_numbers.append(number) else: odd_numbers.append(number) print(even_numbers, odd_numbers) # while loop and random library TRY = 3 target = randrange(10) while TRY != 0: guess = input("Guess what number I'm thinking: ") if guess != target: print("Wrong number") TRY -= 1 else: print("Congratulations! That's correct!") break else: print("Sorry. You're out of guesses!") # connecting to MSSQL via the PYODBC module # lists the total orders for each product - only displays products that have orders server = "localhost,1433" database = "Northwind" username = "SA" password = "Passw0rd2018" docker_Northwind = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';' 'UID='+username+';PWD='+ password) cursor = docker_Northwind.cursor() orders = cursor.execute("SELECT ProductName, SUM(UnitsOnOrder) AS 'Total' FROM Products GROUP BY ProductName HAVING SUM(UnitsOnOrder) > 0 ORDER BY 'Total' DESC;").fetchall() for x in orders: print(x.ProductName, x.Total) # nested dictionaries - fortune teller game fortune = { "red": { "fortune one": "You will meet someone special this week!", "fortune two": "You have a secret admirer!" }, "green": { "fortune three": "Now is a good time to invest in some stocks!", "fortune four": "Be careful how you spend your money this week - you are set to lose a lot!" }, "blue": { "fortune five": "Don't worry, failure is the chance to do better next time!", "fortune six": "You will receive great feedback this week!" }, "yellow": { "fortune seven": "Check in on your friends this week, they are missing you!", "fortune eight": "Remember to share good fortune as well as bad with your friends!" } } running = True name = input("Tell me your name and let me tell you your fortune: ") print("Hi {}, what do you want to know about?".format(name)) print("Choose a colour:\nRed for Love\nGreen for Money\nBlue for Work \nYellow for Friendship") colour = input() while running: try: chosen_number = int(input("Now choose either 1 or 2: ")) except ValueError: print("{}, please insert a numeric character!".format(name.capitalize())) else: if chosen_number < 1 or chosen_number > 2: print("You can only choose 1 or 2 {}! Try again.".format(name.capitalize())) else: for colour in fortune: if colour.lower() == "red": if chosen_number == 1: print(fortune["red"].get("fortune one")) else: print(fortune["red"].get("fortune two")) break elif colour.lower() == "green": if chosen_number == 1: print(fortune["green"].get("fortune three")) else: print(fortune["green"].get("fortune four")) break elif colour.lower() == "blue": if chosen_number == 1: print(fortune["blue"].get("fortune five")) else: print(fortune["blue"].get("fortune six")) break elif colour == "yellow": if chosen_number == 1: print(fortune["yellow"].get("fortune seven")) else: print(fortune["yellow"].get("fortune eight")) break running = False
163f434c9a6af12ad83e515c1d509d0612c0689a
Adrian96119/Miniproyect
/miniproyect_juego_ahorcado/descripcion.py
1,504
4.03125
4
def descripcion(): dibujo_ahorcado = open("ficheros_dibujo/9.txt")#importo el dibujo del ahorcado entero desde ficheros_dibujo para el titulo print("\n\n") #Hago dos saltos de linea para que no me quede tan arriba el texto print(dibujo_ahorcado.read()," -------------------********¡JUEGO DEL AHORCADO!********---------------------") #espaceo el titulo para que me quede más bonito print("\n DESCRIPCION DEL JUEGO---->>>>\n") print(""" Vamos a jugar al conocidísimo juego del ahorcado, el de toda la vida.\n La computadora elegirá una palabra al azar que usted debera adivinar. Irá eligiendo una letra por cada ronda. Si la letra se encuentra dentro de la palabra elegida, se colocará en un conjunto de lineas vacias que representan la palabra sin determinar, y si no está, se añadirá un caracter para representar el dibujo del hombre ahorcado.\n""") print(" OBJETIVO DEL JUEGO---->>>>\n") print(" Debe llegar a adivinar la palabra completa antes de que el dibujo del ahorcado se complete\n") print(""" REGLAS: -Si repite una letra, contará como errónea y se añadirá otro caracter al ahorcado -Tiene de limite 9 letras antes de que se complete el dibujo entero -Solo se aceptan letras, nada de numeros y caracteres extraños -No hay posibilidad de comodín, no te calientes...\n""") #añadir en readme pista pueden ser en ingles... print(" QUE EMPIECE EL JUEGO...") print("")
a73fb839c927bdc5438f28740b575df17fb68789
cossentino/2_linked_lists
/2.6_is_palindrome.py
848
3.65625
4
from linked_list_obj import Node, LinkedList n1 = Node(5) n2 = Node(6) n3 = Node(7) n4 = Node(6) n5 = Node(5) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 def reverse_and_clone(head_node): curr_0 = head_node curr = Node(curr_0.val) prev = None nextt = None while curr_0.next: nextt = Node(curr_0.next.val) nextt.next = curr prev = curr curr = nextt curr_0 = curr_0.next return curr def is_equal(head1, head2): curr1 = head1 curr2 = head2 while curr1.next and curr2.next: if curr1.val != curr2.val: return False curr1 = curr1.next curr2 = curr2.next if curr1.next or curr2.next: return False return True def is_palindrome(head_node): rev_list_head = reverse_and_clone(head_node) return True if is_equal(head_node, rev_list_head) else False print(is_palindrome(n1))
cb8ad6ef50e1dab7e61c6251c8d93e470469392d
ariannedee/intro-to-python
/Problems/Solutions/problem_9_card_hands.py
385
3.859375
4
""" Deal a hand of 5 cards """ import random suits = ['♠︎', '♣︎', '♥︎', '♦︎'] values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] cards = [] hand = [] for suit in suits: for value in values: cards.append(suit + value) for num in range(5): card = random.choice(cards) hand.append(card) cards.remove(card) print(hand)
93221a241477debcb2bb3c2d793be091be5a6df3
mahdibz97/holbertonschool-higher_level_programming
/0x0B-python-input_output/7-save_to_json_file.py
283
3.921875
4
#!/usr/bin/python3 """Define class""" import json def save_to_json_file(my_obj, filename): """writes an Object to a text file, using a JSON representation""" with open(filename, mode='w', encoding='UTF8') as f: my_str = json.dumps(my_obj) f.write(my_str)
c38f02eb2c2f6fe116f4d13773e622365428866b
siddarthjha/Deep-Learning
/CNN/cnn.py
7,947
3.9375
4
""" This is a 5 layers Sequential Convolutional Neural Network for digits recognition trained on MNIST dataset. Firstly, I will prepare the data (handwritten digits images) then i will focus on the CNN modeling and evaluation. It follows three main parts: The data preparation The CNN modeling and evaluation The results prediction and submission """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import seaborn as sns np.random.seed(2) from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix import itertools from keras.utils.np_utils import to_categorical # convert to one-hot-encoding from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D from keras.optimizers import RMSprop from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ReduceLROnPlateau sns.set(style='white', context='notebook', palette='deep') # Using tensorflow backend # Load data train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") # You can take your own data or else download from kaggle Y_train = train["label"] # Drop 'label' column X_train = train.drop(labels = ["label"],axis = 1) # free some space del train g = sns.countplot(Y_train) Y_train.value_counts() # Check for null and missing values X_train.isnull().any().describe() test.isnull().any().describe() # Normalize the data X_train = X_train / 255.0 test = test / 255.0 # Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1) X_train = X_train.values.reshape(-1,28,28,1) test = test.values.reshape(-1,28,28,1) # Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0]) Y_train = to_categorical(Y_train, num_classes = 10) # Set the random seed random_seed = 2 # Split the train and the validation set for the fitting X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed) # Some examples g = plt.imshow(X_train[0][:,:,0]) # Set the CNN model # my CNN architechture is In -> [[Conv2D->relu]*2 -> MaxPool2D -> Dropout]*2 -> Flatten -> Dense -> Dropout -> Out model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu', input_shape = (28,28,1))) model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu')) model.add(MaxPool2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu')) model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu')) model.add(MaxPool2D(pool_size=(2,2), strides=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(256, activation = "relu")) model.add(Dropout(0.5)) model.add(Dense(10, activation = "softmax")) # Define the optimizer optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) # Compile the model model.compile(optimizer = optimizer , loss = "categorical_crossentropy", metrics=["accuracy"]) # Without data augmentation i obtained an accuracy of 0.98114 #history = model.fit(X_train, Y_train, batch_size = batch_size, epochs = epochs, # validation_data = (X_val, Y_val), verbose = 2) # With data augmentation to prevent overfitting (accuracy 0.99286) datagen = ImageDataGenerator( featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180) zoom_range = 0.1, # Randomly zoom image width_shift_range=0.1, # randomly shift images horizontally (fraction of total width) height_shift_range=0.1, # randomly shift images vertically (fraction of total height) horizontal_flip=False, # randomly flip images vertical_flip=False) # randomly flip images datagen.fit(X_train) # Fit the model history = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size), epochs = epochs, validation_data = (X_val,Y_val), verbose = 2, steps_per_epoch=X_train.shape[0] // batch_size , callbacks=[learning_rate_reduction]) # Plot the loss and accuracy curves for training and validation fig, ax = plt.subplots(2,1) ax[0].plot(history.history['loss'], color='b', label="Training loss") ax[0].plot(history.history['val_loss'], color='r', label="validation loss",axes =ax[0]) legend = ax[0].legend(loc='best', shadow=True) ax[1].plot(history.history['acc'], color='b', label="Training accuracy") ax[1].plot(history.history['val_acc'], color='r',label="Validation accuracy") legend = ax[1].legend(loc='best', shadow=True) # Look at confusion matrix def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') # Predict the values from the validation dataset Y_pred = model.predict(X_val) # Convert predictions classes to one hot vectors Y_pred_classes = np.argmax(Y_pred,axis = 1) # Convert validation observations to one hot vectors Y_true = np.argmax(Y_val,axis = 1) # compute the confusion matrix confusion_mtx = confusion_matrix(Y_true, Y_pred_classes) # plot the confusion matrix plot_confusion_matrix(confusion_mtx, classes = range(10)) # Errors are difference between predicted labels and true labels errors = (Y_pred_classes - Y_true != 0) Y_pred_classes_errors = Y_pred_classes[errors] Y_pred_errors = Y_pred[errors] Y_true_errors = Y_true[errors] X_val_errors = X_val[errors] def display_errors(errors_index,img_errors,pred_errors, obs_errors): """ This function shows 6 images with their predicted and real labels""" n = 0 nrows = 2 ncols = 3 fig, ax = plt.subplots(nrows,ncols,sharex=True,sharey=True) for row in range(nrows): for col in range(ncols): error = errors_index[n] ax[row,col].imshow((img_errors[error]).reshape((28,28))) ax[row,col].set_title("Predicted label :{}\nTrue label :{}".format(pred_errors[error],obs_errors[error])) n += 1 # Probabilities of the wrong predicted numbers Y_pred_errors_prob = np.max(Y_pred_errors,axis = 1) # Predicted probabilities of the true values in the error set true_prob_errors = np.diagonal(np.take(Y_pred_errors, Y_true_errors, axis=1)) # Difference between the probability of the predicted label and the true label delta_pred_true_errors = Y_pred_errors_prob - true_prob_errors # Sorted list of the delta prob errors sorted_dela_errors = np.argsort(delta_pred_true_errors) # Top 6 errors most_important_errors = sorted_dela_errors[-6:] # Show the top 6 errors display_errors(most_important_errors, X_val_errors, Y_pred_classes_errors, Y_true_errors)
bb15b4f27a1286c8f2f3d8d4136a9c7df7bd494d
its-rose/Python_3.8_Classwork
/OOP3.py
2,690
3.765625
4
# Магичеcкие методы # Method __hash__ # class User: # def __init__(self, name, email): # self.name = name # self.email = email # # def __hash__(self): # return hash(self.email) # # def __eq__(self, obj): # return self.email == obj.email # # john = User('John Connor', 'john@gmail.com') # sonya = User('Sonya Blade', 'sonya@gmail.com') # # print(john == sonya) # print(hash(john.email)) # print(hash(sonya.email)) # Method __getattr__ / __getattribute__ # class Researcher(): # def __getattr__(self, name): # return 'Nothing found!' # def __getattribute__(self, name): # return 'nope' # # obj = Researcher() # # print(obj.attr) # print(obj.method) # print(obj.DFG2H3J00KLL) # class Researcher(): # def __getattr__(self, name): # return 'Nothing found!' # # def __getattribute__(self, name): # print('Looking for {}', format(name)) # return object.__getattribute__(self, name) # # obj = Researcher() # # print(obj.attr) # print(obj.method) # print(obj.DFG2H3J00KLL) # Method __setattr__ # class Ignorant(): # def __setattr__(self, name, value): # print(f'Not gonna set {name}!') # # obj = Ignorant() # obj.math = True # # print(obj.math) # Method __getattr__ # class Polite(): # def __delattr__(self, name): # value = getattr(self, name) # print(f'Goodbye {name}, you were {value}!') # object.__delattr__(self, name) # # obj = Polite() # # obj.attr = 10 # del obj.attr # Method __call__ # class Logger(): # def __init__(self, filename): # self.filename = filename # # def __call__(self, func): # def wrapper(*args, **kwargs): # with open(self.filename, 'a') as f: # f.write('Oh Danny boy...') # # return func(*args, **kwargs) # return wrapper # # logger = Logger('index.txt') # @logger # Method __add__ and __sub__ # import random # class NoisyInt(): # def __init__(self, value): # self.value = value # # def __add__(self, obj): # noise = random.uniform(-1, 1) # return self.value + obj.value + noise # # a = NoisyInt(10) # b = NoisyInt(20) # # for _ in range(3): # print(a + b) # Method __getitem__ and __setitem__ # class PascalList: # def __init__(self, original_list=None): # self.container = original_list or [] # # def __getitem__(self, index): # return self.container[index - 1] # # def __setitem__(self, index, value): # self.container[index - 1] = value # # def __str__(self): # return self.container.__str__() # # numbers = PascalList([1, 2, 3, 4, 5]) # print(numbers[5])
cb5276198a5c3483b0d2b0f414fba9ec6850d886
wysocki-lukasz/CODEME-homework
/04_Kolekcje/1_Zadanie_1.py
287
3.640625
4
# Stwórz listę przedmiotów, które zabierzesz na samotną wyprawę w góry. # Elementy na liście posortuj alfabetycznie, a następnie wyświetl. items = ['ksiazka', 'termos', 'czpka', 'mapa', 'plecka', 'aparat'] print(items) items_mod = sorted(items, key=str.lower) print(items_mod)
5a22eed6b3901f81239e26d93e18ef0a610043af
santhosh-kumar/AlgorithmsAndDataStructures
/python/problems/array/find_min_in_sorted_rotated_array_with_duplicates.py
1,623
3.84375
4
""" Find Min In Sorted Rotated Array (with duplicates) If the rotated sorted array could contain duplicates? Is your algorithm still O(log n) in runtime complexity? """ from common.problem import Problem class FindMinInSortedRotatedArrayWithDuplicates(Problem): """ Find Min In Sorted Rotated Array (with duplicates) """ PROBLEM_NAME = "FindMinInSortedRotatedArrayWithDuplicates" def __init__(self, input_list): """Find Min In Sorted Rotated Array (with duplicates) Args: input_list: Contains a list of integers (sorted) Returns: None Raises: None """ super().__init__(self.PROBLEM_NAME) self.input_list = input_list def solve(self): """Solve the problem Note: For case where AL == AM == AR, the minimum could be on AM’s left or right side (eg, [1, 1, 1, 0, 1] or [1, 0, 1, 1, 1]). In this case, we could not discard either subarrays and therefore such worst case degenerates to the order of O(n). Args: Returns: integer Raises: None """ left = 0 right = len(self.input_list) - 1 while left < right and self.input_list[left] > self.input_list[right]: middle = int((left + right) / 2) if self.input_list[middle] > self.input_list[right]: left = middle + 1 elif self.input_list[middle] < self.input_list[left]: right = middle else: left = left + 1 return self.input_list[left]
caa991d0433433cc864ce92644f346721c978c29
digitalMirko/PythonReview
/python_review10_file_io.py
1,047
3.875
4
# Python Programming Review # file name: python_review10_file_io.py # JetBrains PyCharm 4.5.4 under Python 3.5.0 import random # random number generator import sys # sys module import os # operating system # file io or input output # create or open a file # opening a file called "test.txt", wb allows you to write to the file test_file = open("test.txt", "wb") # output on screen file mode being used in this situation, wb print(test_file.mode) # outputs: wb # if you forgot your file name, this will remind you print(test_file.name) # outputs: test.txt # write text to a screen or to a file test_file.write(bytes("Write me to the file\n", 'UTF-8')) # close a file test_file.close() # read information from a file # open file, reading and writing (r+) test_file = open("test.txt","r+") # read the data out of the file text_in_file = test_file.read() # print out the info print(text_in_file) # outputs: Write me to the file # delete the file, use the os module, put in file name ("") # and its removed os.remove("test.txt")
6f6706447e564cbd6f16fff3fe2b905d2d7e3fdb
ugiacoman/Basics
/02calc/cylinder.py
784
4.6875
5
# CS 141 lab 2 # cylinder.py # # Modified by: Ulises Giacoman # # This program calculates the volume, surface area and circumference of # a cylinder with values for the radius and height provided by the user import math # Prompts and converts to float the radius and height of the cylinder radius = float(input("Enter the radius of the cylinder: ")) height = float(input("Enter the height of the cylinder: ")) # Calculate the circumference of cylinder circum = 2 * math.pi * radius # Calculate the surface area of cylinder surfArea = 2 * math.pi * radius * height # Calculate the volume of cylinder volume = math.pi * (radius ** 2) * height # Display the results on the screen print(" The circumference is", circum) print(" The surface area is", surfArea) print(" The volume is", volume)
2303ea5af1614c9f10efa4e3ecc22b61b2a30d84
SimplyClueless/DigitalSolutions2021
/Classwork/Python/ConsecutiveLetters.py
205
3.8125
4
def consecutiveLetters(word): for cycle in range(0, len(word), 1): if word[cycle-1:cycle] == word[cycle:cycle+1]: return True return False print(consecutiveLetters(input("Enter a word: ")))
3a08c46d3f642e171a1fcda873dca9e20004cfdd
AadityaDeshpande/LP3
/assign7/diffie.py
899
3.828125
4
import random def generateKey(): num1=random.randint(2,9999) num2=random.randint(2,9999) flag=isPrime(num1) flag2=isPrime(num2) if flag==0 and flag2==0: print("{} and {} is a prime number".format(num1,num2)) x=random.randint(0,9999) print("x is {}".format(x)) y=random.randint(0,9999) print("y is {}".format(y)) A=(num2**x)%num1 print("A is (num2^x)mod num1 = {}".format(A)) B=(num2**y)%num1 print("B is (num2^y)mod num1 = {}".format(B)) key1=(B**x)%num1 key2=(A**y)%num1 print("Key1 is {}".format(key1)) print("Key2 is {}".format(key2)) return num1,num2 else: generateKey() def isPrime(num): flag=0 r=int(num/2) for i in range(2,r): if(num%i==0): flag=1 break i=i+1 return flag generateKey()
efcdaac5d6670c562bd356f06a68d5c860ede1af
akshitMadaan/CustomUserModel
/function.py
393
3.859375
4
x = int(input("Enter the value of x:")) print (x) print(type(x)) n = int(input("Enter the value of n:")) print(n) print(type(n)) sum=0 def first(x,n): sum=0 for i in range(1,n+1): sum += 1/x**i print(sum) first(x,n) def second(x,n,sum): if n==0: return 0 else: sum = 1/(x**n) + second(x,(n-1),sum) return sum x = second(x,n,sum) print(x)
e1f5e702940c2473b3cf2a7e287d89e95a7bcac8
Superbeet/PrimeMultiplicationTable
/PrimeMultiplicationTable.py
3,779
3.859375
4
import math class PrimeMultiplicationTable(object): def get_primes_3(self, num): """ Time Complexity = O(N) Space = O(N) """ if num <= 0: return [] if num == 1: return [2] size = self.prime_bound(num) res = [] count = 0 is_prime = [True]*size is_prime[0] = False is_prime[1] = False for i in xrange(2, size): if is_prime[i]: res.append(i) count += 1 if count == num: break for j in xrange(0, count): if i*res[j] >= size: break is_prime[i*res[j]] = False if i%res[j] == 0: break return res def get_primes_2(self, num): """ Time Complexity = O(NloglogN) Space = O(N) """ if num <= 0: return [] if num == 1: return [2] size = self.prime_bound(num) is_prime = [True]*size is_prime[0] = False is_prime[1] = False sqrt_size = int(math.sqrt(size))+1 for i in range(2, sqrt_size): if is_prime[i]: for j in range(i*i, size, i): is_prime[j] = False res = [] count = 0 for j in xrange(0, size): if is_prime[j]: res.append(j) count += 1 if count == num: break return res def get_primes_1(self, num): """ Time Complexity < O(n^1.5) Space = O(1) """ if num <= 0: return [] if num == 1: return [2] res = [2] count = 1 target = 3 while count < num: is_prime = True for prime in res: if prime > int(math.sqrt(target)): break if target % prime == 0: is_prime = False break if is_prime: res.append(target) count += 1 target += 2 return res def prime_bound(self, num): """ Approximate upper bound of the value of the nth prime """ if num <= 10: size = 30 else: factor = 1.3 size = int(num*math.log(num, math.e)*factor) return size def get_primes(self, num): return self.get_primes_3(num) def print_row(self, nums, name, width): items = map(str, nums) row = '{0: >{width}} |'.format(name, width = width + 1) for item in items: row += '{0: >{width}}'.format(item, width = width + 1) print row def print_cutting_line(self, length, width): print "-"*(length+2)*(width + 1) def generate_prime_table(self, num): """ Generate the prime table with dynamic col widths """ if num <= 0 or num is None: print "the table is empty" return primes = self.get_primes(num) # Dynamically calculate the maximum col width size = self.prime_bound(num) max_digits = len(str(size)) * 2 # Print the header row self.print_row(primes, " "*max_digits, max_digits) self.print_cutting_line(len(primes), max_digits) # Print the muplication table for x in primes: row = [] for y in primes: row.append(x*y) self.print_row(row, x, max_digits) if __name__ == "__main__": prime_muplication = PrimeMultiplicationTable() prime_muplication.generate_prime_table(10)
d6032c898cd6e7aa306a4e701290877c70b1fb11
matheus-Casagrande/ProjetoSudoku-ES4A4
/testes/testes_Ranking/teste1_confereExistenciaArquivo.py
1,368
3.5625
4
''' Este teste serve para testar a existência do arquivo 'ranking.txt' no diretório 'jogo' Neste módulo, importa-se o módulo "posiciona_amostra" que vai tentar copiar o arquivo se o mesmo existir na pasta 'jogo'. Se não for criado um 'ranking.txt' dentro dessa pasta de testes, é porque o ranking.txt original não existe. Este módulo é importante também porque ele dará um "refresh" e vai excluir o ranking.txt antigo, se o mesmo estiver aqui. Atualizando com o 'ranking.txt' da pasta 'jogo' ''' from posiciona_amostra import copiarRankingTxt import os def testarExistenciaArquivo(): # Remove o arquivo 'ranking.txt' do diretório 'testes_Ranking' se o mesmo existir try: os.remove('ranking.txt') except: pass # Copia o ranking.txt do diretório 'jogo' para o diretório 'testes_Ranking', se este existir copiarRankingTxt() try: f = open('ranking.txt', 'r') string = f.read() f.close() # Envia para frente a string do conteúdo de "ranking.txt" return string except: return False print(f'\n\033[;33;40m"Teste 1: confere existência do arquivo ranking" passado?\033[m {testarExistenciaArquivo() is not False}') if testarExistenciaArquivo(): print('--- Conteúdo do arquivo ---') print(testarExistenciaArquivo()) print('--- Fim do arquivo ---')
6451affd3d7597ca1f26cf5bf1110362a2865cf8
shradhakapoor/practice-codes
/binary_search_tree.py
20,179
3.78125
4
import os __path__ = [os.path.dirname(os.path.abspath(__file__))] from . import binary_tree class Queue(object): def __init__(self): self.items = [] def enqueue( self, item ): self.items.insert(0, item) def dequeue( self ): return self.items.pop() def is_empty( self ): return len(self.items) == 0 class Stack(object): def __init__(self): self.items = [] def push( self, item ): self.items.append(item) def pop( self ): if not self.is_empty: return self.items.pop() return def is_empty( self ): return len(self.items) == 0 class Node(object): def __init__(self, value=None): self.value = value self.left = None self.right = None class Binary_Search_Tree(object): def __init__(self, value): self.node = Node(value) # insert element def insert( self, value ): if self.node is None: self.node = Node(value) else: self._insert(self.node, value) def _insert( self, node, value ): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert(node.left, value) elif value > node.value: if node.right is None: node.right = Node(value) else: self._insert(node.right, value) else: #if value == node.value: add the value as a list to this node.value print('Value already in tree') # print tree-- Inorder traversal def print( self ): if self.node is None: return return(self._print(self.node)) def _print( self, node ): if node is None: return if node.left: self._print( node.left ) print(node.value, end=' ') if node.right: self._print(node.right) # Tree sorting def tree_sort(self, node): # Using recursion # print elements in inorder traversal # using iteration stack = Stack() done = 0 curr = node while not done: # reach the leftmost node of current node if curr: stack.push(curr) curr = curr.left else: # backtrack from empty subtree up towards the top of stack if not stack.is_empty(): curr = stack.items.pop() print(curr.value, end=', ') # we have visited the node , its left subtree. Now we visit its right subtree curr = curr.right else: done = 1 # find an element, with recursion def search_with_recursion( self, item ): if item is None or self.node is None: return False return self._search_with_recursion(self.node, item) def _search_with_recursion( self, node, item ): if node is None: return False elif node.value == item: return True elif item < node.value: return self._search_with_recursion(node.left, item) else: return self._search_with_recursion(node.right, item) # find an element, iteratively def search_with_iteration( self, item ): if item is None or self.node is None: return False node = self.node while node: if item > node.value: node = node.right elif item < node.value: node = node.left else: return True return False # height of tree def height( self, node ): if node is None: return 0 else: return 1 + max(self.height(node.left), self.height(node.right)) # find maximum element in tree(with recursion) def maximum_element_with_recursion( self ): if self.node is None: print('Tree doesn\'t exist!') else: print('Maximum element recursively is: '+str(self._max_element_with_recursion(self.node))) max_elem = float( '-inf' ) def _max_element_with_recursion( self, node): if node: if node.value > self.max_elem: self.max_elem = node.value self._max_element_with_recursion(node.left) self._max_element_with_recursion(node.right) return self.max_elem # find minimum element in tree(without recursion) def minimum_element_with_iteration( self, node ): if node is None: return curr = node while curr.left: curr = curr.left return curr.value # check if binary tree is BST or not, complexity O(n^2) def check_binarytree_is_bst( self, node ): # empty tree is BST if node is None: return True # return false if max of node.left is > than node.value if node.left and self._max_element_with_recursion(node.left) > node.value: return False # return false if min of node.right is ≤ then node.value if node.right and self.minimum_element_with_iteration(node.right) < node.value: return False # return false if recursively left subtree or right subtree is not BST if not self.check_binarytree_is_bst(node.left) or not self.check_binarytree_is_bst(node.right): return False # if passed all above conditions then its a BST return True # check if binary tree is BST or not, complexity O(n) def check_binarytree_is_bst_effeciently( self, node ): if node is None: return True return self._check_binarytree_is_bst_effeciently(node, float('-inf'), float('inf')) def _check_binarytree_is_bst_effeciently( self, node, min_value, max_value ): if node is None: return True # return false if node.value violates min max constraint if node.value < min_value or node.value > max_value: return False # otherwise check subtrees are recursively tightening the min or max constraint return (self._check_binarytree_is_bst_effeciently(node.left, min_value, node.value-1) and self._check_binarytree_is_bst_effeciently(node.right,node.value+1, max_value)) # find k-th smallest element(recursively) def kth_smallest_element( self, k ): if self.node is None or k is None: return stack = Stack() return self._kth_smallest_element(self.node, stack).items[k-1] def _kth_smallest_element( self, node, stack ): # inorder traversal to store the elements of bst in sorted order if node: self._kth_smallest_element(node.left, stack) stack.push(node.value) self._kth_smallest_element(node.right, stack) return stack # given 2 nodes, find the lowest common ancestor in BST def lowest_common_ancestor( self, node, value1, value2 ): if node is None: return if node.value > max(value1, value2): return self.lowest_common_ancestor(node.left, value1, value2) elif node.value < min(value1, value2): return self.lowest_common_ancestor(node.right, value1, value2) else: return node # find shortest distance between 2 nodes def shortest_distance_between_two_nodes( self,node, value1, value2 ): if node is None: return 0 if node.value > max(value1, value2): return self.shortest_distance_between_two_nodes(node.left, value1, value2) if node.value < min(value1, value2): return self.shortest_distance_between_two_nodes(node.right, value1, value2) if value1 <= node.value <= value2 or value2 <= node.value <= value1: return self.distance_from_node(node, value1) + self.distance_from_node(node, value2) def distance_from_node( self, node, value ): if node.value == value: return 0 elif node.value > value: return 1+ self.distance_from_node(node.left, value) else: return 1+ self.distance_from_node(node.right, value) # count number of BSTs possible with n nodes = catalan number (2nCn)/n+1 = 2n! / (n+1! n!) # count of number of Binary Trees with n nodes = n! * catalan number def count_of_BST_possible( self, n ): if n is None: return 0 # calculate 2n! twice_n = 1 tn = (2 * n) + 1 for i in range(1, tn): twice_n = twice_n * i # calculate n! single_n = 1 for i in range(1, n+1): single_n *= i # find n+1! by n! * n+1 n_1 = single_n * (n + 1) # result = catalan number result = twice_n / (single_n * n_1) return result # convert sorted array to BST, time complexity O(n) def sorted_array_to_bst( self, arr ): if len(arr) == 0: return if len(arr) == 1: node = Node(arr[0]) return node mid = len(arr)//2 node = Node(arr[mid]) if arr[mid-1] < arr[mid+1]: arr1 = arr[0:mid] arr2 = arr[(mid+1):] else: arr1 = arr[(mid + 1):] arr2 = arr[0:mid] node.left = self.sorted_array_to_bst(arr1) node.right = self.sorted_array_to_bst(arr2) return node # find floor of given data (largest data <= given data) def floor_of_given_value( self, node, value ): if node is None: return -1 if node.value == value: return node.value # if node.value > value, then floor would be in left subtree if node.value > value: if node.left: return self.floor_of_given_value(node.left, value) # if node.value < value then floor is either the node or in right subtree if node.right: right_value = self.floor_of_given_value(node.right, value) return right_value if right_value <= value else node.value return node.value # find ceiling of given data (smallest data > given data) def ceil_of_given_value( self, node, value ): if node is None: return -1 # equal to key value if value == node.value: return node.value # if node.value < value, ceil must be in right subtree if node.value < value: if node.right: return self.ceil_of_given_value(node.right, value) # if node.value > value, ceil is either node.value or in left subtree if node.left: left_value = self.ceil_of_given_value(node.left, value) return left_value if left_value >= value else node.value return node.value # print all elements in increasing order in range r1 to r2 def print_all_in_range( self, node, r1, r2 ): if node is None: return # since desired output is sorted, recurse for left subtree first # if node.value > r1 only then we can get elements in left subtree if r1 < node.value: self.print_all_in_range(node.left, r1, r2) if r1 <= node.value <= r2: print (node.value, end=', ') # if r2 > node.value only then we can get elements in right subtree if r2 > node.value: self.print_all_in_range(node.right, r1, r2) # remove BST elements outside the given range, and modified tree should also be BST def remove_elements_outside_range( self, node, r1, r2 ): if node is None: return # basically we need to fix the tree in post-order fashion node.left = self.remove_elements_outside_range(node.left, r1, r2) node.right = self.remove_elements_outside_range(node.right, r1, r2) # now fix the node if node is not in range # case 1: node.value < r1, delete node and return right subtree if node.value < r1: right_child = node.right self.delete(node, node.value) return right_child # case 2: if node.value > r2, delete node and return left subtree if node.value > r2: left_child = node.left self.delete(node, node.value) return left_child return node # delete an element def delete( self, node, item): if node is None: return False # if value to be deleted is less than node then the value lies in left subtree if item < node.value: node.left = self.delete(node.left, item) # if value to be deleted is greater than node then the value lies in right subtree elif item > node.value: node.right = self.delete(node.right, item) # else the value is same as node.value else: # case 1: node to be deleted has 1 child or no child if node.left is None: return node.right if node.right is None: return node.left # case 2: node to be deleted has 2 children # get the inorder successor of node node temp = node.right while temp.left is not None: temp = temp.left smallest_value = temp # copy inorder successor node.value to this node.value node.value = smallest_value.value # delete the inorder successor node.right = self.delete(node.right, smallest_value.value) return node # tell inorder successor of given key in BST def inorder_successor( self, node ): if node is None: return # case 1: if node has right subtree then go to left most element in right subtree if node.right: temp = node.right while temp.left: temp = temp.left return temp # case 2: if node doesn't have right subtree # then search that node starting from root and the node from where we take the last left is the answer tmp = self.node parent = None while tmp.value != node.value: if node.value < tmp.value: parent = tmp tmp = tmp.left else: tmp = tmp.right return parent # tell the predecessor of a node in BST def inorder_predecessor( self, node ): if node is None: return # case 1: if node has left subtree then go to right most element in left subtree if node.left: temp = node.left while temp.right: temp = temp.right return temp # case 2: if node doesn't have left subtree # then search that node starting from node and the node from where we take the last right is the answer tmp = self.node parent = None while tmp.value != node.value: if node.value > tmp.value: parent = tmp tmp = node.right else: tmp = node.left return parent # convert sorted singly linked list to height balanced BST cur = None def sorted_ll_to_bst( self, list_head ): if not list_head: return self.cur = list_head n = self.getSize_of_list(list_head) return self._sorted_ll_to_bst(n) def _sorted_ll_to_bst( self, list_size ): if list_size <= 0: return left = self._sorted_ll_to_bst(list_size//2) root = Node(self.cur.value) self.cur = self.cur.right # traversing the linked list, cur = cur.next right = self._sorted_ll_to_bst(list_size - int(list_size/2) -1) root.left = left root.right = right return root def getSize_of_list( self, head ): n = 0 while head: head = head.right n += 1 return n # check whether elements of 2 BSTs are same or not (order of elements doesn't matter) def check_elements_same_in_bsts( self, node, node2 ): # base cases if not node and not node2: return True if (node2 and not node) or (node and not node2): return False # create 2 sets and store elements in both bsts to it set1, set2 = set(), set() self._insert_to_set(node, set1) self._insert_to_set(node2, set2) return set1 == set2 def _insert_to_set( self, node, s ): if not node: return self._insert_to_set(node.left, s) s.add(node.value) self._insert_to_set(node.right, s) # convert BST to circular doubly linked list with space complexity(1) prev = None def bst_to_circular_doubly_linkedlist( self, node, head ): # initially, node points to node of the linked list and head is None if node is None: return # basically we are doing inorder traversal and inside we write steps for converting bst to dll self.bst_to_circular_doubly_linkedlist( node.left, head ) if self.prev is None: head = node else: node.left = self.prev self.prev.right = node # make current node as prev node self.prev = node self.bst_to_circular_doubly_linkedlist( node.right, head ) # BST # 500 # / \ # 400 800 # / \ / \ # 200 450 700 900 bst = Binary_Search_Tree(500) bst.insert(400) bst.insert(800) bst.insert(200) bst.insert(450) bst.insert(700) bst.insert(900) print('In-order tree traversal:', end=' ') bst.print() print('\nTree sort in ascending order:', end=' ') bst.tree_sort(bst.node) print('\nSearch an item recursively: ', str(bst.search_with_recursion(700))) print('Search an item iteratively: ', str(bst.search_with_iteration(700))) print('height of tree:', str(bst.height(bst.node))) print('Minimum element in tree(iteratively):', str(bst.minimum_element_with_iteration(bst.node))) # binary tree # 310 # / \ # 200 400 # / \ / # 140 250 350 tree = binary_tree.BinaryTree(310) tree.node.left = Node(200) tree.node.right = Node(400) tree.node.left.left = Node(140) tree.node.left.right = Node(250) tree.node.right.left = Node(350) print('Binary tree', end = ' ') tree.print_tree() print('\nIs this binary tree a bst?(non-effecient solution):', str(bst.check_binarytree_is_bst(tree.node))) print('Is this binary tree a bst?(effecient solution):', str(bst.check_binarytree_is_bst_effeciently(tree.node))) print('kth smallest element in tree:', str(bst.kth_smallest_element(2))) print('lowest common ancestor of two nodes:', str(bst.lowest_common_ancestor(bst.node, 700, 900).value)) print('shortest distance between two nodes:', str(bst.shortest_distance_between_two_nodes(bst.node, 200, 800))) print('count of number of BSTs possible with n nodes:', str(bst.count_of_BST_possible(7))) print('\nConvert sorted array to BST:', end=' ') bst._print(bst.sorted_array_to_bst([70,60,50,40,30,20,10])) print('\nFloor of given value:', bst.floor_of_given_value(bst.node, 810)) print('ceiling of given value:', bst.ceil_of_given_value(bst.node, 720)) print('Inorder successor of node:', str(bst.inorder_successor(bst.node).value)) print('Inorder predecessor of node:', str(bst.inorder_predecessor(bst.node).value)) print('Print all elements in the range r1 to r2 in increasing order:') bst.print_all_in_range(bst.node, 100, 900) print('\nRemove all elements outside the range:', end=' ') bst._print(bst.remove_elements_outside_range(bst.node, 100, 750)) print('\nDelete a node in tree:', end=' ') bst._print(bst.delete(bst.node, 500)) # 5->100->2050->10000 linked_list = Node(5) linked_list.right = Node(100) linked_list.right.right = Node(2050) linked_list.right.right.right = Node(10000) print('\nConvert sorted linked list to bst:',end = ' ') bst._print(bst.sorted_ll_to_bst(linked_list)) print('\nCheck whether 2 BSTs have same set of elements', bst.check_elements_same_in_bsts(bst.node, bst.node)) # print('\nConvert BST to circular doubly linked list:', end='\n ') # bst.bst_to_circular_doubly_linkedlist(bst.node, None)
f135f48ec8203046e3adb8beca1517eee02fa451
wangfeng351/Python-learning
/语法基础/practise/数据库操作.py
503
3.5625
4
""" 数据库常规操作 """ import pymysql def data_select(): # 数据库连接 db = pymysql.connect("localhost", "root", "root", "db_python") # 获得游标 cursor = db.cursor() sql = "SELECT * FROM t_follower WHERE gender>-1" try: cursor.execute(sql) # 执行sql results = cursor.fetchall() # 打印结果 print(results) except: db.rollback() finally: db.close() if __name__ == "__main__": data_select()
89649a2c7cf069bd45fb91ce69b72a9c5a22ca1d
yuanxu-li/careercup
/chapter8-recursion-and-dynamic-programming/8.5.py
2,170
4.78125
5
# 8.5 Recursive Multiply: Write a recursive function to multiply two numbers without using the * operator. # You can use additions, subtraction, and bit shifting, but you should minimize the number of those operations. def multiply_recursive(x, y): """ x can be seen as x1x2, while y as y1y2. steps are listed as follows: 1. compute x1y1, call the result A 2. compute x2y2, call the result B 3. compute (x1+x2)(y1+y2), call the result C 4. compute C-A-B, call the result K; this number is equal to x1y2+x2y1 5. compute A*2^(2m)+K*2^m+B >>> multiply_recursive(4, 18) 72 >>> multiply_recursive(38, 41) 1558 >>> multiply_recursive(1001, 1002) 1003002 """ length1 = bit_length(x) length2 = bit_length(y) if length1 == 0 or length2 == 0: return 0 elif length1 == 1: return y elif length2 == 1: return x else: m = max(length1, length2) // 2 x1 = x >> m x2 = ((1 << m) - 1) & x y1 = y >> m y2 = ((1 << m) - 1) & y A = multiply_recursive(x1, y1) B = multiply_recursive(x2, y2) C = multiply_recursive(x1 + x2, y1 + y2) K = C - A - B return (A << (2*m)) + (K << m) + B def bit_length(num): """ >>> bit_length(4) 3 >>> bit_length(5) 3 >>> bit_length(1024) 11 """ l = 0 while num > 0: num >>= 1 l += 1 return l def multiply_recursive_updated(x, y): """ Make sure x is always not greater than y as inputs Example: to compute 20 * 45, we recursively compute 10 * 25, and add it to itself as the result; to compute 19 * 45, we recursively compute 9 * 45, add it to itself, and add 45 the larger number to it as the result; base case is 1 * y or 0 * y. By reducing x the smaller number instead of y the larger number, we save time by reaching the base case faster. >>> multiply_recursive_updated(4, 18) 72 >>> multiply_recursive_updated(38, 41) 1558 >>> multiply_recursive_updated(1001, 1002) 1003002 """ # base case if x == 0: return 0 elif x == 1: return y # recursive case temp_x = x >> 1 half_prod = multiply_recursive_updated(temp_x, y) if x % 2 == 0: return half_prod + half_prod else: return half_prod + half_prod + y if __name__ == "__main__": import doctest doctest.testmod()
16277b77664f34487b6c135339c76582814413a1
Adrncalel/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,262
3.765625
4
#!/usr/bin/python3 """ This is the matrix_divided module. It has the function of modifyinf certain aspects of bidimensional matrixes. """ def matrix_divided(matrix, div): """This function recieves a bidimensional matrix and a divisior, it returns the matrix with the values divided by the given divisor. """ """new_l = [x[:] for x in matrix]""" T_error = "matrix must be a matrix (list of lists) of integers/floats" O_error = "Each row of the matrix must have the same size" if isinstance(matrix, list) is False or not matrix or\ matrix is None: raise TypeError(T_error) for row in matrix: if isinstance(row, list) is False or not row or\ all(isinstance(m, (int, float)) for m in row) is False: raise TypeError(T_error) if len(row) != len(matrix[0]): raise TypeError(O_error) if div == 0: raise ZeroDivisionError("division by zero") if isinstance(div, (int, float)) is False or div is None: raise TypeError("div must be a number") return ([[round(m / div, 2) for m in n] for n in matrix]) """ for n in range(len(matrix)): for m in range(len(matrix[n])): new_l[n][m] = "fuck" print(new_l) """
4f1274f507b0887e72a77393b8f0663707ea4719
rheena/Python-basics
/Exception handling.py
1,106
4.34375
4
#When an exception happens the rest of the code does not get executed #Try and accept statements try: #put in all the code you want executed if an exception happens, you get into the except block x = int(input('First number: ')) y = int(input('Second number: ')) print(x / y) except: print('There was an error!') #Predefining the error to be looked out for try: a = int(input('First number: ')) b = int(input('Second number: ')) print(a / b) except ValueError: print('Please enter a valid number next time!') except ZeroDivisionError: print('Cannot divide by zero!') b = 1 print(a / b) finally: #The code will be executed no matter what print('DONE!') #Raising exceptions def some_function(): if True: raise ValueError ('Something went terribly wrong!') some_function() #Indirectly assert something. Asset statements are causing or raising exceptions if the condition they are given is not true x = 100 y = 20 assert(x < y) #This statement demands that x is less than y otherwise we terminate the script
93e1dbc2b3d3f8b8e5b2340505b6122800212e7a
xiaotaohe/Python_code
/Python_code/Sequence.py
3,466
4.46875
4
# coding=utf8 #目标:Sequence类型族 #序列类型族(String(字符串)、Tuple(元组)、List(列表)) #字符串操作 a = "Hello, I like python Web Practice" b = a[1] print("b = ",b) b = a[7:13] # I like print("b = ",b) print(a[:13]) #Hello, I like print(a[14:]) #pyth..... print("like" in a) # True print(a+"!!") # Hell........ !! print(a) print('ABC'*3) #重复生成 c = [2,4,"apple",5] print(c[1:]) # 4,"apple" 5 print(b+" "+c[2]) #I like apple #内置函数 b = [1,2,3,4] #list #1.迭代器enumerate for i,num in enumerate(b): print(u"第%d个数是: %d"%(i,num)) for i,num in enumerate(b): print(num) #2.函数len print("b len is ",len(b)) #3.list,将b转换为list print("b type is ",type(b)) c = list(b); print("c type is ",type(c)) #4.max函数 print("max in b is ",max(b)) print("max in the Sequence is ",max(1,4,6,3)) #6.min函数 print("min in b is ",min(b)) print("min in the Sequence is ",min(2,3,1,7)) #7.reversed反转 c = reversed(b) for i,num in enumerate(c): print(num) # 1.String str1 = "Hello,World!" #普通字符串 str2 = u"Hello,I'm unicode" #unicode字符串 str3 = u"你好,世界" #unicode字符串 print(str1," ",str2," ",str3) # 2.通用切片操作 print(str1[5]) print(str1[6:]) # 3.追加&删除 str1 += " I like Python" #以下两种操作效果一样 #str1 = str1[:5]+str1[-7:] str1 = str1[:5]+str1[19:] print(str1) # 4.字符串格式化 #1.格式化字符串指按照指定规则连接、替换字符串并返回新的符合要求的字符串 charA = 65 charB = 66 print(u"ASCII码65代表:%c "%charA) print(u"ASCII码66代表:%c "%charB) #2.格式标记字符串 print("%#x"%108) #十六进制数字 结果 0x6c print("%x"%108) #结果 6c print('%E'%1234.567890) #科学计数法 print('Host: %s\tPost: %d'%('python',90)) #多个参数 print('MM/DD/YY = %02d/%02d/%d'%(2,5,95)) #数字前补零 #3.内置函数 #split a = "hello, world!" c = a.split(",") print(c) #isalpha print(a.isalpha()) # 2.List #1.基本操作 mylist = ['you',456,'English',9.34] #定义 print(mylist[2]) #读取元素 print(mylist[1:]) #读取下标为1之后的所有元素 mylist[2] = 'France' #可以修改内容 print(mylist[0:]) numlist = [1,6,9,8,5,6,13,12] print(sorted(numlist)) #排序并打印 print(numlist) #排序后的numlist本身并不改变 print(sum(numlist)) #求和 #2.内置函数 numlist.append(67) #在列表末尾添加元素 print(numlist) print(numlist.count(1)) #查找某元素出现的次数 numlist.reverse() #反向本身是对序列有改变的 print(numlist) numlist.sort() print(numlist) #3.Set集合 #set定义普通集合 frozenset定义不可变集合 sample1 = set("understand") #用字符串初始化set print(sample1) sample2 = set(mylist) #用list初始化set sample2.add(9) print(sample2) sample3 = frozenset(mylist) print(sample3) #操作符 print(6 in sample1) #判断6是否在集合中 print(sample2>=sample3) #判断子集关系 print(sample2-sample3) #差运算 print(sample2&sample3) #交运算 sample3 |= sample2 #对frozenset执行 |= 重新复制 print(sample3) #内置函数 add update remove # 4.Dictionary 类型 dict1 = {'Langage':'English','Title':'Python book','Page':450} print(dict1['Title']) dict1['Date'] = '2002-10-30' #增加新的key-value print(dict1['Date']) dict1['Langage'] = 'Chinese' #根据key跟新value print(dict1) #内置函数copy(拷贝副本)、clear(清楚字典中的键值对) dict1.fromkeys(mylist) print(dict1)
3ebd38be546db2e8589a1ff8d8703ede235fb2a1
asiasarycheva/asia_homework
/HW-3/HW3-1.py
1,651
3.59375
4
import os, re, pickle patternint = '[0-9]+' patternengint = '[a-z, A-Z, 0-9]+' glacierlst = [] countrylst = [] arealst = [] answer = 1 while answer == 1: glacier = str(input('введите название ледника на русском ')) while re.match(patternengint, glacier): print('по-русски и без цифр! ') glacier = str(input('введите название ледника на русском ')) else: glacierlst = glacierlst + [glacier] country = str(input('введите страну ледника на русском ')) while re.match(patternengint, country): print('по-русски и без цифр! ') else: countrylst = countrylst + [country] area = str(input('введите площадь ледника на русском ')) if re.match(patternint, area): arealst = arealst + [area] else: print('только цифры! ') answer = int(input ('ввести новый ледник (1) или вывести результат (2) ?' )) else: f = open('data.pickle', 'wb') pickle.dump(glacierlst, f) pickle.dump(countrylst, f) pickle.dump(arealst, f) f.close() f = open('data.pickle', 'rb') glacierlst = pickle.load(f) countrylst = pickle.load(f) arealst = pickle.load(f) f.close() n = len(countrylst) for i in range (n): finallst = [glacierlst[i] + ' ' + countrylst[i] + ' ' + arealst[i]] sortedfinallst = sorted(finallst) print(sortedfinallst)
bbe31b4c967113abc5c2fd562a865c166ef185ca
shaokangtan/python_sandbox
/cruise_interview.py
657
3.875
4
#question: find the time when h, m, s all align on the same tick seconds = 24 * 60 * 60 def hand_sec(sec): tick = sec % 60 return tick def hand_min(sec): min = sec // 60 tick = min % 60 return tick def hand_hour(sec): min = sec // 60 hr = min // 60 tick = hr % 12 return tick * (60//12) import time for sec in range(0,seconds,1): s = hand_sec(sec) m = hand_min(sec) h = hand_hour(sec) #print ("{}:{}:{}".format(h,m,s)) if (s== m) and (m == h): #if (hand_sec(sec) == hand_hour(sec)): print (time.strftime('%H:%M:%S', time.gmtime(sec)))