blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
dfc1ca77079f4a880dd8a1a4ee136a9e54a4a59c
jinggz/entity-aspect-linking-toolkit
/src/nlp_preprocessing.py
1,029
3.59375
4
import nltk nltk.download('stopwords') nltk.download('punkt') nltk.download('wordnet') from nltk.corpus import stopwords from nltk import word_tokenize import string from nltk.stem.wordnet import WordNetLemmatizer lemmatizer = WordNetLemmatizer() punct = set(string.punctuation) stop_word_list = set(stopwords.words('english')) def nlp_pipeline(text_list): ''' this pipeline aims to do a series of preprocessing steps: tokenizing, punctuations and numbers removal, lemmatization :param:text_list :type: a list of str :return: a list of preprocessed str ''' string_list = [] for text in text_list: text = text.lower() text = word_tokenize(text) text = [token for token in text if token not in string.punctuation and token.isalpha()] text = [token for token in text if token not in stop_word_list] text = [lemmatizer.lemmatize(token) for token in text] wordstring = ' '.join(text) string_list.append(wordstring) return string_list
62173179b82185eeff452692c79fedbc91437b37
teknofage/SPD1.4-leetcode
/leet1431.py
747
3.75
4
class Solution: def kidsWithCandies(self, candies, extraCandies): candies = [2,3,5,1,3] extraCandies = 3 # return kid with largest stash of candy = fat_bastard # loop through list of kids with candy # for each kid in list, # if the sum of what they already have + extraCandies >= fat_bastard # return True for that kid, # else return False for that kid # keep going to end of list max_candy = max(candies) for index in range(len(candies)): if candies[index] + extraCandies >= max_candy: yield True else: yield False # Time complexity = O(n) # Space complexity = O(n) kidsWithCandies([2,3,5,1,3], 3)
3e8aa69c5938765bc9423fcbf0a4dcd177e73db0
AleksandraPrzybylska/Snake-Game
/utils.py
4,260
3.84375
4
import random import heapq as pq import heapq ###### Random seed - comment this line to randomize food # random.seed(10) ###### def check_neighbors(x1_change, y1_change, snake_block): if (x1_change > 0) and (y1_change == 0): x1_change = 0 y1_change = snake_block elif (x1_change == 0) and (y1_change > 0): x1_change = -snake_block y1_change = 0 elif (x1_change < 0) and (y1_change == 0): x1_change = 0 y1_change = -snake_block elif (x1_change == 0) and (y1_change < 0): x1_change = snake_block y1_change = 0 return x1_change, y1_change def generate_food(width, height, map, snake_block, snake_list=[]): foodValid = False while not foodValid: food_x = round(random.randrange(0, width - snake_block) / snake_block) * snake_block food_y = round(random.randrange(0, height - snake_block) / snake_block) * snake_block if map[int(food_y / snake_block)][int(food_x / snake_block)] == 0: # Prevent getting food on the obstacle if [food_x, food_y] in snake_list: foodValid = False # Prevent getting food on snake body continue return food_x, food_y def copy_map(map): map_copy = [] for r in map: row = [] for c in r: row.append(c) map_copy.append(row) return map_copy # Calculating the heuristics of the distance def heuristics(st, end): # distance = ((st[0] - end[0])**2 + (st[1] - end[1])**2)**(0.5) # Euclidean distance = abs(st[0] - end[0]) + abs(st[1] - end[1]) # Manhattan return distance def find_path_a_star(map, start, end, snake_block, snake_list): came_from = {} g_score = {start: 0} f_score = {start: heuristics(start, end)} oheap = [] # Add a starting vertex to the vertex set to visit heapq.heappush(oheap, (f_score[start], start)) # Create the copy of map map_copy = copy_map(map) # Get and mark the actual position of snake on the map for el in snake_list[:-1]: map_copy[int(el[1] / snake_block)][int(el[0] / snake_block)] = 80 current = None while oheap: # Until the set of vertices to visit is empty current = heapq.heappop(oheap)[1] # Take the vertex from the set whose f_score is the smallest # Check if this vertex is the end vertex if current == end: # if so end the algorithm and display the path break # Check if the current vertex is a free space if map_copy[int(current[1] / snake_block)][int(current[0] / snake_block)] == 0: # Mark this vertex as visited map_copy[int(current[1] / snake_block)][int(current[0] / snake_block)] = 50 neighbors = [] # Get neighbors of the current vertex for new in [(0, -snake_block), (0, snake_block), (-snake_block, 0), (snake_block, 0)]: position = (current[0] + new[0], current[1] + new[1]) # Check if the neighbor is a free space (allowed) if map_copy[int(position[1] / snake_block)][int(position[0] / snake_block)] == 0: neighbors.append(position) # For each of its neighbors, check the path length from the start to that neighbor for neigh in neighbors: cost = heuristics(current, neigh) + g_score[current] # cost of the path if cost < g_score.get(neigh, 0) or neigh not in g_score: came_from[neigh] = current # Set the current considered vertex as the parent of this neighbor g_score[neigh] = cost f_score[neigh] = cost + heuristics(neigh, end) # Set the current distance as the shortest one pq.heappush(oheap, (f_score[neigh], neigh)) # Add to the vertex set to visit this neighbor temp_path = [] # our path # Going through the visited points and recreate the path from the end to the start while current in came_from: temp_path.append(current) current = came_from[current] # Get the parent of the current point # Reversing the path (we want the start to be the first point of the path) return temp_path[::-1]
90685549708d16ca7dd6468bc15a1cc33bb35918
tommyshere/ctci
/1-4_palindrome_permutation.py
928
4.03125
4
# Given a string, check if it is a permutation of a palindrome # Input: "Tact Coa" # Output: True (permutations: 'taco cat', 'atco cta', etc.) # can the words be rearrange to create a palindrome? # what is a palindrome? # same letters front and back # same count of letters # aa aba aaa abba abcba abccba # 2 2,1 3 2,2 2,2,1 2,2,2 # abca # 2,1,1 # you con only have >2 odd number in the dictionary class Solution(object): def pal_perm(): input = "Tact Coa" count = {} for x in input.lower(): if x != " " and x in count: count[x] = count[x] + 1 elif x != " " and x not in count: count[x] = 1 odd_count = 0 for val in count.values(): if val % 2 != 0: odd_count += 1 if odd_count < 2: return True return False if __name__ == "__main__": print(Solution.pal_perm())
5d6c46ebf6db8ad4fe9c087671f5adb85ceec0ac
robbiesri/advent-of-code-2018
/solutions/d2p1.py
585
3.5625
4
#!/usr/bin/env python3 import commonAOC from collections import Counter import string inputDataFile = commonAOC.loadInputData("d2.txt") total2count = 0 total3count = 0 for line in inputDataFile: count2 = False count3 = False counter = Counter(line) for k in string.ascii_lowercase: letterCount = counter[k] if letterCount == 2: count2 = True if letterCount == 3: count3 = True if count2: total2count += 1 if count3: total3count += 1 checksum = total2count * total3count print(checksum)
27e6736983e101b8cf7d064d74bb6962062fa762
cminnera/Cryptography
/week3.py
1,389
3.6875
4
# Clare Minnerath # Week 3 Cryptography assignment # hash video authentication from Crypto.Hash import SHA256 import binascii def create_test_file(): rawhex1 = b'\x11'*1024 rawhex2 = b'\x22'*1024 rawhex3 = b'\x33'*1024 rawhex4 = b'\x44'*773 e1 = open('b1','wb') e2 = open('b2','wb') e3 = open('b3','wb') e4 = open('b4','wb') t1 = open('test11223344','wb') e1.write(rawhex1) e2.write(rawhex2) e3.write(rawhex3) e4.write(rawhex4) t1.write(rawhex1+rawhex2+rawhex3+rawhex4) t1.close() e1.close() e2.close() e3.close() e4.close() def import_data_file(file_name): with open(file_name, 'rb') as f: content = f.read() return content def hex_to_blocks(hex_string): blocks = [] for i in range(0, len(hex_string), 1024): blocks.append(hex_string[i:i+1024]) return blocks def compute_h_0(blocks): blocks.reverse() for i in range(len(blocks)-1): h = SHA256.new() h.update(blocks[i]) blocks[i+1] += h.digest() h = SHA256.new() h.update(blocks[len(blocks)-1]) return h.hexdigest() def main(): file_hex = import_data_file("6.1.intro.mp4_download") # file_hex = import_data_file("6.2.birthday.mp4_download") # file_hex = import_data_file("test11223344") blocks = hex_to_blocks(file_hex) print("h_0 = ", compute_h_0(blocks)) main()
188b8d76e3944e28432f518092795a9f49624946
iewaij/ml-assignment
/2_Kernels/bank_mkt.py
8,850
3.90625
4
import pandas as pd def import_dataset(filename): """ Import the dataset from the path. Parameters ---------- filename : str filename with path Returns ------- data : DataFrame Examples -------- bank_mkt = import_dataset("BankMarketing.csv") """ bank_mkt = pd.read_csv( filename, na_values=["unknown", "nonexistent"], true_values=["yes", "success"], false_values=["no", "failure"], ) # Drop 12 duplicated rows bank_mkt = bank_mkt.drop_duplicates().reset_index(drop=True) # `month` will be encoded to the corresponding number, i.e. "mar" -> 3 month_map = { "mar": 3, "apr": 4, "may": 5, "jun": 6, "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12, } bank_mkt["month"] = bank_mkt["month"].replace(month_map) # Add days since lehman brothers bankcrupt bank_mkt.loc[bank_mkt.index < 27682, "year"] = 2008 bank_mkt.loc[(27682 <= bank_mkt.index) & (bank_mkt.index < 39118), "year"] = 2009 bank_mkt.loc[39118 <= bank_mkt.index, "year"] = 2010 bank_mkt["year"] = bank_mkt["year"].astype("int") bank_mkt["date"] = pd.to_datetime(bank_mkt[["month", "year"]].assign(day=1)) bank_mkt["lehman"] = pd.to_datetime("2008-09-15") bank_mkt["days"] = bank_mkt["date"] - bank_mkt["lehman"] bank_mkt["days"] = bank_mkt["days"].dt.days # Drop data before 2009 bank_mkt = bank_mkt.loc[bank_mkt.index > 27682, :] # Drop date and lehman columns bank_mkt = bank_mkt.drop(columns=["lehman", "year", "date"]) # Treat pdays = 999 as missing values -999 bank_mkt["pdays"] = bank_mkt["pdays"].replace(999, -999) # `day_of_week` will be encoded to the corresponding number, e.g. "wed" -> 3 dow_map = {"mon": 1, "tue": 2, "wed": 3, "thu": 4, "fri": 5} bank_mkt["day_of_week"] = bank_mkt["day_of_week"].replace(dow_map) # Convert types, "Int64" is nullable integer data type in pandas bank_mkt = bank_mkt.astype( dtype={ "contact": "category", "month": "Int64", "day_of_week": "Int64", "campaign": "Int64", "pdays": "Int64", "previous": "Int64", "poutcome": "boolean", "y": "boolean", } ) # Drop demographic data to improve model performace bank_mkt = bank_mkt.drop( columns=["age", "job", "marital", "education", "housing", "loan", "default"] ) return bank_mkt def split_dataset(data, preprocessor=None, test_size=0.3, random_state=42): """ Split dataset into train, test and validation sets using preprocessor. Because the random state of validation set is not specified, the validation set will be different each time when the function is called. Parameters ---------- data : DataFrame preprocessor : Pipeline random_state : int Returns ------- datasets : tuple Examples -------- from sklearn.preprocessing import OrdinalEncoder data = import_dataset("../data/BankMarketing.csv").interpolate(method="pad").loc[:, ["job", "education", "y"]] # To unpack all train, test, and validation sets X_train, y_train, X_test, y_test, X_ttrain, y_ttrain, X_validate, y_validate = split_dataset(data, OrdinalEncoder()) # To unpack train and test sets. X_train, y_train, X_test, y_test, *other_sets = split_dataset(data, OrdinalEncoder()) # To unpack test and validation set *other_sets, X_test, y_test, X_ttrain, y_ttrain, X_validate, y_validate = split_dataset(data, OrdinalEncoder()) # To unpack only train set. X_train, y_train, *other_sets = split_dataset(data, OneHotEncoder()) """ from sklearn.model_selection import StratifiedShuffleSplit train_test_split = StratifiedShuffleSplit( n_splits=1, test_size=test_size, random_state=random_state ) for train_index, test_index in train_test_split.split( data.drop("y", axis=1), data["y"] ): train_set = data.iloc[train_index] test_set = data.iloc[test_index] X_train = train_set.drop(["duration", "y"], axis=1) y_train = train_set["y"].astype("int").to_numpy() X_test = test_set.drop(["duration", "y"], axis=1) y_test = test_set["y"].astype("int").to_numpy() if preprocessor != None: X_train = preprocessor.fit_transform(X_train, y_train) X_test = preprocessor.transform(X_test) return (X_train, y_train, X_test, y_test) def transform( X, cut=None, gen=None, cyclic=None, target=None, fillna=True, to_float=False, ): """ Encode, transform, and generate categorical data in the dataframe. Parameters ---------- X : DataFrame gen : list, default = None cut : list, default = None external : list, default = None cyclic : list, default = None fillna : boolean, default = True to_float : boolean, default = False Returns ------- X : DataFrame Examples -------- bank_mkt = import_dataset("../data/BankMarketing.csv") X = dftransform(bank_mkt) """ X = X.copy() if cut != None: if "pdays" in cut: # Cut pdays into categories X["pdays"] = pd.cut( X["pdays"], [0, 3, 5, 10, 15, 30, 1000], labels=[3, 5, 10, 15, 30, 1000], include_lowest=True, ).astype("Int64") if cyclic != None: if "month" in cyclic: X["month_sin"] = np.sin(2 * np.pi * X["month"] / 12) X["month_cos"] = np.cos(2 * np.pi * X["month"] / 12) X = X.drop("month", axis=1) if "day_of_week" in cyclic: X["day_sin"] = np.sin(2 * np.pi * X["day_of_week"] / 5) X["day_cos"] = np.cos(2 * np.pi * X["day_of_week"] / 5) X = X.drop("day_of_week", axis=1) # Transform target encoded feature as str if target != None: X[target] = X[target].astype("str") # Other categorical features will be coded as its order in pandas categorical index X = X.apply( lambda x: x.cat.codes if pd.api.types.is_categorical_dtype(x) else (x.astype("Int64") if pd.api.types.is_bool_dtype(x) else x) ) if fillna: # Clients who have been contacted but do not have pdays record should be encoded as 999 # Clients who have not been contacted should be encoded as -999 X.loc[X["pdays"].isna() & X["poutcome"].notna(), "pdays"] = 999 X["pdays"] = X["pdays"].fillna(-999) # Fill other missing values as -1 X = X.fillna(-1) else: X = X.astype("float") if to_float: X = X.astype("float") return X def evaluate(X_train, y_train, X_test, y_test, clf=None): """ Evaluate classifier's performance on train, validation and test sets. Parameters ---------- clf : estimator, default = None """ from sklearn.metrics import ( average_precision_score, precision_score, recall_score, balanced_accuracy_score, roc_auc_score, ) X_sets = [X_train, X_test] y_sets = [y_train, y_test] metric_names = ["TNR", "TPR", "REC", "PRE", "bACC", "ROC", "AP"] set_names = ["Train", "Test"] metric_df = pd.DataFrame(index=metric_names, columns=set_names) for name, X, y in zip(set_names, X_sets, y_sets): y_pred = clf.predict(X) try: y_score = clf.decision_function(X) except AttributeError: y_score = clf.predict_proba(X)[:, 1] metrics = [ recall_score(y, y_pred, pos_label=0), recall_score(y, y_pred), recall_score(y, y_pred), precision_score(y, y_pred), balanced_accuracy_score(y, y_pred), roc_auc_score(y, y_score), average_precision_score(y, y_score), ] metric_df[name] = metrics return metric_df def search(X_train, y_train, X_test, y_test, clf, param_distributions, scoring): """ Tune classifier's parameters using randomized search. Parameters ---------- clf : estimator, default = None """ from sklearn.model_selection import RandomizedSearchCV from warnings import filterwarnings filterwarnings("ignore") search = RandomizedSearchCV( clf, param_distributions, scoring=scoring, cv=3, n_jobs=-1 ) fit = search.fit(X_train, y_train) print( f"best parameters found: {fit.best_params_},", f"with mean test score: {fit.best_score_}.", ) return evaluate(X_train, y_train, X_test, y_test, search)
26b5b5061db9a8d7724bf54b36e6db6afd492bb8
Mudit-Nahata/mypython
/string_split.py
291
3.6875
4
def string_split(): string="a=b;c=d;e=f;g=h" split1=string.split(";") split2=[] for i in split1: convertor1=str(i) convertor2=convertor1.split("=") convertor2=tuple(convertor2) split2.append(convertor2) return split2 print(string_split())
5191d61515cc9b1942cc8da25924c3195c5a4aee
amit/kachara
/consume_mem.py
252
3.671875
4
#!/usr/bin/env python import time consume=2 # Size of RAM in GB snooze=10 # How long to sleep in seconds print("Eating %s GB ..." % consume) str1="@"*1024*1024*1024*consume print("sleeping %s seconds ..." % snooze) time.sleep(snooze) print("All Done")
355a865bb3ad8a542086e94f7b3d769c74e97cf3
leige133/test_python
/test_program
1,413
3.953125
4
#!/usr/bin/env python #-*-coding:utf-8-*- #coding:utf-8 """ author by wanglei Created on April 21, 2016 """ print __name__ print __file__ print __doc__ """ def show(*args): #将参数以列表形式传入函数中 for item in args: print item if __name__ == '__main__': show('wl','zc',123,('w',5)) """ """ def show(**args): #将参数以字典形式传入函数中 for i in args.items(): print i if __name__ == '__main__': show(name='wl',age='zc',scort=123) dict={'k':1,'k1':2} show(**dict) #传字典变量时,变量前也得加** """ #生成器 xrange,xreadlines def foo(): yield 1 yield 2 yield 3 yield 4 re=foo() print re for i in re: print i """ def readlines():#xreadlines实现方式 seek = 0 while True: with open('D:\google.txt','r') as f: #with自动关闭文件 f.seek(seek) data = f.readline() print data if data: seek = f.tell() yield data else: return for i in readlines(): print i, """ result = 'gt' if 1 > 3 else 'lt' #三元运算 print result temp = lambda x,y:x**y #lambda函数(匿名函数) print temp(1,2) print [x*2 for x in range(10)] print map(lambda x:x**2,range(10)) for i,j in enumerate([1,2,3,4],1): #enumerate生成一个key,逗号后为从几开始 print i,j
99092ece360bac7c6e3bd924208d859ebe673639
achicha/py_samples
/codeforces/231A.py
765
3.859375
4
""" Input The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces. Output Print a single integer — the number of problems the friends will implement on the contest. """ counter = 0 for i in range(int(input())): s = eval('+'.join(input().split(' '))) if s > 1: counter += 1 print(counter) # print(sum(input().count('1')>1 for x in range(int(input()))))
790242a7074e61d0bd571b7c65f2251b37f4e6c1
namonai/UebungSS19
/Session5/cl_uebungss19_jr.py
795
3.515625
4
#!/usr/bin/python3 import matplotlib.pyplot as plt from numpy.random import rand import pandas # Funktion CreateData def createData(data_points, filename): if data_points < 5: data_points = data_points * 5 # als Erinnerung: rand(zeilen, spalten) x = rand(data_points, 2) df = pandas.DataFrame(data=x, columns=['x', 'y']) # print(df) df.to_csv(filename) print("Erzeugte Daten wurden in " + filename + " gespeichert.") # Funktion CreatePlot def createPlot(filename): df = pandas.read_csv(filename) # plot = plt.scatter(x=df['x'], y=df['y']) plot = df.plot(x=df.iloc[:,1], y=df.iloc[:,2], kind='scatter') # plot = df.plot(x=df['x'], y=df['y'], kind='scatter')) # Ausgabe führt zu einem Fehler: print(plot) createData(15, "scatterPlot.csv") createPlot("scatterPlot.csv")
eaf81fec64e2f2c7e4a1cc09b1f4a2d512fd71ff
yxu1998/miscellaneous-stuffs
/hw8_skel.py
13,532
4.09375
4
# hw8_skel.py # Matt Querdasi class Node(object): """ Represents a singly-linked node """ def __init__(self, value, next_node): self.value = value self.next = next_node class LinkedList(object): """ Represents a singly-linked list """ def __init__(self): self.head = None def is_empty(lst): """ lst: LinkedList returns: bool, True if lst is empty (has no nodes) and False otherwise """ return lst.head is None def insert_front(lst, val): """ lst: LinkedList val: int returns: nothing. lst is mutated such that a node with value val is the first node """ new_node = Node(val,None) new_node.next = lst.head lst.head = new_node def insert_after_node(node, val): """ node: Node val: int returns: nothing. Node is being mutated to link to a new node with value val """ new_node = Node(val, None) new_node.next = node.next node.next = new_node def insert_in_position(lst, val, pos): """ lst: LinkedList val: int pos: int, position in the list where new node should be inserted returns: nothing. lst is mutated such that a node with value val is added in position pos precondition: pos is a valid position (i.e. non-negative and <= than the list length) """ if pos == 0: insert_front(lst, val) i = 0 curr = lst.head while curr is not None and i < pos-1: i = i+1 curr = curr.next # according to the precondition curr should not be None, # but let's check just in case if curr is not None: insert_after_node(curr, val) def list_to_str(lst): """ lst: LinkedList returns: str, string representation of lst """ curr = lst.head s = ' ' while curr is not None: s = s + str(curr.value) + ' -> ' curr = curr.next s = s + 'None' return s """ Part I: practice problems (not graded). Solutions available on Moodle """ def insert_in_position_recur(lst, val, pos): """ same as insert_in_position but with no loop """ if pos == 0: insert_front(lst, val) elif pos == 1: insert_after_node(lst.head, val) else: short_list = LinkedList() short_list.head = lst.head.next insert_in_position_recur(short_list, val, pos-1) # UNCOMMENT FOLLOWING LINES TO TEST lst = LinkedList() insert_front(lst, 1) insert_front(lst, 8) insert_front(lst, 2) insert_front(lst, 3) insert_in_position_recur(lst, -5, 2) # 3 -> 2 -> -5 -> 8 -> 1 -> None print(list_to_str(lst)) insert_in_position_recur(lst, -10, 0) # -10 -> 3 -> 2 -> -5 -> 8 -> 1 -> None print(list_to_str(lst)) insert_in_position_recur(lst, -20, 6) # -10 -> 3 -> 2 -> -5 -> 8 -> 1 -> -20 -> None print(list_to_str(lst)) def int_to_list(num): """ num: int, non-negative integer returns: LinkedList, the digits of num """ res = LinkedList() while num > 0: insert_front(res, num%10) num = num // 10 return res # UNCOMMENT FOLLOWING LINES TO TEST print(list_to_str(int_to_list(147))) # 1 -> 4 -> 7 -> None print(list_to_str(int_to_list(4))) # 4 -> None print(list_to_str(int_to_list(9148))) # 9 -> 1 -> 4 -> 8 -> None print(list_to_str(int_to_list(0))) #. None def only_events(lst): """ lst: LinkedList returns: LinkedList, a list with only the elements in lst that are even IMPORTANT: you are not allowed to create new nodes, i.e. no calls to Node constructor are allowed (including via a helper function). Also, you are not allowed to change the value of any of the nodes. In other words, you are only allowed to change the 'next' attribute """ # new listed list res = LinkedList() last_even = None curr = lst.head while curr is not None: if curr.value % 2 == 0: if last_even is None: # this is the first even number that we see => make res.head # point to it res.head = curr else: # this is not the first even number that we see => make the last # even number we saw point to it last_even.next = curr last_even = curr curr = curr.next # make sure to end the list with the last even number last_even.next = None # return the linked list return res # UNCOMMENT FOLLOWING LINES TO TEST lst = LinkedList() insert_front(lst, 12) insert_front(lst, 11) insert_front(lst, 8) insert_front(lst, 4) insert_front(lst, 1) print(list_to_str(only_events (lst))) # 4 -> 8 -> 12 -> None lst = LinkedList() insert_front(lst, 12) insert_front(lst, 11) insert_front(lst, 8) insert_front(lst, 4) insert_front(lst, 2) print(list_to_str(only_events (lst))) # 2 -> 4 -> 8 -> 12 -> None lst = LinkedList() insert_front(lst, 9) insert_front(lst, 11) insert_front(lst, 8) insert_front(lst, 4) insert_front(lst, 2) print(list_to_str(only_events (lst))) # 2 -> 4 -> 8 -> None def concatenate(lst1, lst2): """ lst1: LinkedList lst2: LinkedList returns: LinkedList, list obtained by concatenating lst1 and lst2 IMPORTANT: you are not allowed to create new nodes, i.e. no calls to Node constructor are allowed (including via a helper function). Also, you are not allowed to change the value of any of the nodes. In other words, you are only allowed to change the 'next' attribute """ res = LinkedList() if is_empty(lst1) and is_empty(lst2): return res elif is_empty(lst1): res.head = lst2.head return res res.head = lst1.head curr = lst1.head while curr is not None: if curr.next is None: curr.next = lst2.head curr = None else: curr = curr.next return res # UNCOMMENT FOLLOWING LINES TO TEST lst1 = LinkedList() insert_front(lst1, 3) insert_front(lst1, 2) insert_front(lst1, 1) lst2 = LinkedList() insert_front(lst2, 10) insert_front(lst2, 20) print(list_to_str(concatenate(lst1, lst2))) # 1 -> 2 -> 3 -> 20 -> 10 -> None lst1 = LinkedList() insert_front(lst1, 3) insert_front(lst1, 2) insert_front(lst1, 1) lst2 = LinkedList() print(list_to_str(concatenate(lst1, lst2))) # 1 -> 2 -> 3 -> None lst1 = LinkedList() lst2 = LinkedList() insert_front(lst2, 3) insert_front(lst2, 2) insert_front(lst2, 1) print(list_to_str(concatenate(lst1, lst2))) # 1 -> 2 -> 3 -> None """ Part II: Graded problems (25 points each) """ def insert_in_place(lst, x): """ lst: LinkedList, a sorted list (increasing order) x: int returns: nothing. x is inserted to lst in the right place """ i = 0 curr = lst.head now = curr prev = curr if x < curr.value: insert_front(lst, x) else: while curr!= None: prev = now now = curr if curr.value < x: if curr.next == None: insert_after_node(curr, x) break curr = curr.next else: insert_after_node(prev, x) break # UNCOMMENT FOLLOWING LINES TO TEST lst = LinkedList() insert_front(lst, 8) insert_front(lst, 3) insert_front(lst, 2) insert_front(lst, 1) insert_in_place(lst, 5) print(list_to_str(lst)) # 1 -> 2 -> 3 -> 5 -> 8 -> None lst = LinkedList() insert_front(lst, 3) insert_front(lst, 2) insert_front(lst, 1) insert_in_place(lst, 5) print(list_to_str(lst)) # 1 -> 2 -> 3 -> 5 -> None lst = LinkedList() insert_front(lst, 3) insert_front(lst, 2) insert_front(lst, 1) insert_in_place(lst, 0) print(list_to_str(lst)) # 0 -> 1 -> 2 -> 3 -> None def interleave(lst1, lst2): """ lst1: LinkedList lst2: LinkedList returns: LinkedList, list obtained by interleaving lst1 and lst2 and tucking leftovers at the end. IMPORTANT: you are not allowed to create new nodes, i.e. no calls to Node constructor are allowed (including via a helper function). Also, you are not allowed to change the value of any of the nodes. In other words, you are only allowed to change the 'next' attribute """ curr1 = lst1.head curr2 = lst2.head next1 = lst1.head.next next2 = lst2.head.next lst = LinkedList() lst.head = lst1.head curr_lst = lst.head curr1 = curr1.next while curr1 != None or curr2 != None: #print(list_to_str(lst)) if curr2 != None: next2 = curr2.next curr_lst.next = curr2 curr2 = next2 curr_lst = curr_lst.next #print(list_to_str(lst)) if curr1 != None: next1 = curr1.next curr_lst.next = curr1 curr1 = next1 curr_lst = curr_lst.next return lst # UNCOMMENT FOLLOWING LINES TO TEST lst1 = LinkedList() insert_front(lst1, 3) insert_front(lst1, 2) insert_front(lst1, 1) lst2 = LinkedList() insert_front(lst2, 'c') insert_front(lst2, 'b') insert_front(lst2, 'a') print(list_to_str(interleave(lst1, lst2))) # 1 -> a -> 2 -> b -> 3 -> c -> None lst1 = LinkedList() insert_front(lst1, 5) insert_front(lst1, 4) insert_front(lst1, 3) insert_front(lst1, 2) insert_front(lst1, 1) lst2 = LinkedList() insert_front(lst2, 'c') insert_front(lst2, 'b') insert_front(lst2, 'a') print(list_to_str(interleave(lst1, lst2))) # 1 -> a -> 2 -> b -> 3 -> c -> 4 -> 5 -> None lst1 = LinkedList() insert_front(lst1, 3) insert_front(lst1, 2) insert_front(lst1, 1) lst2 = LinkedList() insert_front(lst2, 'e') insert_front(lst2, 'd') insert_front(lst2, 'c') insert_front(lst2, 'b') insert_front(lst2, 'a') print(list_to_str(interleave(lst1, lst2))) # 1 -> a -> 2 -> b -> 3 -> c -> d -> e -> None def deal(lst): """ lst: LinkedList returns: (LinkedList,LinkedList) two linked lists obtained by dealing the elements of lst into odd and even positions (see examples below) IMPORTANT: you are not allowed to create new nodes, i.e. no calls to Node constructor are allowed (including via a helper function). Also, you are not allowed to change the value of any of the nodes. In other words, you are only allowed to change the 'next' attribute """ lst1 = LinkedList() lst2 = LinkedList() if lst.head == None: return(lst1, lst2) if lst.head.next is None: return(lst, lst2) lst1.head = lst.head lst2.head = lst.head.next curr = lst.head while curr.next != None: temp = curr.next curr.next = curr.next.next curr = temp return(lst1,lst2) # UNCOMMENT FOLLOWING LINES TO TEST lst = LinkedList() insert_front(lst, 6) insert_front(lst, 5) insert_front(lst, 4) insert_front(lst, 3) insert_front(lst, 2) insert_front(lst, 1) lst1, lst2 = deal(lst) print(list_to_str(lst1)) # 1 -> 3 -> 5 -> None print(list_to_str(lst2)) # 2 -> 4 -> 6 -> None lst = LinkedList() insert_front(lst, 5) insert_front(lst, 4) insert_front(lst, 3) insert_front(lst, 2) insert_front(lst, 1) lst1, lst2 = deal(lst) print(list_to_str(lst1)) # 1 -> 3 -> 5 -> None print(list_to_str(lst2)) # 2 -> 4 -> None lst = LinkedList() insert_front(lst, 10) lst1, lst2 = deal(lst) print(list_to_str(lst1)) # 10 -> None print(list_to_str(lst2)) # None def swap(lst, i, j): """ lst: LinkedList i, j: int returns: nothing. swaps the elements in positions i and j precondition: i and j are valid indices and i < j IMPORTANT: you are not allowed to create new nodes, i.e. no calls to Node constructor are allowed (including via a helper function). Also, you are not allowed to change the value of any of the nodes. In other words, you are only allowed to change the 'next' attribute """ curr = lst.head x = 0 node1 = curr node1_prev = curr node1_post = curr node2 = curr node2_prev = curr node2_post = curr while curr != None: if x+1 == i: node1_prev = curr elif x == i: node1 = curr elif x == i+1: node1_post = curr if x+1 == j: node2_prev = curr elif x == j: node2 = curr elif x == j+1: node2_post = curr x += 1 curr = curr.next if i == 0 and j != x-1 and j-i != 1: lst.head = node2 node2.next = node1_post node2_prev.next = node1 node1.next = node2_post elif i == 0 and j == x-1: lst.head = node2 node2.next = node1_post node2_prev.next = node1 node1.next = None elif j-i == 1 and j == x-1: node1_prev.next = node2 node2.next = node1 node1.next = None elif j-i == 1 and i == 0: lst.head = node2 node2.next = node1 node1.next= node2_post else: node1_prev.next = node2 node2.next = node1_post node2_prev.next = node1 node1.next = node2_post # UNCOMMENT FOLLOWING LINES TO TEST lst = LinkedList() insert_front(lst, 6) insert_front(lst, 5) insert_front(lst, 4) insert_front(lst, 3) insert_front(lst, 2) insert_front(lst, 1) insert_front(lst, 0) swap(lst, 2, 4) print(list_to_str(lst)) # 0 -> 1 -> 4 -> 3 -> 2 -> 5 -> 6 -> None swap(lst, 0, 3) print(list_to_str(lst)) # 3 -> 1 -> 4 -> 0 -> 2 -> 5 -> 6 -> None swap(lst, 0, 6) print(list_to_str(lst)) # 6 -> 1 -> 4 -> 0 -> 2 -> 5 -> 3 -> None swap(lst, 5, 6) print(list_to_str(lst)) # 6 -> 1 -> 4 -> 0 -> 2 -> 3 -> 5 -> None swap(lst, 0, 1) print(list_to_str(lst)) # 1 -> 6 -> 4 -> 0 -> 2 -> 3 -> 5 -> None
acfd6191021f32549e0c8cca3989101b816b1f17
yxu1998/miscellaneous-stuffs
/lab5_skel.py
7,258
4.375
4
# lab_skel.py # October 3, 2018 """ Part I: warm up exercises. Complete the functions below """ def sum_list(xs): """ xs: list, a list of integers returns: int, sum of all elements in xs precondition: none (if list is empty, 0 should be returned) """ pass acc=0 for char in xs: acc=char+abc return acc print(" ----- TEST sum_list ----- ") print(sum_list([1,12,3,10])) print(sum_list([4])) print(sum_list([])) def mul_list(xs): """ xs: list, a list of integers returns: int, multiple of all elements in xs precondition: none (if list is empty, 1 should be returned) """ pass acc=1 for char in xs: acc=char*abc return acc print(" ----- TEST mul_list ----- ") print(mul_list([1,5,2,10])) print(mul_list([4])) print(mul_list([])) def largest(xs): """ xs: list, a list of integers returns: int, largest element in xs precondition: list is not empty """ pass lar=xs[0] for char in xs: if lar>char: lar=lar else: lar=char return lar print(" ----- TEST largest ----- ") print(largest([1,5,2,10])) print(largest([4])) print(largest([60,1,-2,9,4])) """ Part II: working with lists """ """ 1. write a function that counts the number of palindromes in a list of strings. You can use the function is_palindrome provided below. Examples: >>> count_palindromes(['aba', 'abca', 'abccba']) 2 >>> count_palindromes(['abcdef']) 0 >>> count_palindromes([]) 0 >>> count_palindromes(['']) 1 """ def is_palindrome(s): """ s: str returns: True if s is a palindrome and False otherwise precondition: none """ reverse_s = '' for ch in s: # concatenate ch from the left reverse_s = ch + reverse_s return reverse_s==s def count_palindromes(xs): """ xs: list, list of strings returns: number of strings in xs that are a palindrome precondition: none """ count=0 for char in xs: if is_palindrome(char)==True: count+=1 else: count=count return count pass # remove pass after implementing """ 2. write a function is_common_member that takes two lists and returns True if they have at least one common member. Examples: >>> is_common_member([1,2,3],[4,5,6]) False >>> is_common_member([1,2,3],[4,5,3,6]) True >>> is_common_member([1,2,3],[]) False """ def is_common_member(xs, ys): """ xs: list, a list of integers ys: list, a list of integers returns: True if there is at least one number x that is in both xs and ys precondition: none """ for char in xs: if char in ys: return True return False # YOUR CODE HERE pass # remove pass after implementing print(" ----- TEST is_common_member -----") print(is_common_member([1,2,3],[4,5,3,6])) """ 3. write a function elim_reps that takes a list xs and returns a new list containing the elements of xs without repetitions (in any order). Note: xs should NOT be mutated. Examples: >>> elim_reps([1,2,3,1,2,3,4]) [1,2,3,4] >>> elim_reps([1,2,3,4]) [1,2,3,4] >>> elim_reps([]) [] """ def elim_reps(xs): """ xs: list returns: list, a list containing the elements of xs without repetitions. xs is not mutated. precondition: none """ acc=[] for char in xs: if char in acc: acc=acc else: acc.append(char) return acc pass # remove pass after implementing print(" ----- TEST elim_reps -----") """ 4. write a function factors that takes a positive number n and return a list of the factors of n, i.e. a list of numbers a such that a divides n without remainder. Examples: >>> factors(8) [1, 2, 4, 8] >>> factors(17) [1, 17] >>> factors(1) [1] """ def factors(n): """ n: int, a positive integer returns: list, a list with factors of n precondition: none """ acc=[] a=1 while a<=n: if n%a==0: acc.append(a) a+=1 else: a+=1 return acc pass # remove pass after implementing print(" ----- TEST factors -----") print(factors(8)) """ 5. write a function fibonacci that takes a positive integer n and returns a list with the first n terms of Fibonacci series. The first two Fibonacci numbers are F_1=1, F_2=1, and for n>2, F_n is given by the sum of the two preceding numbers: F_n = F_{n-1} + F_{n-2} Examples: >>> fibonacci(5) [1, 1, 2, 3, 5] >>> fibonacci(12) [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ] >>> fibonacci(1) [1] >>> fibonacci(2) [1, 1] """ def fibonacci(a): """ n: int, a positive integer returns: list, a list with the first n terms of Fibonacci series precondition: n is positive """ acc=[1,1] n=2 if a<2: return [1] else: while n<a: acc.append(acc[n-2]+acc[n-1]) n+=1 return acc pass # remove pass after implementing print(" ----- TEST fibonacci -----") print(fibonacci(2)) """ 6. write a function prefixes that takes a string and returns a list of all prefixes of s. Examples: >>> prefixes('funny') ['', 'f', 'fu', 'fun', 'funn', 'funny'] """ def prefixes(s): """ s: str returns: list, a list of all prefixes of s precondition: none """ acc1="" acc2=[""] for char in s: acc1=acc1+char acc2.append(acc1) return acc2 pass # remove pass after implementing print(" ----- TEST prefixes -----") """ 7. write a function longest_upsequence that takes a list xs and returns the length of the longest subsequence of xs that is strictly increasing (i.e. each member is less than the next). Examples: >>> longest_upsequence([1,2,0,1,2,-1]) 3 >>> longest_upsequence([1,2,0,-1,5,2,3]) 2 >>> longest_upsequence([8,7,6,5,4,3]) 1 >>> longest_upsequence([1,2,0,1,2,3,4]) 5 """ def longest_upsequence(xs): """ xs: list, a list of integers returns: the length of the longest subsequence of xs that is strictly increasing precondition: xs is not empty """ count=1 lar=1 acc=[] n1=0 n2=0 while n<len(xs): while xs(n)<xs(n+1): count+=1 n2+=1 if count>lar: lar=count else: lar=lar n1+=1 return lar pass # remove pass after implementing print(" ----- TEST longest_upsequence -----") # TESTS HERE print(longest_upsequence([1,2,0,-1,5,2,3])) """ 8. (harder question, involves nested loops): write a function list_binary that takes a positive integer n and returns a list of all binary strings of length n Examples: >>> list_binary(2) ['00', '01', '10', '11'] >>> list_binary(3) ['000', '001', '010', '011', '100', '101', '110', '111'] """ def list_binary(n): """ n: int, a positive integer returns: list, a list of all binary strings of length n precondition: n is positive """ # YOUR CODE HERE pass # remove pass after implementing print(" ----- TEST list_binary -----") # TESTS HERE
dad97fd210d3b6491734b7adc3f42f8925b640a5
byteridge/ML-Byteridge
/Santhan/ASSIGNEMENT 1/stringnmultiplychars.py
394
3.84375
4
def stringMultiply(str): res = '' # increment by 2 over iterations for i in range(0, len(str), 2): # casting every second charcter num = int(str[i+1]) # adding up char n times to result for j in range(num): res += str[i] return sorted(res) # test 1 print(stringMultiply("c4b3g6h1")) # test 2 print(stringMultiply("f4g5c2n6o2"))
36d2a4aa96460215721c2d346f034f2a7c6b46d1
marissa-graham/cs673
/corpus.py
10,118
3.515625
4
#!python3 import string import numpy as np from scipy import sparse import os import phonetic from phonetic import Word class WordCorpus: """ Calculate the transition probabilities for a given corpus of text and use the distribution to generate options for new text. Attributes: dictionary : PhoneticDictionary to use for lookup corpString : Source text in string format size : Number of unique words in the corpus frequency : Number of times each word occurs unique_precedent_counts : # of unique words each word follows unique_antecedent_counts : # of unique follow words for each word wordSeq : Indices for each word in the corpus text wordList : List of unique Word objects in the corpus wordDict : Dictionary with wordDict[Word.stringRepr] = index of Word That is, we look up the index based on the text of an actual Word, so we can extend the corpus without duplicating Word objects sylDict : Dictionary with sylDict[syl] = a list of tuples that represent the (word, syl_index) coordinates of where the syllable appears in the corpus A : Transition matrix used to sample the probability distribution """ def __init__(self, dictionary): """ Initialize an empty corpus. """ self.dictionary = dictionary self.corpString = None self.size = 0 self.frequency = None self.unique_precedent_counts = None self.unique_antecedent_counts = None self.wordSeq = [] self.wordList = [] self.wordDict = dict() self.sylDict = dict() self.unknowns = "" self.unknowns_indices = [] def _initializeCorpus(self, verbose=False): """ Initialize wordSeq, wordList, and wordDict for a corpus given a normal string of punctuation and space separated text. """ # Split the corpus string into words wordstrings = self.corpString.split() # Define the characters we want to strip away nonos = string.punctuation + '0123456789' # Go through all the words for i in range(len(wordstrings)): # Get punctuation free word text word = wordstrings[i].strip(nonos).lower() # Ignore an empty stripped word if len(word) == 0: pass # Add the normal words to the wordDict and wordSeq else: # If the word is already in the corpus, only update wordSeq if word in self.wordDict: self.wordSeq.append(self.wordDict[word]) # Otherwise, create the word and update accordingly else: # Look the word up in the dictionary new_word = self.dictionary.lookup(word, verbose=verbose) # If the word isn't in the phonetic dictionary if new_word == None: # Add to file of unknown words with open(self.unknowns, "a") as unknowns: unknowns.write(word + "\n") self.unknowns_indices.append(self.size) self.wordSeq.append(self.size) self.wordDict[word] = self.size self.wordList.append(new_word) self.size += 1 if len(self.unknowns_indices) > 0: print("unknowns filename:", self.unknowns) print("Need to add", len(self.unknowns_indices), "words to template word list using LOGIOS tool") self.wordSeq = np.array(self.wordSeq) print("Corpus text:", len(wordstrings), "words,", self.size, "unique") def add_unknowns(self, logios_file, verbose=False): """ Function to add the unknown words after using the LOGIOS tool, either manually or via API. You just have to go through and fix wordList, since it has null values at the indices at the end of the line. wordDict and wordList are fine. It should be pretty easy, just replace the value at that index. The wordList isn't used until generate_sample, so it can just throw a warning at the end of the normal initialization steps. """ new_words = [] with open(logios_file, "r") as logios_output: for line in logios_output: items = line.split() word_string = items[0] phonemes = items[1:] for i in range(len(phonemes)): if phonetic.is_vowel(phonemes[i]): phonemes[i] += "0" # default stress to 0 new_words.append(Word(word_string.lower(), phonemes)) if verbose: print("Add", new_words[-1]) for i in range(len(self.unknowns_indices)): self.wordList[self.unknowns_indices[i]] = new_words[i] def _initializeMatrix(self): """ Initialize the transition matrix as a scipy.sparse.csr_matrix. We use the convention that A[i,j] is the probability of word i being followed by word j. """ # Initialize total number of each word pair transition n = self.wordSeq.size A_raw = sparse.coo_matrix( (np.ones(n-1), (self.wordSeq[:-1], self.wordSeq[1:])), shape=(self.size, self.size)).tocsr().toarray() # Keep track of followability stuff self.frequency = A_raw.sum(axis=1).flatten() self.unique_precedent_counts = np.count_nonzero(A_raw, axis=0) self.unique_antecedent_counts = np.count_nonzero(A_raw, axis=1) # Normalize A by row and column to get probabilities row_data = np.maximum(self.frequency, np.ones(self.size)) row_d = sparse.spdiags(1.0/row_data, 0, self.size, self.size) self.A_forward = row_d * A_raw col_data = np.maximum(A_raw.sum(axis=0).flatten(), np.ones(self.size)) col_d = sparse.spdiags(1.0/col_data, 0, self.size, self.size) self.A_backward = (col_d * A_raw.T).T def initialize(self, text, is_filename=True, keeplines=False): """ Read in the corpus and calculate the transition matrix. Arguments: text : String containing either a filename or the actual text is_filename : Bool telling us whether text is a filename keeplines : Bool telling us whether to keep line structure at the cost of sometimes splitting words apart, or to keep words together at the cost of losing line structure """ # Assign the text to self.corpString if is_filename: with open(text) as filename: self.corpString = filename.read() self.unknowns = text.replace(".txt","")+"_unknowns.txt" else: self.corpString = text self.unknowns = "corpus_unknowns.txt" # Remove unknowns file if it already exists if os.path.exists(self.unknowns): os.remove(self.unknowns) #self.corpString = self.corpString.replace("\'","") # Remove newline characters if keeplines == False: # Hyphens followed by a newline should be ignored self.corpString = self.corpString.replace('-\n', '') self.corpString = self.corpString.replace('\n', ' ') # Remove hyphens so hyphenated words can be treated as two words self.corpString = self.corpString.replace('-', ' ') self._initializeCorpus() def initializeMatrix(self): self._initializeMatrix() def initializeSylDict(self): # Can only be called after unknown words have been added # print(self.wordDict) for word in self.wordList: vowel_pos = 0 for i in range(len(word.phonemes)): syl = word.phonemes[i] if syl[-1].isdigit(): # only care about vowels key = syl[:-1] # strip stress indicator val = (self.wordDict[word.stringRepr], vowel_pos) if key not in self.sylDict.keys(): self.sylDict[key] = [val] else: self.sylDict[key].append(val) vowel_pos += 1 def sample_distribution(self, current, n, forward, verbose): """ Sample the probability distribution for word 'current' n times. """ if verbose: if forward: print("\n\tGet forwards choices for '"+self.wordList[current].stringRepr+"'") else: print("\n\tGet backwards choices for '"+self.wordList[current].stringRepr+"'") # Try to grab some samples try: # If we are sampling forward, we sample from the row if forward: samples = np.random.choice(self.size, size=n, p=self.A_forward[current,:]) # If we are going backwards, we sample from the column else: samples = np.random.choice(self.size, size=n, p=self.A_backward[:,current]) # If it doesn't work, there are no options, so just pick random words. except ValueError: if verbose: print("\t\tHave to just choose random words\n\t\t", "unique_antecedent_counts =", self.unique_antecedent_counts[current]) samples = np.random.randint(self.size, size=n) return np.unique(samples) def followability(self, word_index, forward): """ Get the followability score for the given index. """ if forward: num_options = self.unique_antecedent_counts[word_index] else: num_options = self.unique_precedent_counts[word_index] return num_options/(1.0 + self.frequency[word_index])
d6a2e7781f1d97b296f15990abefb720fdb04258
lihip94/countingPolyominos
/gui.py
470
3.734375
4
from tkinter import * from counting_polyominos import counting_poly root = Tk() e = Entry(root, width=50) e.pack() def click(): num = e.get() fixed_num = counting_poly({(0, 0)}, set(), [], int(num)) - counting_poly({(0, 0)}, set(), [], int(num)-1) label1 = Label(root, text="fixed("+str(num)+") = " + str(fixed_num)) label1.pack() myButton = Button(root, text="calculate fixed polyominos", padx=50, command=click) myButton.pack() root.mainloop()
b1cb1ad578bb76f3dd42bb64f8b72811b411658b
aybidi/Algorithmic-Sprint
/Element of Programming Interview in Python/Strings/look_and_say.py
562
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 9 19:21:00 2019 @author: abdullah """ def look_and_say(n): ''' time complexity ~ O(n x 2^n) ''' def next_number(s): result, i = [], 0 while i < len(s): count = 1 while i + 1 < len(s) and s[i] == s[i + 1]: i += 1 count += 1 result.append(str(count) + s[i]) i += 1 return "".join(result) s = "1" for _ in range(n): s = next_number(s) return s
eb9612315e24e7c5dcac2c0208c99fd5dec6a891
aybidi/Algorithmic-Sprint
/Element of Programming Interview in Python/InterviewQs.py
4,080
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 22 14:22:13 2019 @author: macbook """ def add_pair(values, target): val_comp = {} for value in range(len(values)): val_comp[values[value]] = value for value in values: diff = target - value if diff in val_comp: return values.index(value), val_comp[diff] return False def vertex_dist(points, vertex, k): points_distance = [] for point in points: dist = 0 for i in range(2): dist += (point[i] - vertex[i])**2 points_distance.append(dist) def dutch_flag(A,k): pivot = A[k] smaller = equal = 0 larger = len(A) while equal < larger: if A[equal] < pivot: A[equal], A[smaller] = A[smaller], A[equal] smaller, equal = smaller + 1, equal + 1 elif A[equal] == pivot: equal += 1 else: #A[equal] > pivot larger -= 1 A[larger], A[equal] = A[equal], A[larger] return A def increment_integer(A): for i in reversed(range(len(A))): if A[i] < 9: A[i] += 1 return A elif A[i] == 9: A[i] = 0 if i == 0: return [1] + A[:] def multiply_two_integers(A,B): sign = -1 if A[0] ^ B[0] else 1 A[0], B[0] = abs(A[0]), abs(B[0]) ans = [0] * (len(A) + len(B)) for i in reversed(range(len(B))): for j in reversed(range(len(A))): res = B[i] * A[j] ans[i + j + 1] += res ans[i + j] += ans[i+j+1]//10 ans[i + j + 1] %= 10 start = 0 while ans[start] == 0: start += 1 ans[start] *= sign return ans[start:] def advance_through_array(A): _max = 0 for i in range(len(A)): if i + A[i] > _max: if i <= _max: _max = i + A[i] if _max >= len(A) - 1: return True return False def delete_duplicates(A): if not A: return 0 write_index = 1 for i in range(1,len(A)): if A[write_index - 1] != A[i]: A[write_index] = A[i] write_index += 1 return A def sell_stock_once(A): min_price_so_far, max_profit = float('inf'), 0.0 for price in A: max_profit_sell_today = price - min_price_so_far max_profit = max(max_profit, max_profit_sell_today) min_price_so_far = min(min_price_so_far, price) return max_profit def rearrange(A): for i in range(len(A)): A[i:i+2] = sorted(A[i:i+2], reverse=i%2) def enumerate_primes(n): ans = list(range(2,n+1)) for i in range(len(ans)): if ans[i] > 0: for j in range(i+1,len(ans)): if ans[j] % ans[i] == 0: ans[j] = 0 else: pass return ans def permutation(A, perm): """ time complexity = O(n) space complexity = O(1) """ for i in range(len(A)): next = i #resolve each cycle within the while loop while perm[next] >= 0: A[i], A[perm[next]] = A[perm[next]], A[i] #swap the current element with the target element temp = perm[next] #store the current permutation index perm[next] -= len(perm) #mark it so that you know when the cycle ends next = temp #now go to the permutation index you stored. Essentially you are resolving the cycle in order perm[:] = [a + len(perm) for a in perm] #restore the permutation list return A #print(permutation(['a','b','c','d'],[0,2,3,1])) #print(enumerate_primes(18)) #print(sell_stock_once([310,315,275,295,260,270,290,230,255,250])) #print(delete_duplicates([2,3,5,5,7,11,11,11,13])) #print(advance_through_array([0,2,2,2,2,0,1])) #print(multiply_two_integers([1,9,3,7,0,7,7,2,1],[-7,6,1,8,3,8,2,5,7,2,8,7])) #print(increment_integer([9,9,9])) #print(dutch_flag([0,1,9,3,2,5,1,7,7,2,6,1,2,3,5,5], 5)) #print(vertex_dist([[0,0],[1,9],[2,4],[4,1],[2,2],[2,1]],[2,2],2)) #print(add_pair([14, 13, 6, 7, 8, 10, 1, 2], 3))
edc5beae0fbf7f7406b535dbda33c843bd95e761
aybidi/Algorithmic-Sprint
/Element of Programming Interview in Python/Recursion/generate_btrees.py
939
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 6 20:18:28 2019 @author: abdullah """ class BinaryTreeNode: def __init__(self, value, left, right): self.value = value self.left = left self.right = right def generate_binary_trees(num_nodes): """ input: number of nodes in a binary tree output: all possible binary trees with the input number of nodes """ if num_nodes == 0: return [None] result = [] for num_left_subtree_nodes in range(num_nodes): num_right_subtree_nodes = num_nodes - 1 - num_left_subtree_nodes left_subtree = generate_binary_trees(num_left_subtree_nodes) right_subtree = generate_binary_trees(num_right_subtree_nodes) result += [ BinaryTreeNode(0,left,right) for left in left_subtree for right in right_subtree] return result
e76998550d5a5ff9d2f2eee8f7440b5689d1d066
aybidi/Algorithmic-Sprint
/Element of Programming Interview in Python/Recursion/generate_power_set.py
789
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 6 20:06:57 2019 @author: abdullah """ def generate_power_set(input_set): """ input: a set output: power set of the input set (all subsets of the input set) time complexity ~ O(n x 2^n) space complexity ~ O(n x 2^n) """ def directed_power_set(to_be_selected, selected_so_far): if to_be_selected == len(input_set): power_set.append(list(selected_so_far)) # print(selected_so_far) return directed_power_set(to_be_selected + 1, selected_so_far) directed_power_set(to_be_selected + 1, selected_so_far + [input_set[to_be_selected]]) power_set = [] directed_power_set(0,[]) return power_set
0970f57aa338249ee6466c1dadadeee769acf7c6
MurphyStudebaker/intro-to-python
/1-Basics.py
2,086
4.34375
4
""" PYTHON BASICS PRACTICE Author: Murphy Studebaker Week of 09/02/2019 --- Non-Code Content --- WRITING & RUNNING PROGRAMS Python programs are simply text files The .py extension tells the computer to interperet it as Python code Programs are run from the terminal, which is a low level interaction with the computer You must be in the directory of your program in order to run the file correctly Switch directories by typing: cd <PATH/TO/YOUR/FILE> (path can be found by right clicking your file and copying the full path) Once in the right directory, type python (or python3 for Macs) and then the name of your file EXAMPLE: python MyProgram.py NAMING CONVENTIONS Variable names should be lower_case, cannot contain any python keywords, and must be descriptive of what the variable represents OPERATORS + Addition - Subtraction * Multiplication / Division // Rounded Division ** Exponent (ex 2**2 is 2 to the power of 2) % Modulo aka Integer Remainder < Less than == Equal to > Greater than <= less than or equal to >= greater than or equal to != not equal to = assignment (setting a value to a variable) TYPES int Integer 8, 0, -1700 float Decimal 8.0, .05, -42.5 str String "A character", "30", "@#$!!adgHHJ" bool Boolean True, False """ """ NOW FOR THE CODE """ # GETTING INPUT AND OUTPUTTING TO CONSOLE # input is always a string # saving what the user types in to the variable "name" name = input("Enter your name: ") print("Hello, " + name) """ MODULES Modules are libraries of code written by other developers that make performing certain functions easier. Commonly used modules are the math module (has constants for pi and e and sqrt() functions) and the random module (randomly generate numbers) """ import random user_id = random.randint(100, 1000) print("Hello, " + name + "! Your ID is " + str(user_id)) # MATHEMATICAL OPERATIONS import math radius = float(input("Radius: ")) circ = 2 * math.pi * radius print("The circumference is " + str(circ))
d1324a79ae30418d5722f22782283d05cd738c23
IfDougelseSa/cursoPython
/exercicios_secao5/22.py
370
3.921875
4
# aposentadoria idade = int(input("Digite sua idade : ")) tempo_servico = int(input("Digite o tempo de serviço: ")) if idade > 65: print(f'Você já pode aposentar!!') elif tempo_servico > 30: print(f'Você já pode aposentar!!') elif tempo_servico > 25 and idade > 60: print(f'Você já pode aposentar!!') else: print(f'Você não pode aposentar!!')
a663237f9a4f7c5099c4e65201bbd4e7a4fefe8a
IfDougelseSa/cursoPython
/exercicios_secao6/5.py
143
3.96875
4
# Soma de dez valores soma = 0 for values in range(11): num = int(input("Digite o numero: ")) soma = soma + num print(f'{soma}')
9a3ccf577884d3afbade517373e20d4540420a6f
IfDougelseSa/cursoPython
/exercicios_secao6/10.py
164
3.671875
4
#soma dos 50 primeiros numeros pares par = 0 soma = 0 for values in range(50): par = par + 2 print(par) soma = soma + par print(soma) print(soma)
226d02ec4ae29ebeb6a19115101a65750e43ae04
IfDougelseSa/cursoPython
/exercicios_secao5/20.py
485
4.03125
4
# determinando um triângulo a = int(input("Digite o valor do lado a: ")) b = int(input("Digite o valor do lado b: ")) c = int(input("Digite o valor do lado c: ")) if (a + b) > c and (a + c) > b and (b + c) > a: if a == b and a == c: print(f'Triângulo equilátero') elif a == b or a == c or b == c: print(f'Triângulo isósceles') else: print(f'Triângulo escaleno') else: print(f'Não é possível formar um triângulo com essas medidas!')
4e529878318541826bf0323176a9b35dda63f56d
IfDougelseSa/cursoPython
/exercicios_seccao4/6.py
205
4
4
# Conversor de temperatura celsius para fahrenheit celsius = float(input("Digite a temperatura em Celsius: ")) fahrenheit = celsius * (9 / 5) + 32 print(f'A temperatura em fahrenheit é {fahrenheit}')
3d876bd8dd7e98da0b2227478dce4fb5c77fc0a2
IfDougelseSa/cursoPython
/deque.py
477
3.953125
4
""" Módulo Collections - Deque Podemos dizer que o deck é uma lista de alta perfomamce. # Import from collections import deque # Criandp deques deq = deque('geek') print(deq) #Adicionando elementos no deque deq.append('y') # print(deq) deq.appendleft('k') print(deq) # Adiciona no comeco da lista. # Remover elementos print(deq.pop()) # Remove e retorna o último elemento print(deq) print(deq.popleft()) # Remove e retorna o primeiro elemento. print(deq) """
6bf090c2ef148b96404539238a5425a055c57f6a
IfDougelseSa/cursoPython
/exercicios_seccao4/53.py
319
3.671875
4
# Custo para cercar o terreno c = float(input("Digite o comprimento do terreno: ")) l = float(input("Digite a largura do terreno: ")) preco_metro = float(input("Digite o preço da tela: ")) diametro = c + l custo_total = diametro * preco_metro print(f'O custo total para cercar seu terreno é {custo_total} reais.')
874769f6eddcea51823c926e4b520e6cc0bbcf89
IfDougelseSa/cursoPython
/exercicios_seccao4/46.py
266
4.125
4
# Digitos invertidos num = int(input('Digite o numero com 3 digitos: ')) primeiro_numero = num % 10 resto = num // 10 segundo_numero = resto % 10 resto = resto //10 terceiro_numero = resto % 10 print(f'{primeiro_numero}{segundo_numero}{terceiro_numero}')
7ea222e7fee925a91e1e9cd3781545759e1f44c6
IfDougelseSa/cursoPython
/exercicios_seccao4/47.py
307
4.1875
4
# Numero por linha x = int(input("Digite o numero: ")) quarto_numero = x % 10 resto = x // 10 terceiro_numero = resto % 10 resto = resto // 10 segundo_numero = resto % 10 resto = resto // 10 primeiro_numero = resto % 10 print(f'{primeiro_numero}\n{segundo_numero}\n{terceiro_numero}\n{quarto_numero}')
7097f9cf932ac4aa674dcbf40c2e13f24c1d103e
IfDougelseSa/cursoPython
/exercicios_secao5/8.py
276
4.03125
4
# média com notas válidas nota1 = float(input("Digite a nota 1: ")) nota2 = float(input("Digite a nota 2: ")) if (0 <= nota1 <= 10) and (0 <= nota2 <= 10): media = (nota1 + nota2) / 2 print(f'A sua média é {media}.') else: print(f'Valor da nota inválido.')
badce90cf518f3c4be864c8f37f93f25c01a9283
IfDougelseSa/cursoPython
/test.py
491
3.890625
4
for letras in "Persistência é um dom!": if letras == 'a': print(f'Mais uma vogal: {letras}\n') elif letras == 'e': print(f'Mais uma vogal: {letras}\n') elif letras == 'i': print(f'Mais uma vogal: {letras}\n') elif letras == 'o': print(f'Mais uma vogal: {letras}\n') elif letras == 'u': print(f'Mais uma vogal: {letras}\n') elif letras == 'ê': print(f'Mais uma vogal: e\n') else: print(f'{letras}\n')
248feea895eb5a8e78b5a7de999ef50bdb1bfd4d
IfDougelseSa/cursoPython
/exercicios_secao5/23.py
225
3.78125
4
# ano bissexto ano = int(input("Digite o ano: ")) if (ano % 400) == 0: print(f'Ano bissexto.') elif (ano % 4 == 0) and (ano % 100) != 0: print(f'Ano bissexto.') else: print(f'O ano digitado não é bissexto.')
a958de7cc8511d475f0f2731ff8cf669b09df96c
IfDougelseSa/cursoPython
/exercicios_seccao4/1.py
56
3.5625
4
x = int(input('Digite um numero inteiro: ')) print(x)
a1985b72d397408ac12f513d65be334965d34b6a
IfDougelseSa/cursoPython
/exercicios_seccao4/51.py
156
4.0625
4
# coordernadas import math x = float(input("Digite o valor de x: ")) y = float(input("Digite o valor de y: ")) r = math.sqrt(x ** 2 + y ** 2) print(r)
044cb61a7d188d6661848b84e286f393d5d91b82
andyhuzhill/ProjectEuler
/problem7.py
529
3.59375
4
#!/usr/bin/env python # *-* encoding: utf-8 *-* # # ============================================= # author: Andy Scout # homepage: http://andyhuzhill.github.com # # description: # # ============================================= prime = [] prime.append(2) n = 1 p = 3 while n < 10001: for i in prime: if p % i == 0: p += 1 break elif i == prime[-1]: prime.append(p) p += 1 n += 1 break for i in prime: print i
b59405cb66a726ee2bc19b86fadd0ac85f996c25
Joana84/Python-learning
/list_comprehentions.py
550
3.5625
4
l = [1, 2, 3, 4, 5] even = [x for x in l if x % 2 == 0] print(even) g = lambda x: x**2 print(g(4)) print(dir(l)) class Person(): def __init__(self, name, surname): self.name = name self.surname = surname def __str__(self): return self.name + " " + self.surname def get_name(self): return self.name asia = Person('Joanna', 'Koziol') print(asia) print(asia.get_name()) print('jshdjsdhjfdshjsfhdhdfhrefhjfdjh\nfdhjfdhjfdhjfdfhjfdhjfdhjdfshjfdshjfdshjfds\nhjdfhdfhjfdhjfdhjdfhjdfhjfdhjfdhjfdhjhjdhjdfhjd')
105a662f929dabe1f536a58b4d233f89ca2cdbe1
sudoabhinav/competitive
/codechef/practice problems/cutting-recipe.py
393
3.546875
4
# https://www.codechef.com/problems/RECIPE def find_gcd(x, y): while(y): x, y = y, x % y return x n = int(raw_input().strip()) for i in xrange(n): li = map(int, raw_input().strip().split()) li = li[1:] result = li[0] for i in xrange(len(li)): result = find_gcd(li[i], result) for i in xrange(len(li)): print li[i] / result, print ""
f721cd2800a98b3e5eec010e698bb4e07f0d8de2
sudoabhinav/competitive
/hackerrank/week-of-code-36/acid-naming.py
544
4.15625
4
# https://www.hackerrank.com/contests/w36/challenges/acid-naming def acidNaming(acid_name): first_char = acid_name[:5] last_char = acid_name[(len(acid_name) - 2):] if first_char == "hydro" and last_char == "ic": return "non-metal acid" elif last_char == "ic": return "polyatomic acid" else: return "not an acid" if __name__ == "__main__": n = int(raw_input().strip()) for a0 in xrange(n): acid_name = raw_input().strip() result = acidNaming(acid_name) print result
c08fe37650a23b1cb70f936b919184f7a01e08d7
sudoabhinav/competitive
/codechef/journey begins/frequent-winner.py
388
3.734375
4
# https://www.codechef.com/JOBE2018/problems/FRW from collections import defaultdict a = int(raw_input().strip()) n = raw_input().strip().split() dict_names = defaultdict() for item in set(n): dict_names.setdefault(item, n.count(item)) max_val = max(dict_names.values()) names = [key for key, value in dict_names.items() if value == max_val] names.sort(reverse=True) print names[0]
0790f3bdde034ed1cc7aba38292bf3fba6409465
sudoabhinav/competitive
/hackerrank/algorithms/warmup/compare-the-triplets.py
443
3.59375
4
#https://www.hackerrank.com/challenges/compare-the-triplets a0, a1, a2 = raw_input().strip().split(' ') a0, a1, a2 = [int(a0), int(a1), int(a2)] b0, b1, b2 = raw_input().strip().split(' ') b0, b1, b2 = [int(b0), int(b1), int(b2)] count = 0 count1 = 0 if a0 > b0: count += 1 elif a0 < b0: count1 += 1 if a1 > b1: count += 1 elif a1 < b1: count1 += 1 if a2 > b2: count += 1 elif a2 < b2: count1 += 1 print count, count1
a3c3790812f74749f601c0075b115fbe2a296ca1
sudoabhinav/competitive
/hackerrank/algorithms/strings/pangrams.py
232
4.125
4
# https://www.hackerrank.com/challenges/pangrams from string import ascii_lowercase s = raw_input().strip().lower() if len([item for item in ascii_lowercase if item in s]) == 26: print "pangram" else: print "not pangram"
5c47bc674218773c7c083f96532f64efc2f49c03
iliyahoo/perfecto
/3/parser.py
961
3.546875
4
#!/usr/bin/env python from BeautifulSoup import BeautifulSoup import urllib2 import json import sys from json2html import * def url_parse(url): # sys.setdefaultencoding() does not exist, here! reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') # grab the page url = urllib2.urlopen(url) content = url.read() soup = BeautifulSoup(content) # convert to dictionary a = json.loads(soup.text) # parse parsed_dict = {} for e in a['records']: parsed_dict.setdefault(e['Country'], []).append(e['Name']) # convert dict to json parsed_json = json.dumps(parsed_dict, ensure_ascii=False, indent=4, sort_keys=True) return(parsed_json) if __name__ == '__main__': url = "https://www.w3schools.com/angular/customers.php" my_json = url_parse(url) infoFromJson = json.loads(my_json) print(my_json) print("#" * 40) print json2html.convert(json = infoFromJson)
2e5477d1a7840074b59fb0f655685ce90352c4c1
alexaoh/meeting
/quadrature/trapezoidQuad.py
802
3.71875
4
#Composite trapezoid quadrature implementation def trapezoid(f,a,b,n): ''' Input: f: Function to integrate a: Beginning point b: End point n: Number of intervals. Output: Numerical approximation to the integral ''' assert(b > a) h = float(b-a)/n result = (f(a) + f(b))/2.0 for k in range(1,n): result += f(a + k*h) return h*result #Implementation with numpy (no loop): import numpy as np def trapezoid_numpy(f, a, b, n): assert(b > a) h = (b-a)/n x = np.linspace(a,b,n+1) result = (f(x[0]) + f(x[-1]))*(h/2) return result + h*np.sum(f(x[1:-1:])) #Test #print(trapezoid(lambda x : np.exp(-x**2), 0, 2, 16)) print(trapezoid_numpy(lambda x : (1-np.cos(x))/x**2, 0.000001, np.pi, 4)) #They give the same result!
0a22ab2537a658d377bdd61143b662c7dac9c56e
gansterhuang/-
/时序神经网络模型/序列学习研究/GRU网络学习序列.py
8,099
3.671875
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import Series_generator as sg import matplotlib.pyplot as plt import copy #定义训练集样本数量 data_number=500 x1=sg.series_2() #定义标准化矩阵的函数 def standardization(data): mu = np.mean(data, axis=0) sigma = np.std(data, axis=0) return (data - mu) / sigma #X和F由于量纲原因,数值大小差距比较大,故标准化数据 x1=standardization(x1) #绘制x1 x2 x3 三段位移曲线,绘制F1,F3两段载荷曲线 plt.subplot(111) plt.plot(range(np.shape(x1)[0]),x1) plt.title('x1_curve') plt.show() "这里构造数据集,训练集每次输入的格式为10个数据,即前5个时刻的F1,F3输入" "训练集的结果输入格式为第5个时刻的x1,x2,x3" data=np.zeros((data_number,5),dtype=float)#定义具有(500,5)格式的初始数组 for i in range(data_number): data[i]=np.array([x1[i],x1[i+1],x1[i+2],x1[i+3],x1[i+4]]) #这里数组里前4个数为输入,后一个为输出 data_random=copy.copy(data) np.random.shuffle(data_random)#打乱data顺序,这里data维度(500,5) print(np.shape(data_random)) #构造训练集 #训练集输入 data_x=np.zeros((data_number,4,1),dtype=float)#定义如(500,4)的格式 for i in range(data_number): data_x[i]=[[data_random[i][0]], [data_random[i][1]], [data_random[i][2]], [data_random[i][3]] ] #训练集输出 data_y=np.zeros((data_number,1),dtype=float)#定义如(500,)的格式 for i in range(data_number): data_y[i]=[data_random[i][4]] print(np.shape(data_x)) print(data_x[1]) "tensorflow 组建rnn网络部分" # 序列段长度,即是几步 time_step = 4 # 隐藏层节点数目,每个LSTM内部神经元数量 rnn_unit = 20 # cell层数 gru_layers = 2 # 序列段批处理数目 batch_size = 20 # batch数目 n_batch=data_number//batch_size # 输入维度 input_size = 1 # 输出维度 output_size = 1 # 学习率 lr = 0.00016 #前置网络的隐藏层神经元数量 hidden_size=5 #输出层网络的隐藏层神经元数量 out_hidden_size=5 #这里的none表示第一个维度可以是任意值 x=tf.placeholder(tf.float32,[None,time_step, input_size])# y=tf.placeholder(tf.float32,[None, output_size]) #定义输入输出权值及偏置值 '同时注明一点,这里的bias及weights的写法必须要是这样,后面的saver函数才能正常调用' weights = { 'in': tf.Variable(tf.random_normal([input_size, hidden_size])), 'in_hidden': tf.Variable(tf.random_normal([hidden_size, rnn_unit])), 'out_hidden': tf.Variable(tf.random_normal([rnn_unit, out_hidden_size])), 'out': tf.Variable(tf.constant(0.1, shape=[out_hidden_size, output_size])) } biases = { 'in': tf.Variable(tf.random_normal([hidden_size])), 'in_hidden': tf.Variable(tf.random_normal([rnn_unit])), 'out_hidden': tf.Variable(tf.random_normal([out_hidden_size])), 'out': tf.Variable(tf.constant(0.1, shape=[output_size])) } ''' 结论上来说,如果cell为LSTM,那 state是个tuple,分别代表Ct 和 ht,其中 ht与outputs中的对应的最后一个时刻的输出相等, 假设state形状为[ 2,batch_size, cell.output_size ],outputs形状为 [ batch_size, max_time, cell.output_size ], 那么state[ 1, batch_size, : ] == outputs[ batch_size, -1, : ];如果cell为GRU,那么同理,state其实就是 ht,state ==outputs[ -1 ] ''' ''' LSTM的输入(batch_size,time_step,input_size) LSTM的output(batch_size,time_step,hidden_units) LSTM的state输出(2,batch_size,hidden_units)其中这里的2是由于Ct和ht拼接而成的 GRU的输入(batch_size,time_step,input_size) GRU的output(batch_size,time_step,hidden_units) GRU的state输出(batch_size,hidden_units) ''' def lstm(batch): # 定义输入的权值及偏置值 w_in = weights['in'] b_in = biases['in'] w_hidden = weights['in_hidden'] b_hidden = biases['in_hidden'] # 对输入rnn网络的数据做前置处理 input = tf.reshape(x, [-1, input_size]) #x被置位(bacth_size*time_step,input_size) 的格式(250,3),由于是三维数组无法直接乘,需要进行处理 #前置网络的隐藏层处理 input_hidden=tf.nn.relu(tf.matmul(input, w_in) + b_in) input_rnn = tf.nn.relu(tf.matmul(input_hidden, w_hidden) + b_hidden) input_rnn = tf.reshape(input_rnn, [-1, time_step, rnn_unit])#这里是真实输入rnn网络格式的数据 #定义GRU网络的参数 GRU_cells = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(rnn_unit) for _ in range(gru_layers)]) init_state = GRU_cells.zero_state(batch, dtype=tf.float32) output_rnn, final_states = tf.nn.dynamic_rnn(GRU_cells, input_rnn, initial_state=init_state, dtype=tf.float32) ''' 由于本网络是由两个GRU单元堆叠而成,所以state的输出是2*hidden_unit的,state要取[-1] ''' output = tf.reshape(final_states[-1], [-1, rnn_unit]) # 定义输出权值及偏置值,并对LSTM的输出值做处理 w_out_hidden=weights['out_hidden'] b_out_hidden = biases['out_hidden'] w_out = weights['out'] b_out = biases['out'] out_hidden=tf.nn.tanh(tf.matmul(output,w_out_hidden)+b_out_hidden) pred = 5*(tf.matmul(out_hidden, w_out) + b_out) print(pred.shape.as_list())#查看pred维数 return pred, final_states def train_lstm(): global batch_size with tf.variable_scope("sec_lstm"): pred, _ = lstm(batch_size) loss = tf.reduce_mean(tf.square(pred - y)) train_op = tf.train.AdamOptimizer(lr).minimize(loss) #定义变量存储参数 saver = tf.train.Saver(tf.global_variables()) loss_list = [] with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(1000): # We can increase the number of iterations to gain better result. for i in range(n_batch): _, loss_ = sess.run([train_op, loss], feed_dict={x: data_x[batch_size * i:batch_size * (i + 1)], y: data_y[batch_size * i:batch_size * (i + 1)]}) loss_list.append(loss_) if epoch % 10 == 0: print("Number of epoch:", epoch, " loss:", loss_list[-1]) if epoch > 0 and loss_list[-2] > loss_list[-1]: saver.save(sess, 'model_save1\\GRU_curve_fit_modle_1.ckpt') train_lstm()#运行LSTM网络 "测试部分" #测试集输入, test_number=950 test_data=np.zeros((test_number,4,1),dtype=float)#定义具有(500,4,1)格式的初始数组 for i in range(test_number): test_data[i]=np.array([[x1[i]],[x1[i+1]],[x1[i+2]],[x1[i+3]]]) #这里数组里前4个数为输入,后一个为输出 #用模型计算得出的输出 with tf.variable_scope("sec_lstm", reuse=tf.AUTO_REUSE): prey, _ = lstm(1) #这里预测,所以输入的batch_size为1就可以 saver = tf.train.Saver(tf.global_variables()) pre_list=[] with tf.Session() as sess: saver.restore(sess, 'model_save1\\GRU_curve_fit_modle_1.ckpt') for i in range(test_number): next_seq = sess.run(prey, feed_dict={x: [test_data[i]]}) pre_list.append(next_seq) # 计算均方根误差 pre_list_np=np.array(pre_list) pre_list_np=np.reshape(pre_list_np,(950,)) rmse = 0.0 for i in range(test_number): rmse=rmse+(pre_list_np[i]-x1[i+4])**2 rmse=np.sqrt((rmse/test_number)) rmse=np.around(rmse, decimals=6) #绘制图像 plt.plot(range(np.shape(x1)[0]), x1) plt.plot(range(np.shape(x1)[0])[4:4+test_number], pre_list_np, color='r') plt.text(900, 8, 'rmse='+str(rmse), fontsize=20) plt.show()
b090f5b4253f0a2318f124b6a6b94ae8992a50a9
zhaofeng555/python2-test
/pytest/hjg/spe.py
177
3.6875
4
#!/usr/bin/python print 'abc'+'xyz' print 'abc'.__add__('xyz') print (1.8).__mul__(2.0) print len([1,2,3]) print [1,2,3].__len__() li=[1,2,3,4,4,5,6] print(li.__getitem__(3))
3d4e601737b5c07cdb33a1f1773b454dfc1c17c5
zhaofeng555/python2-test
/pytest/hjg/str.py
233
3.9375
4
#!/usr/bin/python name='hello world' if name.startswith('hel'): print 'yes, the string starts with "hel"' if 'o' in name: print 'yes, it contains "o"' delimiter="hehe" mylist=['aa', 'bb', 'cc', 'dd'] print delimiter.join(mylist)
17f06f032b23c1e29fe9bd6dfcff5bbc14024ca3
zhaofeng555/python2-test
/pytest/hjg/9x9.py
159
3.546875
4
#coding:utf-8 for i in range(1, 9): for j in range(1, i+1): print i,'*',j,'=',(i*j), print '' else: print '九九乘法表完事'
dfd5901190b3715f8b3727b9600518bed7b29a36
jdalichau/classlabs
/letter_removal.py
982
4.1875
4
#CNT 336 Spring 2018 #Jaosn Dalichau #jdalichau@gmail.com #help with .replace syntax found it the book 'how to think like a computer scientist' interactive edition #This code is designed to take an input name and remove vowels of any case n = input('Enter your full name: ') #input statement for a persons full name if n == ('a') or ('e') or ('i') or ('o') or ('u'): #If statement declaring lower case values n = n.replace('a','')#remove a n = n.replace('e', '')#remove e n = n.replace('i','')#remove i n = n.replace('o','')#remove o n = n.replace('u','')#remove u if n == ('A') or ('E') or ('I') or ('O') or ('U'):#second if statement declaring upper case values n = n.replace('A','')#remove A n = n.replace('E', '')#remove E n = n.replace('I','')#remove I n = n.replace('O','')#remove O n = n.replace('U','')#remove U print(n)#print the input with or without replaced values
a9c972ff3829d7dd690221bc001b89dcf73e642f
AkulinaSaint/Python-code-examples
/05_easy.py
2,055
3.921875
4
# Задача-1: # Напишите скрипт, создающий директории dir_1 - dir_9 в папке, # из которой запущен данный скрипт. # И второй скрипт, удаляющий эти папки. import os import sys import shutil print(sys.argv) def make_a_lot_of_dir(): if not sys.argv[1]: print('Вы забыли передать первый параметр add_dirs') return for x in range(0, 9): dir_path = os.path.join(os.getcwd(), 'dir_{}'.format(1 + x)) try: os.mkdir(dir_path) print('Директория {} создана!'.format(dir_path)) except FileExistsError: print('Такая директория {} уже существует!'.format(dir_path)) def delete_generated_dirs(): for x in range(0, 9): dir_path = os.path.join(os.getcwd(), 'dir_{}'.format(1 + x)) try: os.rmdir(dir_path) print('Директория {} удалена!'.format(dir_path)) except FileNotFoundError: print('Такой директории {} здесь не было!'.format(dir_path)) if not sys.argv[1]: print('Вы забыли передать первый параметр add_dirs') if sys.argv[1] == 'add_dirs': make_a_lot_of_dir() elif sys.argv[1] == 'delete_dirs': delete_generated_dirs() # Задача-2: # Напишите скрипт, отображающий папки текущей директории. elif sys.argv[1] == 'show_dirs': print(os.listdir(os.getcwd())) # Задача-3: # Напишите скрипт, создающий копию файла, из которого запущен данный скрипт. elif sys.argv[1] == 'copy_file': current_file = os.path.join(os.getcwd(), sys.argv[0]) new_file = os.path.join(os.getcwd(), sys.argv[0] + 'new') shutil.copyfile(current_file, new_file) print('Файл {} создан!'.format(sys.argv[0] + 'new')) else: pass
4fba8865f46597abff778e63bccf77de1b190fb9
SMAshhar/Temp-Ashhar1
/HTML CSS/my-smarter-site/Testing.py
969
3.84375
4
class Navi(): def __init__(self, x, y): self.x = x self.y = y def newPos(self, x1, y1): self.x = x1 self.y = y1 dot = Navi(0,3) import numpy as np a = [[0,0,0,1,0,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,0], [0,1,0,0,0,0,1,0,1,0], [0,1,1,1,0,1,1,0,1,0], [0,1,0,1,0,1,0,0,1,0], [0,1,1,1,1,1,0,1,1,0], [0,0,0,0,0,1,0,0,0,0], [0,1,0,1,0,1,0,0,1,0], [0,1,1,1,1,1,1,1,1,0], [0,0,0,0,0,0,0,1,0,0]] while dot.x != 9 and dot.y != 9: if a[dot.x + 1][dot.y] == 1 and a[dot.x][dot.y - 1] != 1 and a[dot.x][dot.y + 1] != 1: dot.x += 1 print(a[dot.x][dot.y]) elif a[dot.x + 1][dot.y] != 1 and a[dot.x][dot.y - 1] != 1 and a[dot.x][dot.y + 1] == 1: dot.y += 1 print(a[dot.x][dot.y]) elif a[dot.x + 1][dot.y] != 1 and a[dot.x][dot.y - 1] == 1 and a[dot.x][dot.y + 1] != 1: dot.y -= 1 print(a[dot.x][dot.y])
6373adb8318ea1a23b4a1f5a45babfa27756862d
bdarrenn/LR3_CPE106L
/POSTLAB_PROGRAMS_UMLS/PROJECT_2/student.py
2,386
3.9375
4
import random class Student(object): """Represents a student.""" def __init__(self, name, number): """All scores are initially 0.""" self.name = name self.scores = [] for count in range(number): self.scores.append(0) def getName(self): """Returns the student's name.""" return self.name def setScore(self, i, score): """Resets the ith score, counting from 1.""" self.scores[i - 1] = score def getScore(self, i): """Returns the ith score, counting from 1.""" return self.scores[i - 1] def getAverage(self): """Returns the average score.""" return sum(self.scores) / len(self.scores) def getHighScore(self): """Returns the highest score.""" return max(self.scores) def __eq__(self, other): """Returns if equal or not""" if (self.name == other.name): return "Equal" else: return "Not Equal" def __lt__(self, other): """Returns if less than or not""" if (self.name < other.name): return "Less Than" else: return "Not less than" def __gt__(self, other): if self.name > other.name: return "Greater than" elif self.name == other.name: return "Both are equal" else: return "Not greater or equal" def __str__(self): """Returns the string representation of the student.""" return "Name: " + self.name + "\nScores: " + \ " ".join(map(str, self.scores)) def main(): """A simple test.""" studentsList = [] student = Student("Justine", 5) for i in range(1, 6): student.setScore(i, 100) studentsList.append(student) student1 = Student("Mon", 8) for i in range(1, 9): student1.setScore(i, 100) studentsList.append(student1) student2 = Student("Darren", 5) for i in range(1, 6): student2.setScore(i, 100) studentsList.append(student2) random.shuffle(studentsList) print("Shuffled list of Students: ") for i in studentsList: print(i.__str__()) print("\nSorted list of Students: ") studentsList.sort(key = lambda x:x.name) for i in studentsList: print(i.__str__()) if __name__ == "__main__": main()
a877ed0d8f74dc61e1e490642788ac021cc23722
bandisri/python
/guessthenumber.py
726
3.84375
4
import random import math def main(): print("Hit 'E' to exit") gussedNumber = input("Guess Number between 1 - 100: ") while gussedNumber.upper() != 'E': if gussedNumber.isdigit() and ( int(gussedNumber) > 0 and int(gussedNumber) <= 100 ): generatedNumber = random.randint(1,10) if int(gussedNumber) == generatedNumber: print("Guess is correct!!!!!") else: print("Wrong Guess, number is {}".format(generatedNumber)) else: print('XXXXXXX - Check your input - XXXXXXX') gussedNumber = input("Guess another number?") else: print("Exiting program...........") if __name__ == '__main__': main()
2ba9e7c3dba0e5eed7cf3ca843938c5fc4021650
sripadaraj/pro_programs
/python/forloops/sort.py
152
3.515625
4
a=[1,2,33,23,4,5,6,8] print a for i in range(0,len(a)): for j in range(i+1,len(a)): if a[i]>=a[j] : a[i],a[j]=a[j],a[i] print a
6ad233abf66a03c2690d6450f9a54f56d83048ed
sripadaraj/pro_programs
/python/starters/biggest_smallest.py
1,015
4.1875
4
print "The program to print smallest and biggest among three numbers" print "_____________________________________________________________" a=input("enter the first number") b=input("enter the second number") c=input("enter the third number") d=input("enter the fourth number") if a==b==c==d : print "all are equal " else : if a>=b and a>=c and a>=d: big=a if a<=b and a<=c and a<=d: small=a if b>=a and b>=c and b>=d: big=b if b<=a and b<=c and b<=d: small=b if c>=a and c>=b and c>=d: big=c if c<=a and c<=b and c<=d: small=c if d>=a and d>=b and d>=c: big=d if d<=a and d<=b and d<=c: small=d print "_______________________________________________________________" print "the biggest among ",a,",",b,",",c,",",d,"is :\n" print big print "the smallest among ",a,",",b,",",c,",",d,"is :\n" print "smallest",small print "_______________________________________________________________"
54ec15a92464e0c90249e38b73ffa6b4bcf9295d
sripadaraj/pro_programs
/python/forloops/vowels1.py
159
3.5625
4
s1= raw_input("enter a string check how many vowels does it have") d={"a":0,"e":0,"i":0,"o":0,"u":0} for i in s1 : if i in d: d[i]=d[i]+1 print d
833100e3910b92bf1f55a0bb4a3653bd952ad6bb
sripadaraj/pro_programs
/python/forloops/count_string2.py
209
3.984375
4
#def char_frequency(str1): str1=raw_input("enter the string") dict1 = {} for n in str1: if n in dict1: dict1[n] += 1 else: dict1[n] = 1 print dict1 #print(char_frequency('google.com'))
23bd889858bf051c633b4e72ad04f209fdf85006
JuanbiB/Rotation-Optimization-WoW
/classes.py
3,435
3.5625
4
import random """Juan Bautista Berretta & Jack Reynolds 2016 Reinforcement Learning Project """ GCD = 1.5 """ Ability class to encapsulate the the functionality of different abilities. """ class Ability: def __init__(self, name, damage, cd, cost): self.name = name self.damage = damage self.cost = cost self.cd = cd self.remaining_time = 0 """ To check if an ability is on CD or not. """ def canUse(self): if self.remaining_time <= 0: return True else: return False """ Returns damage and activates CD. """ def useAbility(self, battle_cry): crit_chance = random.uniform(0.0, 100.0) self.remaining_time = self.cd # battlecry guarantees crit strike if not battle_cry: if crit_chance < 15.07: print("Critical strike for ability: " + self.name) return self.damage * 2 else: return self.damage else: return self.damage * 2 """ Target objects that gets passed from state to state, in order be able to finish an episode (when the health's depleted). """ class Target: def __init__(self, health): self.health = health self.full_health = health self.colossus_smash = 0 # duration left in damage boost self.battle_cry = 0 # guaratneed crit strike self.avatar = 0 def takeDamage(self, ability): if self.battle_cry: damage = ability.useAbility(True) # Parameter guarantees critical strikes else: damage = ability.useAbility(False) # original damage kept for boosting abilities og_damage = damage # damage modifying if self.colossus_smash > 0: damage += ((og_damage/100) * 47) # + 47% damage boost if self.avatar > 0: damage += ((og_damage/100) * 20) # + 20% damage boost # CD refreshing elif ability.name == "colossus_smash": self.colossus_smash = 8 elif ability.name == "avatar": self.avatar = 20 elif ability.name == "battle_cry": self.battle_cry = 5 # Actual health deduction self.health -= damage # Used to decrease timers of enhancing effects def checkEffects(self): self.avatar -= GCD self.colossus_smash -= GCD self.battle_cry -= GCD # Useful for debugging def printStatus(self): print("\nTarget status: ") print("Life: " + str((self.health / self.full_health) * 100)) print("Cooldowns:") print("\tColossus Smash: " + str(self.colossus_smash)) print("\tBattle Cry: " + str(self.battle_cry)) print("\tAvatar: " + str(self.avatar) + "\n") print("<------------------------>") """ State class that holds a list of abilities and the state of the current target. """ class State: def __init__(self, abilities, target): self.abilities = abilities self.target = target self.rage = 100 self.auto_attack_timer = 3.6 def decreaseRage(self, amount): self.rage -= amount def decreaseTimer(self, amount, target): self.auto_attack_timer -= amount if self.auto_attack_timer <= 0: target.rage += 25 # increase rage self.auto_attack_timer += 3.6 # reset timer
b6bd22d9d207e9cd75d3f06e4e9e43d3b80af360
Shijie97/python-programing
/ch04/8-function(3).py
685
4.1875
4
# !user/bin/python # -*- coding: UTF-8 -*- def func(a, b = 2, c = "hello"): # 默认参数一定是从最后一个开始往左连续存在的 print(a, b, c) func(2, 100) # 覆盖了b = 2 i =5 def f(arg = i): print(i) i = 6 f() # 6 # 在一段程序中,默认值只被赋值一次,如果参数中存在可变数据结构,会进行迭代 def ff(a, L = []): L.append(a) return L print(ff(1)) # [1] print(ff(2)) # [1, 2] print(ff(3)) # [1, 2 ,3] # 不想迭代的话,就如下所示 def fff(a, L = None): if L is None: L = [] L.append(a) return L print(fff(1)) # [1] print(fff(2)) # [2] print(fff(3)) # [3]
3e0adfb7a5611c6095186c900e830d5ce6f8d001
Shijie97/python-programing
/ch05/8-loop tricks.py
675
3.6875
4
# !user/bin/python # -*- coding: UTF-8 -*- # 字典遍历 dic = {x : x ** 2 for x in range(10)} for k, v in dic.items(): print(k, v) # 数组遍历 lst = list(range(10)) for i, e in enumerate(lst): print(i, e) # zip打包 lst1 = [chr(x) for x in range(97, 97 + 26)] lst2 = list(range(97, 97 + 26)) for c, n in zip(lst1, lst2): print('{0} -> {1}'.format(c, n)) print(list(zip(lst1, lst2))) # 元组对儿,一溜儿存在一个list里面 # 如果循环的时候想要修改正在遍历的序列,则应该遍历其副本 lst = list(range(10)) for e in lst[:]: # 这里用的就是副本 if e > 5: lst.remove(e) print(lst)
5dec35884f68e244093f09a30121f04bb9c52aba
Shijie97/python-programing
/ch04/7-function(2).py
369
3.859375
4
# !user/bin/python # -*- coding: UTF-8 -*- def fib2(n): """定义一个斐波那契数列,不打印,返回一个list""" lst = [] a, b = 1, 1 while(a <= n): lst.append(a) a, b = b, a + b return lst f = fib2(100) print(f) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] print(type(f)) # <class 'list'> print (1 in f) # True
01edc69712cc340ab98aab6edef608483102deda
Shijie97/python-programing
/ch05/2-list(2).py
499
4.125
4
# !user/bin/python # -*- coding: UTF-8 -*- from collections import deque lst = [100, 1, 2, 3, 2] # 列表当做stack使用 lst.append(5) # push print(lst) lst.pop() # pop print(lst) # 列表当做queue用 queue = deque(lst) print(queue) queue.append(5) # 入队 deque([0, 1, 2, 3, 2]) print(type(queue)) # <class 'collections.deque'> print(queue) res = queue.popleft() # 出队,并返回出队的元素 print(res) print(queue) print(list(queue)) # 强制转化成list结构
c4f942aae920b00d89c010e7c98adf7ab665a19b
sundarcsk/hello
/flightdetails.py
613
3.546875
4
inpp="Sundar:1234567890:Delhi,Raman:234567890:Mumbai" result="" if(',' in inpp): strinpp=inpp.split(',') dummy=0 # print(str(strinpp)) for i in strinpp: sum=0 dummy+=1 coloninpp=i.split(':') # print(coloninpp) for num in coloninpp[1]: sum+=int(num) result+=coloninpp[0][:2]+str(sum)+coloninpp[2][-2:] if(len(strinpp)!=dummy): result+=',' else: coloninpp=inpp.split(':') for num in coloninpp[1]: sum+=int(num) result+=coloninpp[0][:2]+str(sum)+coloninpp[2][-2:] print(result)
56fe0d6a863dc1d1cb5479ec2fded1d298eeb561
Fastwriter/Pyth
/Daulet Demeuov t1/A.py
335
3.65625
4
#STUDENT: Daulet Demeuov #GROUP: EN1-C-04 #TASK: Task1 problem A #Description: Read five-digit number; find sum and product of digits. while True: a = str(input('Enter number ')) b = int(a[0])+int(a[1])+int(a[2])+int(a[3])+int(a[4]) c = int(a[0])*int(a[1])*int(a[2])*int(a[3])*int(a[4]) print('Sum:',b) print('Product:',c)
57441b841c695d0b2c4318b00bcd80a2a03a219c
Fastwriter/Pyth
/__pycache__/sss.py
903
3.90625
4
import math class triangle: def __init__(self, a=0, b=0, c=0): self.a=a self.b=b self.c=c def __str__(self): if(self.a==self.b==self.c): k='Equal' elif(self.a==self.b!=self.c or self.a==self.c!=self.b or self.b==self.c!=self.a): k='Isos' else: k='just' return('The sides are %d, %d, %d, triangle is %s' %(self.a,self.b,self.c,k)) def area(self): p=(self.a+self.b+self.c)/2 return math.sqrt(p*(p-self.a)*(p-self.b)*(p-self.c)) def compare(self, self2): if(triangle.area(self)>triangle.area(self2)): return ('First is greater') if(triangle.area(self)<triangle.area(self2)): return ('First is less') else: return('There are equal') t=triangle(3,4,5) print(t) t2=triangle(5,12,12) print(t2) print(triangle.compare(t, t2))
7c5cc01a65c131ed91a9aae1547e8e6980ffac3a
Fastwriter/Pyth
/Питон ост/C.py
163
3.640625
4
def func(): A=input('write the number') B=input('write the number') A=int(A) B=int(B) C=int(A+B) D=int(A*B) print('sum',C,'product',A)
adb90cf16198b6628d8ebc30412adcd4be2ec480
Fastwriter/Pyth
/Питон ост/C1.py
119
3.890625
4
def func(): a=int(input('Value:')) if(a<0): print('Maximum is ',a) else:while True
df905a595e5480a0b8b8af53f55d4c8397499a52
Fastwriter/Pyth
/Питон ост/circle.py
292
3.953125
4
def func(): import math A=input('X1') B=input('Y1') C=input('X2') D=input('Y2') E=input('R') A=int(A) B=int(B) C=int(C) D=int(D) E=int(E) F=float(((C-A)**2+(D-B)**2)**0.5) if(F<E): print('inside') else: print('outside')
ac3b5b6cb12a4b4f66104f7d3ea9242a261ac277
Fastwriter/Pyth
/Питон ост/recursion/n.py
84
3.578125
4
def pan(a): if(a<0): return else: print(a) pan(a-1)
9bc028e47d9e102d4c87ed14377a193653e68b28
Fastwriter/Pyth
/Питон ост/grade.py
212
3.625
4
def grade(a): if(100>=a>=90): print("A") elif(89>=a>=75): print("B") elif(74>=a>=60): print("C") elif(59>=a>=50): print("D") elif(49>=a>=0): print("F")
2ead845f157ed118e0333c47decc884456cfbe1d
Fastwriter/Pyth
/02.11.16/5.py
138
3.515625
4
def tran(e,r): d={} c=len(e) for i in e: d[i]=list() for i in range(c): d[e[i]].append(r[i]) print(d)
eac86ec920a1100221c52806bf21bcad3e06ed4b
thuongtran1210/Buoi1
/Bai5.py
169
3.59375
4
print("Nhập số gồm hai chữ số: ",end='') a=int(input()) chuc=a//10 donvi=a%10 print("Hàng chục là: ",str(chuc)) print("Hàng đơn vị là: ",str(donvi))
005f8facc445d02847d4ec59de367642982741e2
paucarre/Expression
/tests/test_gen.py
2,821
3.765625
4
""" This file is just to explore how generators works """ from typing import Generator import pytest # from hypothesis import given, strategies as st def test_generator_with_single_empty_yield(): def fn(): yield gen = fn() value = next(gen) assert value is None def test_generator_with_single_empty_yield_double_next(): def fn(): yield gen = fn() value = next(gen) assert value is None with pytest.raises(StopIteration) as ex: # type: ignore next(gen) assert ex.value.value is None def test_generator_with_single_yield_value(): def fn(): yield 42 gen = fn() value = next(gen) assert value == 42 def test_generator_with_multiple_yield_value(): def fn(): yield 2 yield 4 gen = fn() value = next(gen) assert value == 2 value = next(gen) assert value == 4 def test_generator_with_single_return_value(): def fn(): return 42 yield gen = fn() # Return in a generator is just syntactic sugar for raise StopIteration with pytest.raises(StopIteration) as ex: # type: ignore next(gen) # type: ignore assert ex.value.value == 42 def test_generator_with_multiple_return_value(): def fn(): return 2 return 4 yield gen = fn() # Return in a generator is just syntactic sugar for raise StopIteration with pytest.raises(StopIteration) as ex: # type: ignore next(gen) # type: ignore assert ex.value.value == 2 with pytest.raises(StopIteration) as ex: # type: ignore next(gen) # type: ignore # Cannot get value from second return assert ex.value.value is None def test_generator_with_yield_assignment_and_yield(): def fn() -> Generator[int, int, None]: x = yield 42 yield x gen = fn() value = next(gen) assert value == 42 value = gen.send(10) # type: ignore assert value == 10 def test_generator_with_yield_assignment_and_return(): def fn() -> Generator[int, int, int]: x = yield 42 return x gen = fn() value = next(gen) assert value == 42 with pytest.raises(StopIteration) as ex: # type: ignore gen.send(10) # type: ignore assert ex.value.value == 10 def test_generator_with_yield_from(): def fn(): yield from [42] gen = fn() value = next(gen) assert value == 42 def test_generator_with_yield_from_gen(): def gn(): yield 42 def fn(): yield from gn() gen = fn() value = next(gen) assert value == 42 def test_generator_with_yield_from_gen_empty(): def gn(): yield from [] def fn(): yield from gn() yield 42 gen = fn() value = next(gen) assert value == 42
0a913794075bb24d0b683692b640ff007ae6c200
paucarre/Expression
/tests/test_choice.py
676
3.578125
4
from expression import Choice, Choice1of2, Choice2, Choice2of2, match def test_choice_choice1of2(): xs: Choice2[int, str] = Choice1of2(42) assert isinstance(xs, Choice) assert isinstance(xs, Choice2) with match(xs) as case: for x in Choice1of2.match(case): assert x == 42 break else: assert False def test_choice_choice2of2(): xs: Choice2[int, str] = Choice2of2("test") assert isinstance(xs, Choice) assert isinstance(xs, Choice2) with match(xs) as case: for x in Choice2of2.match(case): assert x == "test" break else: assert False
e183ac98fe31cee46d4a8ec4d97fe0c6ff29a752
potatoHVAC/leet-code-solutions
/1290-Convert-Binary-Num.py
2,302
3.9375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None """ Psudocode: FOR SINGLY-LINKED LIST TRAVERSAL Go to first ListNode Append ListNode.value to binary number list Go to second ListNode Append ListNode.value to binary number list Repeat until ListNode.next = None FOR BINARY CONVERSION Reverse the list. Loop through list. If the digit is a 1 Add the value of the current place to the final number If the place value is one Only increment by one Else If the place value is one Only increment by one Else Double the place value Return final number """ import unittest def build_binary(head): pointer = head binary = list() while True: binary.append(pointer.val) if pointer.next is None: break else: pointer = pointer.next def convert_binary(binary): number = 0 value = 1 binary.reverse() for i in binary: if i == 1: number += value if value == 1: value += 1 else: value *= 2 else: if value == 1: value += 1 else: value *= 2 return number class TestBin(unittest.TestCase): def test_101(self): input = convert_binary([1, 0, 1]) output = 5 self.assertEqual(input, output) def test_0(self): input = convert_binary([0]) output = 0 self.assertEqual(input, output) def test_00(self): input = convert_binary([0, 0]) output = 0 self.assertEqual(input, output) def test_01101(self): input = convert_binary([0, 1, 1, 0, 1]) output = 13 self.assertEqual(input, output) def test_11011(self): input = convert_binary([1, 1, 0, 1, 1]) output = 27 self.assertEqual(input, output) def test_10010001(self): input = convert_binary([1, 0, 0, 1, 0, 0, 0, 1]) output = 145 self.assertEqual(input, output) if __name__ == '__main__': unittest.main() # convert_binary([1, 0, 1])
e75a405199bd9ffcc9e9ed35f6db998c705d9934
de-nuke/prir_tsp
/ga_functions.py
2,614
3.546875
4
import random def distance(p1, p2): return ((p1[0] - p2[0])*(p1[0]-p2[0]) + (p1[1] - p2[1]) * (p1[1] -p2[1]))**(1/2) def path_distance(path, cities): dist = 0 for i in range(1, len(path)): dist += distance(cities[path[i-1]], cities[path[i]]) return dist def reproduce(population, cities): fitnesses = [1/path_distance(path, cities) for path in population] fitness_sum = sum(fitnesses) size = len(population) next_population = [] probability = [fitnesses[0]/fitness_sum] for i in range(1, size): probability.append(((fitnesses[i]) / fitness_sum) + probability[i-1]) probability[-1] = 1.0 for i in range(size): chance = random.random() j = 0 while (chance > probability[j]): j += 1 next_population.append(population[j]) return next_population def cross(population): if len(population) <= 1: return population pairs = [] #population = list(population.copy()) while len(population) > 1: r1 = population.pop(random.randrange(0, len(population))) r2 = population.pop(random.randrange(0, len(population))) pairs.append((r1, r2)) for p1, p2 in pairs: const_positions, i, stop, item = [], 0, p1[0], None while item != stop: const_positions.append(i) item = p2[i] i = p1.index(item) population.append(''.join([p1[i] if i in const_positions else p2[i] for i in range(len(p1))])) population.append(''.join([p2[i] if i in const_positions else p1[i] for i in range(len(p2))])) return population def mutate(population, mutation_prob=0.01): size = len(population) cities_length = len(population[0]) for i in range(size): for j in range(cities_length): chance = random.random() if chance >= 1 - mutation_prob: randj = random.randint(0, cities_length -1) path = list(population[i]) path[j], path[randj] = path[randj], path[j] population[i] = ''.join(path) return population def find_path_statistics(population, cities): best = (path_distance(population[0], cities), population[0]) worst = (path_distance(population[0], cities), population[0]) average = 0 for path in population: dist = path_distance(path, cities) if dist < best[0]: best = (dist, path) if dist > worst[0]: worst = (dist, path) average += dist average = average / len(population) return best, average, worst
ba2e076ef77275add34ec9be6d65fbf09d7834f2
deckardmehdy/coursera
/Course2/Week4/phoneBook.py
618
3.890625
4
# python3 ### START OF PROGRAM ### n = int(input()) # Create an empty dictionary phoneBook = {} for i in range(n): request = [str(x) for x in input().split()] if request[0] == "add": # add phoneBook[request[1]] = request[2] elif request[0] == "find": # find number = request[1] phoneBook.setdefault(number,None) person = phoneBook[number] if person != None: print(person) else: print("not found") else: # delete number = request[1] phoneBook.pop(number, None)
dddda83ba6a039d30ef4ff0da2e264dd933aa582
deckardmehdy/coursera
/Course4/Week1/constructTrie.py
2,529
3.953125
4
# Runs using Python 3 import queue def nextNode(trie,currentNode,letter): # See how many letters are in the node's adjanency list nextNodes = len(trie[str(currentNode)][1]) # If there are none, then return None if nextNodes == 0: return None # If there are some, loop through and return if # the letter we are looking for is found: else: for i in range(nextNodes): nextNode = trie[str(currentNode)][1][i] if trie[str(nextNode)][0][-1] == letter: return trie[str(currentNode)][1][i] # If none of them match the letter, return None return None def makeTrie(n,patterns): # Create empty dict to store trie tree # Make the "0" the root node trie, nodeCount = {}, 1 trie["0"] = [[],[]] # Loop through all patterns: for p in range(n): currentNode, pattern = 0, patterns[p] # Go through each letter in each pattern for i in range(len(pattern)): letter = pattern[i] newNode = nextNode(trie,currentNode,letter) # If the letter exists in the adjacency list, then move onto the next one if newNode != None: currentNode = newNode # Otherwise, create a new node with the new letter # and append it to the current node's adacency list else: trie[str(currentNode)][1].append(nodeCount) trie[str(nodeCount)] = [[letter],[]] currentNode = nodeCount nodeCount += 1 # Returnt the trie tree at the end return trie def printTrie(trie): # Create a FIFO queue and add the root node myQueue = queue.Queue() myQueue.put(0) # Go through all nodes in the trie tree # Adding and printing nodes as they are explored while myQueue.empty() != True: currentNode = myQueue.get() nextNodes = len(trie[str(currentNode)][1]) if nextNodes > 0: for i in range(nextNodes): newNode = trie[str(currentNode)][1][i] newNodeLetter = trie[str(newNode)][0][-1] myQueue.put(newNode) print(str(currentNode) + "->" + str(newNode) + ":" + str(newNodeLetter)) ################################ ####### START OF PROGRAM ####### ################################ n = int(input()) # Record patterns patterns = [""] * n for i in range(n): patterns[i] = str(input()) trie = makeTrie(n,patterns) printTrie(trie)
92e14ec8324f5affbbdd48b38209d666dae8c70f
deckardmehdy/coursera
/Course4/Week4/knuth_morris_pratt.py
835
3.578125
4
# Runs using Python 3 def computePrefixFunction(P): s = [0] * len(P) border = 0 for i in range(1,len(P)): while (border > 0) and (P[i] != P[border]): border = s[border-1] if P[i] == P[border]: border += 1 else: border = 0 s[i] = border return s def findAllOccurrences(P,T): S = P + "$" + T s = computePrefixFunction(S) result = [] for i in range((len(P)+1),len(S)): if s[i] == len(P): result.append(i-(2*len(P))) return result ################################ ####### START OF PROGRAM ####### ################################ P = str(input()) T = str(input()) if len(P) > len(T): print() else: result = findAllOccurrences(P,T) if len(result) > 0: print(*result) else: print()
8ccd7e7add949ccd48dc9f14c445bce91921c773
deckardmehdy/coursera
/Course4/Week1/suffixTree.py
9,174
3.953125
4
# Runs using Python 3 class SuffixTree: class Node: # Node constructor: def __init__(self,starting_index,length): self.starting_index = starting_index self.length = length self.children = [] self.marker = None # Suffix Tree constructor: def __init__(self): self.root = None def divide(self,node,splitting_index): # Create a new node new_length = node.length - splitting_index new_pointer = node.starting_index + splitting_index newNode = self.Node(new_pointer,new_length) # Transfer over the old pointers and parameters # to the new node newNode.children = node.children # Change parameters of the old node node.children = [newNode] node.length = node.length - new_length def add_child(self,node,starting_index,length): newNode = self.Node(starting_index,length) node.children.append(newNode) return newNode def suffixTree(text): # Create a suffix tree object and make a root node mySuffixTree = SuffixTree() root = mySuffixTree.Node(None,None) mySuffixTree.root = root # Go through all suffixs in text and add them to the tree: for s in range(len(text)): suffix = text[s:len(text)] node, pointer = root, s while pointer < len(text): children, found, i = node.children, False, 0 while i < len(children): childString = nodeString(children[i],text) remainingSuffix = text[pointer:len(text)] overlap = checkOverlap(remainingSuffix,childString) # If we do find a match: if overlap > 0: charsLeft = len(text) - (pointer + overlap) # If the entire child's string was matched: if overlap == len(childString): if charsLeft > 0: node = children[i] pointer += overlap # If the entire child's string wasn't matched, # split the current node: else: mySuffixTree.divide(children[i],overlap) # If the suffix isn't finished, add a new # node with the remaining suffix: if charsLeft > 0: newNode = mySuffixTree.add_child(children[i],(pointer+overlap),charsLeft) pointer = len(text) i, found = len(children), True else: i += 1 # If no children were found that match the suffix, # then add a new child with the remaining suffix if found == False: length = len(text) - pointer newNode = mySuffixTree.add_child(node,pointer,length) pointer += length return mySuffixTree def checkOverlap(suffixString,nodeString): overlap, j = 0, 0 minRange = min(len(suffixString),len(nodeString)) while j < minRange: if suffixString[j] == nodeString[j]: overlap += 1 j += 1 else: j = minRange return overlap def nodeString(node,text): start = node.starting_index end = node.length + start return text[start:end] def pathTo(node,stack,text,type): str = "" if type == "leaf": i = len(stack) - 2 else: i = len(stack) - 1 while i > 0: node = stack[i] str = nodeString(node,text) + str i -= 1 return str def findPoundSym(string): for i in range(len(string)): if string[i] == "#": return [i,True] return [None,False] def allChildrenMarked(node,stack): parent = stack[-2] parentsChildren = parent.children for i in range(len(parentsChildren)): sibling = parentsChildren[i] if (sibling != node) and (sibling.marker == None): return False return True def childrenMark(node,stack): parent = stack[-2] parentsChildren = parent.children for i in range(len(parentsChildren)): sibling = parentsChildren[i] if (sibling != node) and (sibling.marker == "R"): return "R" return "L" def swapParentsChildren(node,stack): parent = stack[-2] parentsChildren = parent.children for i in range(len(parentsChildren)): if parentsChildren[i] == node: parentsChildren[-1], parentsChildren[i] = parentsChildren[i], parentsChildren[-1] def getUniqueStrings(text1,text,tree): # Create a stack with the root on top stack = [tree.root] # Initialize result to longest possible unique sequence result = text1 # Do a DFS of the tree while len(stack) > 0: # Peek at the top of the stack #print("Stack length: " + str(len(stack))) node = stack[-1] children = node.children # See if the node is a leaf or non-leaf node: if len(children) > 0: # Non-leaf # Check if any leaves aren't marked i, leafMarkings = 0, "L" while i < len(children): #print("Entering child loop...") child = children[i] # If one isn't, then put it on top of the stack if child.marker == None: #print("Child with string " + nodeString(child,text) + " being added to top of stack") stack.append(child) i = len(children)+1 # break from loop & set flag else: i += 1 if child.marker == "R": leafMarkings = "R" # All leaves have been marked: if i != (len(children)+1): #print("Entering all leaves marked loop...") if (leafMarkings == "L"): node.marker = "L" newResult = pathTo(node,stack,text,"non-leaf") #print("Node with string " + nodeString(node,text) + " has just been marked with L!") #print("String from root to node is " + newResult) if len(newResult) < len(result): result = newResult #print("Result has been updated to " + str(result)) else: node.marker = "R" _ = stack.pop() #print("Stack was just popped!") else: # Leaf [index,found] = findPoundSym(nodeString(node,text)) if (found == True) and (index > 0): # see if this statement is valid node.marker = "L" string = nodeString(node,text) newResult = pathTo(node,stack,text,"leaf") + string[0] #print("Node with string " + nodeString(node,text) + " has just been marked with L!") #print("String from root to node is " + newResult) if len(newResult) < len(result): result = newResult #print("Result has been updated to " + str(result)) # Special case: if all parents leaves are L and leaf starts with '#' elif (found == True) and (index == 0) and (len(stack) > 2): # Check if all of its parent's children have been marked: if allChildrenMarked(node,stack) == True: # Check if all children have a mark 'L' if childrenMark(node,stack) == "L": node.marker = "L" string = nodeString(node,text) newResult = pathTo(node,stack,text,"leaf") #print("Node with string " + nodeString(node,text) + " has just been marked with L!") #print("String from root to node is " + newResult) if len(newResult) < len(result): result = newResult #print("Result has been updated to " + str(result)) else: node.marker = "R" #print("Node with string " + nodeString(node,text) + " has just been marked with R!") # If they haven't been checked, then put this node # at the end of the parents children else: swapParentsChildren(node,stack) #print("Node being swapped...") else: node.marker = "R" #print("Node with string " + nodeString(node,text) + " has just been marked with R!") _ = stack.pop() return result ################################ ####### START OF PROGRAM ####### ################################ text1 = str(input()) text2 = str(input()) text = text1 + "#" + text2 + "$" # Make a suffex tree from the text tree = suffixTree(text) # Print trie tree print(getUniqueStrings(text1,text,tree))
3da4a7809e976185f86615502b92bedef571a016
deckardmehdy/coursera
/Course4/Week1/patternMatching_notcompressed.py
4,350
3.875
4
# Runs using Python 3 import queue def nextNode(trie,currentNode,letter): # See how many letters are in the node's adjanency list nextNodes = len(trie[str(currentNode)][1]) # If there are none, then return None if nextNodes == 0: return None # If there are some, loop through and return if # the letter we are looking for is found: else: for i in range(nextNodes): nextNode = trie[str(currentNode)][1][i] if trie[str(nextNode)][0][-1] == letter: return trie[str(currentNode)][1][i] # If none of them match the letter, return None return None def suffixTrie(text): # Create empty dict to store trie tree # Make the "0" the root node trie, nodeCount = {}, 1 # Sub-list 0: letter corresponding to node; # Sub-list 1: next nodes numbers; # Sub-list 2: starting position within text of string trie["0"] = [[],[],[]] # Loop through all suffixs in text: T = len(text) for p in range(T): currentNode, pattern = 0, text[(0+p):T] # Go through each letter in each pattern for i in range(len(pattern)): letter = pattern[i] newNode = nextNode(trie,currentNode,letter) # If the letter exists in the adjacency list, then move onto the next one if newNode != None: currentNode = newNode # Otherwise, create a new node with the new letter # and append it to the current node's adacency list else: trie[str(currentNode)][1].append(nodeCount) trie[str(nodeCount)] = [[letter],[],[]] currentNode = nodeCount nodeCount += 1 # If we are on the last letter in the pattern, # then append it to the list of starting vertexs if i == (len(pattern)-1): trie[str(currentNode)][2].append(p) # Returnt the trie tree at the end return trie def findPatterns(trie,patterns): # Create a list to store pattern matches in text matches = [] # Check all patterns: for p in range(len(patterns)): # See if we can match every letter in the pattern currentNode = 0 pattern = patterns[p] matchFound = False for i in range(len(pattern)): letter = pattern[i] newNode = nextNode(trie,currentNode,letter) # If the letter exists in the adjacency list, # then move onto the next letter if newNode != None: currentNode = newNode # If all of the letters match, # then a match has been found if i == (len(pattern)-1): matchFound = True # Otherwise, break out of the loop else: i = len(pattern) # If a match was found, add all of the starting # vertexs in the text to the list if matchFound == True: matches = findStartingPoints(trie,currentNode,matches) return matches def findStartingPoints(trie,currentNode,matches): # Create a FIFO queue and make the current node the starting point myQueue = queue.Queue() myQueue.put(currentNode) # Go through all nodes in the trie tree, adding all of # the starting vertexs from the current node and beneath while myQueue.empty() != True: currentNode = myQueue.get() nextNodes = len(trie[str(currentNode)][1]) startingVertexs = len(trie[str(currentNode)][2]) if startingVertexs > 0: matches += trie[str(currentNode)][2] if nextNodes > 0: for j in range(nextNodes): newNode = trie[str(currentNode)][1][j] myQueue.put(newNode) return matches ################################ ####### START OF PROGRAM ####### ################################ text = str(input()) n = int(input()) # Record patterns patterns = [""] * n for i in range(n): patterns[i] = str(input()) # Make a suffex trie from the text trie = suffixTrie(text) # Find and print all of the matches of the pattern within the text matches = findPatterns(trie,patterns) if len(matches) == 0: print("") else: matches.sort() print(*matches)
bc94e388d71357616cc2934e80fabf8f20c9b77f
PythonScriptPlusPlus/olimp
/PythonScriptPlusPlus/questions/question6.py
247
3.671875
4
n = int(input()) if n <= 2: print('NONE') quit() if n == 5: print(0,1) quit() three = 0 four = n // 4 n = n % 4 if n == 2: four -= 1 three = 2 n = 0 elif n == 1: four -= 2 three = 3 elif n == 3: three = 1 print(str(three)+'\n'+str(four))
6246edd8b7431de8f9230077cd26fdaac8a14733
yunko006/CodeWars
/6-kyu/DeleteOccurence.py
269
3.8125
4
""" EXAMPLES: delete_nth ([1,1,1,1],2) # return [1,1] delete_nth ([20,37,20,21],1) # return [20,37,21] """ def delete_nth(order, max_e): simple = list() for i in order: if simple.count(i) < max_e: simple.append(i) return simple
78b8f148a5404d3522e7b9944f810095793c4411
aquibjamal/hackerrank_solutions
/write_a_function.py
323
4.25
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 21:41:35 2019 @author: aquib """ def is_leap(year): leap = False # Write your logic here if year%4==0: leap=True if year%100==0: leap=False if year%400==0: leap=True return leap
441dc9bb62c96f4f840e1e60ccfcf74029a94510
aquibjamal/hackerrank_solutions
/dealing_with_complex_nums.py
1,406
3.90625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 12 02:43:36 2019 @author: aquib """ class Complex(object): def __init__(self, real, imaginary): self.real=real self.imaginary=imaginary def __add__(self, no): return Complex(self.real+no.real, self.imaginary+no.imaginary) def __sub__(self, no): return Complex(self.real-no.real, self.imaginary-no.imaginary) def __mul__(self, no): return Complex(self.real*no.real-self.imaginary*no.imaginary, self.real*no.imaginary+self.imaginary*no.real) def __truediv__(self, no): try: return self.__mul__(Complex(no.real, -1*no.imaginary)).__mul__(Complex(1.0/(no.mod().real)**2,0)) except ZeroDivisionError as e: print(e) return None def mod(self): return Complex(pow(self.real**2+self.imaginary**2,0.5),0) def __str__(self): if self.imaginary == 0: result = "%.2f+0.00i" % (self.real) elif self.real == 0: if self.imaginary >= 0: result = "0.00+%.2fi" % (self.imaginary) else: result = "0.00-%.2fi" % (abs(self.imaginary)) elif self.imaginary > 0: result = "%.2f+%.2fi" % (self.real, self.imaginary) else: result = "%.2f-%.2fi" % (self.real, abs(self.imaginary)) return result
3334f3a28d9a1942ac493ca144715daf08b9571d
aquibjamal/hackerrank_solutions
/default_arguments.py
257
4.03125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 12 02:43:22 2019 @author: aquib """ def print_from_stream(n, stream=None): if stream is None: stream=EvenStream() for _ in range(n): print(stream.get_next())
e18c1a47c8a7ff364ae3659d931515ac8cda8665
aquibjamal/hackerrank_solutions
/set_difference.py
333
3.65625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 21:54:10 2019 @author: aquib """ # Enter your code here. Read input from STDIN. Print output to STDOUT num_e=int(input()) roll_e=set(map(int,input().split())) num_f=int(input()) roll_f=set(map(int,input().split())) diff=roll_e-roll_f print(len(diff),end='')
2e6fccc9f51c820442ab496cb419f28436f5318e
aquibjamal/hackerrank_solutions
/set_union.py
503
3.9375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 21:52:43 2019 @author: aquib """ # Enter your code here. Read input from STDIN. Print output to STDOUT #read in number of English subscribers num_e=int(input()) #read roll number of English subscribers roll_e=list(map(int, input().split())) #read in number of French subscribers num_f=int(input()) #read roll number of French subscribers roll_f=list(map(int,input().split())) total=roll_e+roll_f print(len(set(total)),end='')
52015723ceb6e40f5c5b88529992d7370acc4c7d
aquibjamal/hackerrank_solutions
/valid_credit_card_numbers.py
541
3.75
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 22:12:23 2019 @author: aquib """ # Enter your code here. Read input from STDIN. Print output to STDOUT import re valid_structure = r"[456]\d{3}(-?\d{4}){3}$" no_four_repeats = r"((\d)-?(?!(-?\2){3})){16}" filters=valid_structure, no_four_repeats output=[] num_cc=int(input()) for _ in range(num_cc): cc=input() if all(re.match(f, cc) for f in filters): output.append("Valid") else: output.append("Invalid") for o in output: print(o)
09e6cca73ea7ae36d09efa8eaf971f35013b2fc8
aquibjamal/hackerrank_solutions
/string_validators.py
357
3.671875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 22:23:14 2019 @author: aquib """ if __name__ == '__main__': s = input() print(any([c.isalnum() for c in s])) print(any([c.isalpha() for c in s])) print(any([c.isdigit() for c in s])) print(any([c.islower() for c in s])) print(any([c.isupper() for c in s]))
dbb4d38bd6e816c3ee40d996bb92da0bdbb6b23b
aquibjamal/hackerrank_solutions
/check_strict_superset.py
429
3.671875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 22:09:07 2019 @author: aquib """ # Enter your code here. Read input from STDIN. Print output to STDOUT setA=set(map(int,input().split())) cond=[] numB=int(input()) for _ in range(numB): setB=set(map(int,input().split())) cond1=all([b in setA for b in setB]) cond2=len(setA)>len(setB) cond.append(cond1 and cond2) print(all(cond),end='')
ad28c75360b09d06d4e7e52fe1267699b1c506dc
fpierin/mac5711
/heapSort.py
763
3.75
4
#!/usr/bin/env python # # Author: Felipe Pierin # Author: Viviane Bonadia from compare import cmp def heapsortCmp(c, A): def heapify(c, A): start = (len(A) -2) / 2 while (start >= 0): fixdown(c, A, start, len(A) - 1) start -= 1 def fixdown(c, A, start, end): root = start while root * 2 + 1 <= end: child = root * 2 + 1 if (child + 1 <= end and cmp(c, A[child], A[child + 1], (A[child] < A[child + 1]))): child += 1 if (child <= end and cmp(c, A[root], A[child], (A[root] < A[child]))): A[root], A[child] = A[child], A[root] root = child else: return heapify(c, A) end = len(A) - 1 while end > 0: A[end], A[0] = A[0], A[end] fixdown(c, A, 0, end -1) end -= 1 def heapsort(A): c = [] x = heapsortCmp(c, A) return c
e8cff56a53e29a80d047e999918b43deff019c3e
sauravsapkota/HackerRank
/Practice/Algorithms/Implementation/Beautiful Days at the Movies.py
713
4.15625
4
#!/bin/python3 import os # Python Program to Reverse a Number using While loop def reverse(num): rev = 0 while (num > 0): rem = num % 10 rev = (rev * 10) + rem num = num // 10 return rev # Complete the beautifulDays function below. def beautifulDays(i, j, k): count = 0 for num in range(i, j + 1): rev = reverse(num) if (abs(num - rev) % k) == 0: count += 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') ijk = input().split() i = int(ijk[0]) j = int(ijk[1]) k = int(ijk[2]) result = beautifulDays(i, j, k) fptr.write(str(result) + '\n') fptr.close()
1561be5165baa902c1a5bb0ef4d74be14e957a8c
sauravsapkota/HackerRank
/Practice/Algorithms/Implementation/Append and Delete.py
756
3.609375
4
#!/bin/python3 import os # Complete the appendAndDelete function below. def appendAndDelete(s, t, k): common_length = 0 for i, j in zip(s, t): if i == j: common_length += 1 else: break # CASE A if ((len(s) + len(t) - 2 * common_length) > k): return "No" # CASE B elif ((len(s) + len(t) - 2 * common_length) % 2 == k % 2): return "Yes" # CASE C elif ((len(s) + len(t) - k) < 0): return "Yes" # CASE D else: return "No" if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() t = input() k = int(input()) result = appendAndDelete(s, t, k) fptr.write(result + '\n') fptr.close()
96d4e5f4c03d746833b3934f36e0286394eb5c50
SHINE1607/coding
/problems/introductory/number_spiral.py
648
3.5625
4
def number_spiral(ind1, ind2): diagnol = 0 if ind1 == ind2: print(ind2*(ind2-1) + 1) return if ind1 < ind2: diagnol = ind2*(ind2-1) + 1 if ind2%2 == 0: print(diagnol - (ind2 - ind1)) else: print(diagnol + (ind2 - ind1)) elif ind1 > ind2: diagnol = ind1*(ind1-1) + 1 if ind1%2 == 0: print(diagnol + (ind1 - ind2)) else: print(diagnol - (ind1 - ind2)) n = int(input()) for i in range(n): index_arr = input().split() ind1 = int(index_arr[0]) ind2 = int(index_arr[1]) number_spiral(ind1, ind2)
41e077188841e53d91f0e0bb30facdf111be3646
SHINE1607/coding
/DSA/sorting/merge_sort.py
1,482
3.8125
4
import random def merge(left, right): global swaps left_pointer = 0 right_pointer = 0 res = [] if left == None: return right if right == None: return left while left_pointer < len(left) and right_pointer < len(right): if left[left_pointer] < right[right_pointer]: res.append(left[left_pointer]) left_pointer += 1 else: swaps += 1 res.append(right[right_pointer]) right_pointer += 1 if left_pointer < len(left): res += left[left_pointer:] # swaps += (len(left) - left_pointer) if right_pointer < len(right): res += right[right_pointer:] return res def merge_sort(arr): global swaps if len(arr) <= 1: return arr middle = len(arr)//2 left = merge_sort(arr[:middle]) right = merge_sort(arr[middle:]) return merge(left, right) arr = [] for i in range(20): arr.append(random.randint(1, 100)) swaps = 0 print(merge_sort(arr)) print("number ofswaps:", swaps) # def partition(arr): # pivot = arr[0] # i = 0 # j = len(arr) - 1 # while True: # while pivot < arr[i] and i < len(arr): # i += 1 # while pivot > arr[i] and j >= 0: # j -= 1 # if i < j: # arr[i], arr[j] = arr[j], arr[i] # else: # break # def quick_sort(arr):
26252a6dc20ee7b8e12fa8d91036123df4030b4e
SHINE1607/coding
/DSA/sorting/bubble_sort.py
1,298
3.90625
4
# possibly the themost brute force approoach we can think of # steps # > we select the last element as i # > we iterate j from to i - 1 # > replace the largest element with ith position # like that imoves from n -1 to 1 # 20 3 11 5 7 2 # first iteration for i # j i # 20 3 11 5 7 2 # j i # 3 20 11 5 7 2 # j i # 3 11 20 5 7 2 # j i # 3 11 5 20 7 2 # j i # 3 11 5 7 20 2 # ji # 3 11 5 7 2 20 # time complexity: O(n^2) import time def bubble_sort(arr): n = len(arr) for i in range(n - 1, 0, -1): for j in range(i): if arr[j] > arr[i]: arr[j], arr[i] = arr[i], arr[j] print(arr) arr = [int(x) for x in input().split()] arr1 = arr.copy() start = time.time() bubble_sort(arr1) end = time.time() print("time for bubble sort: ", end - start) def bubble_sort_linear(arr): start = time.time() n = len(arr) i = n - 1 t = 0 while i > 0: print(arr, i) for j in range(i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr [j] t = j i = t print(arr) start = time.time() bubble_sort_linear(arr) end = time.time() print("time for bubble sort linear: ", float(end - start))
7b8f09db39753b23760cdefc34da9cfa9e6ea729
SHINE1607/coding
/problems/introductory/repetitions.py
408
3.859375
4
def repetitions(string): longest = 1 curr_long = [string[0]] for i in range(1, len(string)): if string[i] == string[i - 1]: curr_long.append(string[i]) else: if len(curr_long) > longest: longest = len(curr_long) curr_long = [string[i]] print(max(len(curr_long), longest)) string = input() repetitions(string)
73e778301805644bbaa5f570f01498aa07c5cdf2
SHINE1607/coding
/problems/introductory/chessboard_and_queens.py
2,322
3.5
4
ans = 0 def queens_rec(q_no, taken, taken_clone, diff_arr, main_board): global ans # print(taken_clone) if q_no == 2: ans += 1 # print(taken , taken_clone) for i in range(8): # loop for the chess board for j in range(8): if main_board[i][j] != ".": continue else: if i in taken_clone[0]: break if j in taken_clone[1]: continue diff = i - j if diff in diff_arr or -1*diff in diff_arr: continue else: print(i, j) temp1 = taken_clone.copy() temp1[0].append(i) temp1[1].append(j) main_board[i][j] = "#" # if i == 1 and j==3 and q_no == 1: # print("shit") # print(temp2) queens_rec(q_no + 1, taken + [[i, j]], temp1, diff_arr + [i - j], main_board) temp1[0].append(j) temp1[1].append(i) if q_no == 1: print(temp1) queens_rec(q_no + 1, taken + [[j, i]], temp1, diff_arr + [j - i], main_board) main_board[i][j] = "." # board = [] # for i in range(8): # board.append(list(input())) fixed_pos = [[], []] # print(board) board = [['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '*', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '*', '*', '.'], ['.', '.', '.', '*', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.']] main_board = [["." for i in range(8)] for j in range(8)] main_board[0][0] = "#" queens_rec(1, [[0, 0]], [[0], [0]], [0], main_board) # fixing the first queeen # for i in range(8): # for j in range(8): # main_board = [["." for i in range(8)] for j in range(8)] # main_board[i][j] = "#" # queens_rec(1, [[i, j]], [[i], [j]], [i - j], main_board) # main_board = [["." for i in range(8)] for j in range(8)] # print(ans) print(ans)