blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
9222b9bcabb51b3adf0e7619ab871f5b0cb15ded
RVdeported/PyAlgo
/Lesson_3/task_3.py
706
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 18 18:16:45 2021 @author: Roman """ """ 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. """ import random as r nums = [r.randint(0,99) for n in range(10)] print(nums) low_num_i = 0 large_num_i = 0 for i, n in enumerate(nums): if (n < nums[low_num_i]): low_num_i = i if (n > nums[large_num_i]): large_num_i = i buff = nums[low_num_i] nums[low_num_i] = nums[large_num_i] nums[large_num_i] = buff print(nums) print(f'Changed {low_num_i} and {large_num_i} indexes with values {nums[low_num_i]} and {nums[large_num_i]}')
894ede2e98b4285cbd5ecf2a2cf6b512bafbbb55
awxinmin/bt4222-burpple-reviews
/utils/preprocessing.py
1,214
3.609375
4
import string from string import digits import pandas as pd def clean_review(review) : ''' Removes digits, empty strings, and new lines from phrases Parameters: review (string): review text Output: review (string): processed review texttext ''' # remove numbers remove_digits = str.maketrans('', '', digits) review = review.translate(remove_digits) # remove new lines review = review.replace('\n', ' ') return review def preprocessing_pipeline(review_file, preprocessed_csv): ''' Runs preprocessing on review_file ''' # read review_df review_df = pd.read_csv(review_file) # convert any np.nans to empty string review_df = review_df.fillna("") # keep original raw review_df["review_title_raw"] = review_df["review_title"] review_df["review_body_raw"] = review_df["review_body"] # clean review text review_df["review_title"] = review_df["review_title"].apply(lambda x: clean_review(x)) review_df["review_body"] = review_df["review_body"].apply(lambda x: clean_review(x)) # save preprocessed file review_df.to_csv(preprocessed_csv, index=False) print("PRE-PROCESSING COMPLETE")
e403728cb04da9fd353b4a68ea2546bb4d3a0689
gammarayburst999/Coursera
/Python_Functions_Files_Dictionaries/Week_04/Part_B.py
3,520
4.46875
4
#course_2_assessment_7 #Create a function called mult that has two parameters, the first is required and should be an integer, the second is an optional parameter that can either be a number or a string but whose default is 6. The function should return the first parameter multiplied by the second. default=6 def mult(s, s2=default): return int(s)*s2 #The following function, greeting, does not work. Please fix the code so that it runs without error. This only requires one change in the definition of the function. def greeting(name,greet="Hello ", excl="!"): s=greet + name + excl return s print(greeting("Bob")) print(greeting("")) print(greeting("Bob", excl="!!!")) #Below is a function, sum, that does not work. Change the function definition so the code works. The function should still have a required parameter, intx, and an optional parameter, intz with a defualt value of 5. def sum( intx,intz=5): return intz + intx #Write a function, test, that takes in three parameters: a required integer, an optional boolean whose default value is True, and an optional dictionary, called dict1, whose default value is {2:3, 4:5, 6:8}. If the boolean parameter is True, the function should test to see if the integer is a key in the dictionary. The value of that key should then be returned. If the boolean parameter is False, return the boolean value “False”. def test(s,d=bool(1),dict1={2:3,4:5,6:8}): if d==bool(0): return False if d==bool(1): for k in dict1.keys(): print(k) if k==s: return dict1[k] #Write a function called checkingIfIn that takes three parameters. The first is a required parameter, which should be a string. The second is an optional parameter called direction with a default value of True. The third is an optional parameter called d that has a default value of {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}. Write the function checkingIfIn so that when the second parameter is True, it checks to see if the first parameter is a key in the third parameter; if it is, return True, otherwise return False. #But if the second paramter is False, then the function should check to see if the first parameter is not a key of the third. If it’s not, the function should return True in this case, and if it is, it should return False. def checkingIfIn(s, direction=bool(1), d={'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): print(s) if direction==bool(1): for k in d.keys(): if k==s: return bool(1) if direction==bool(0): for m in d.keys(): if m!=s: return bool(1) else: return bool(0) return bool(0) #We have provided the function checkingIfIn such that if the first input parameter is in the third, dictionary, input parameter, then the function returns that value, and otherwise, it returns False. Follow the instructions in the active code window for specific variable assignmemts. c_false=bool(0) c_true=bool(1) param_check=8 fruit_ans=19 def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): if direction==bool(0): return c_false if direction==bool(1): for k in d.keys(): print(k) if k==s: fruit_ans=d[k] return fruit_ans
1d1778f45c1b3800d06fd029ff7f8a5a0d66102d
gammarayburst999/Coursera
/Python_Functions_Files_Dictionaries/Week_01/question_06.py
288
3.65625
4
#Create a list called emotions that contains the first word of every line in emotion_words.txt fname="emotion_words.txt" file1 = open(fname,"r") emotions=[] for x in file1: a=file1.readline() b=a.split() emotions.append(b[0]) #print(b) print(emotions) file1.close()
9993999b54b7b5d5fba00fdc6a30cc5622ed5b80
gammarayburst999/Coursera
/Python_Basics/Week_03/question_03.py
473
4
4
#Write code to count the number of strings in list items that have the character w in it. Assign that number to the variable acc_num. items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"] acc_num=0 str='w' for i in range(len(items)): print(items[i]) b=items[i] print(type(b)) #print(b[0]) #print(len(a[i])) val=b.find(str) if (val>=0): acc_num+=1 # acc_num+=1 #print(val) print(acc_num)
a5fcb149580f9c527a29e6f4062b9eb7c836d680
gammarayburst999/Coursera
/Python_Basics/Week_04/question_01.py
396
4
4
#Below are a set of scores that students have received in the past semester. Write code to determine how many are 90 or above and assign that result to the value a_scores scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100" print(type(scores)) a=scores.split() print(a) a_scores=0 for x in a: if (float(x)>=90): a_scores+=1 print(a_scores)
82fd32c3034f4dbdf66fad4254af4dfb33cd116a
Shamsullo/HackerRank_Python-
/ErrorsAndExceptions/Exceptions.py
251
3.625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT t = int(input()) for i in range(t): a,b = raw_input().split() try: print(int(a) // int(b)) except Exception as e: print ("Error Code: " + str(e))
02c7899045560a22e7a15eb610e261b9a4d8ce15
Petro1919/Recommender-System
/PetroMalkoun_Lab1_NonPerRecommender.py
6,329
3.859375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import csv import numpy as np import pandas as pd # In[2]: # I actually read the dataset as a csv and did not build it because I want it as a DF input_file=pd.read_csv("../../DataSets/movieratings.csv",header=0) # In[3]: #function that returns the n elements having the best mean (by descending order) def topMean(prefs,n=5): #calculating the mean and sorting them by descending order. #No need to drop NaN's scores=prefs.mean().sort_values(ascending=False) return scores[0:n] # In[4]: #calling the topMean function to test it topMean(input_file, 7) # In[ ]: # Output: # 318: Shawshank Redemption, The (1994) 3.600000 # 260: Star Wars: Episode IV - A New Hope (1977) 3.266667 # 541: Blade Runner (1982) 3.222222 # 1265: Groundhog Day (1993) 3.166667 # 593: Silence of the Lambs, The (1991) 3.062500 # 296: Pulp Fiction (1994) 3.000000 # 1210: Star Wars: Episode VI - Return of the Jedi (1983) 3.000000 # dtype: float64 # In[5]: #function that returns the n elements having the highest percentage of # ratings equals or larger than r (by descending ordered) def topPerc(prefs,r=3,n=5): #changing the shape (turning movie titles to 1 column) for usage purpose input_file_2=pd.melt(prefs, id_vars=["User"], var_name='title') #Keeping only the ratings that are equal or greater than R rank_r=input_file_2.loc[input_file_2['value'] >= r] #counting how many ratings are above the r value #had to group, count and sum the axis in order to get it because of the new DF format count_r=rank_r.groupby(['title','value']).count().unstack().sum(axis=1) #counting all ratings for all the columns in order to use it to compute the % #used the same command as in the previous one total_ratings=input_file_2.groupby(['title','value']).count().unstack().sum(axis=1) #dividing the total number of movies with a ratings higher than R with the total #number of rating for each movie scores=(count_r/total_ratings).sort_values(ascending=False) return scores[0:n] # In[6]: #calling the topPerc function to test it topPerc(input_file,4,8) # In[ ]: # Output: # 318: Shawshank Redemption, The (1994) 0.700000 # 260: Star Wars: Episode IV - A New Hope (1977) 0.533333 # 3578: Gladiator (2000) 0.500000 # 541: Blade Runner (1982) 0.444444 # 593: Silence of the Lambs, The (1991) 0.437500 # 2571: Matrix, The (1999) 0.416667 # 1265: Groundhog Day (1993) 0.416667 # 34: Babe (1995) 0.400000 # In[7]: #function that returns the n elements having the most number of ratings def topCount(prefs,n=5): #counting the number of ratings and sorting them by descending order. #No need to drop NaN's scores=prefs.count(numeric_only=True).sort_values(ascending=False) return scores[0:n] # In[8]: #calling the topCount function to test it topCount(input_file,n=8) # In[ ]: # Output: # 1: Toy Story (1995) 17 # 593: Silence of the Lambs, The (1991) 16 # 260: Star Wars: Episode IV - A New Hope (1977) 15 # 1210: Star Wars: Episode VI - Return of the Jedi (1983) 14 # 780: Independence Day (ID4) (1996) 13 # 2762: Sixth Sense, The (1999) 12 # 527: Schindler's List (1993) 12 # 2571: Matrix, The (1999) 12 # In[9]: #function that returns the top n other movie raters who also rated that movie #In percentages and ordered def topOccur(prefs,x='260: Star Wars: Episode IV - A New Hope (1977)',n=5): #dropping all the Users that did not rate the movie named x prefs_1 = prefs[prefs[x].notna()] #counting the number of ratings for x ratings_x=len(prefs_1[x]) #initializing two lists to use in the for loop #the number of non null ratings movie_ratings=[] #and the name/title of the movie movie_name=[] #for loop that goes from 1 because we don't want to take 'User' column into account for title in prefs.columns[1:input_file.shape[0]]: #checking if the column is different from x, because if so we don't want it if (title != x): #dropping all the Users that did not rate movie x from the dataset #so we only have the users that rated both movie 'x' and movie 'title' #so we're not changing prefs_1 when we move throught the loop! new_col=prefs_1[prefs_1[title].notna()] #appending movie_ratings with the number of non null raters movie_ratings.append(len(new_col[title])) #appending movie_name with the name of the specific movie movie_name.append(title) #creating a dataframe with the 2 lists that we computed new_pred=pd.DataFrame(movie_ratings,movie_name) #dividing each movie rating count by the number of ratings that movie x has #and hence getting the percentages new_pred['new']=new_pred.iloc[:,0]/ratings_x #sorting the computed percentages by descending order scores=new_pred['new'].sort_values(ascending=False) return scores[0:n] # In[10]: ##calling the topOccur function to test it topOccur(input_file,x='1198: Raiders of the Lost Ark (1981)',n=10) # In[ ]: # Output: # 593: Silence of the Lambs, The (1991) 0.818182 # 1: Toy Story (1995) 0.818182 # 2762: Sixth Sense, The (1999) 0.727273 # 527: Schindler's List (1993) 0.727273 # 1265: Groundhog Day (1993) 0.727273 # 3578: Gladiator (2000) 0.727273 # 1210: Star Wars: Episode VI - Return of the Jedi (1983) 0.636364 # 260: Star Wars: Episode IV - A New Hope (1977) 0.636364 # 2916: Total Recall (1990) 0.636364 # 780: Independence Day (ID4) (1996) 0.636364
039f33ba81c66c6fa00f76024bd8efb2ee29f6b0
SnippyValson/DailyCodingProblems
/Problem1.py
260
3.5
4
# Solved with hint. # Use set since look up in set is O(1) def two_sum(lst, k): seen = set() for num in lst: if k-num in seen: return True seen.add(num) return False result = two_sum([10, 15, 3, 7], 18) print(result)
911dc72e0e1496cde04762410f92100dea7fb942
frankma/Sandbox
/bet/binary_expression_tree.py
2,220
3.5
4
from typing import Dict class Expression(object): def __str__(self): raise NotImplemented def evaluate(self, env: Dict): raise NotImplemented pass class BinaryOperator(Expression): def __init__(self, left: Expression, right: Expression): self.left = left # type: Expression self.right = right # type: Expression pass class Plus(BinaryOperator): def __str__(self): return self.left.__str__() + ' + ' + self.right.__str__() def evaluate(self, env: Dict): return self.left.evaluate(env) + self.right.evaluate(env) class Minus(BinaryOperator): def __str__(self): return self.left.__str__() + ' - ' + self.right.__str__() def evaluate(self, env: Dict): return self.left.evaluate(env) - self.right.evaluate(env) class Times(BinaryOperator): def __str__(self): left_str = '(' + self.left.__str__() + ')' if isinstance(self.left, BinaryOperator) else self.left.__str__() right_str = '(' + self.right.__str__() + ')' if isinstance(self.right, BinaryOperator) else self.right.__str__() return left_str + ' * ' + right_str def evaluate(self, env: Dict): return self.left.evaluate(env) * self.right.evaluate(env) class Divide(BinaryOperator): def __str__(self): left_str = '(' + self.left.__str__() + ')' if isinstance(self.left, BinaryOperator) else self.left.__str__() right_str = '(' + self.right.__str__() + ')' if isinstance(self.right, BinaryOperator) else self.right.__str__() return left_str + ' / ' + right_str def evaluate(self, env: Dict): return self.left.evaluate(env) / self.right.evaluate(env) class UnaryOperator(Expression): def __init__(self, value: Expression): self.value = value pass class Operand(Expression): def __init__(self, value): self.value = value pass class Constant(Operand): def __str__(self): return self.value.__str__() def evaluate(self, env: Dict): return self.value class Variable(Operand): def __str__(self): return self.value.__str__() def evaluate(self, env: Dict): return env[self.value]
de23715eae61991a6a5ff2982e0c5fc9154a2a06
jrwalk/empath
/NLP/tf_idf.py
1,708
3.5
4
"""Calculators for TF-IDF score for word list, taken from pre-calculated frequency distribution from word_count. """ import nltk from nltk.text import TextCollection import pickle import glob import re def tf_idf(freqdist,corpus): """Calculates TF-IDF score for series of words, using distribution in freqdist for the TF score and the IDF score for each of those words from the corpus. ARGS: freqdist: nltk.probability.FreqDist object. contains frequency statistics for wordset. corpus: nltk.text.TextCollection object. TextCollection object (a series of nltk.text.Text objects) on which the IDF score for a word may be computed for an independent corpus. RETURNS: wordscores: dict. dict of TF-IDF scores for each word in freqdist. """ wordscores = {} N = freqdist.N() for word in freqdist.viewkeys(): tf = float(freqdist[word])/N idf = corpus.idf(word) wordscores[word] = tf*idf return wordscores def calc_tf_idfs(count): """loops through archived wordlists, loads each, calculates TF-IDF score for words contained, writes to dict and saves in pickle. """ corpus = TextCollection(nltk.corpus.webtext) filepath = '/home/jrwalk/python/empath/data/reddit/pickles/' files = glob.glob(filepath+'wordcount*%s.pkl' % count) filecount = len(files) for i,picklefile in enumerate(files): print "%i/%i processing %s" % (i+1,filecount,picklefile) with open(picklefile,'r') as readfile: freqdist = pickle.load(readfile)[2] wordscores = tf_idf(freqdist,corpus) druglim = re.findall('[a-z]+_[0-9]+|all|antidepressant',picklefile)[0] writepath = filepath+'tfidf_'+druglim+'.pkl' with open(writepath,'w') as writefile: pickle.dump(wordscores,writefile)
6b74fdc249485fb2fa6a0a755747346638da65de
jj131204/Excercises-python
/exercises/exercises8.py
379
3.75
4
lista = [] print('Ingrese números y para salir escriba "basta"') while True: valor = input('Ingrese valor: ') if valor == 'basta': break else: try: valor = int(valor) lista.append(valor) except: print('Dato inválido') exit() resultado = 0 for x in lista: resultado += x print(resultado)
abe3713a43c57d6564c638ceacbab2c2ce308a0a
meermm/test
/композиция.py
908
4.1875
4
''' По композиции один из классов состоит из одного или нескольких экземпляров других классов. Другими словами, один класс является контейнером, а другой класс - содержимым, и если вы удалите объект-контейнер, все его объекты содержимого также будут удалены. ''' class Salary: def __init__(self, pay): self.pay = pay def get_total(self): return (self.pay*12) class Human: def __init__(self, pay, bonus): self.pay = pay self.bonus = bonus self.obj_salary = Salary(self.pay) def annual_salary(self): return "Total: " + str(self.obj_salary.get_total() + self.bonus) obj_emp = Human(680, 500) print(obj_emp.annual_salary())
e4dcddcf7daf425a58c1dc132cc78e41a8e2ce56
2021-jgottschalk-projects/2020_Code_Advent
/AOC_Puzzle_10_v1.py
597
3.765625
4
# write data from file f = open("2020_advent_10_data.txt", "r") content = f.read() numbers = content.splitlines() f.close() # Change data to integers... integer_list = [] for item in numbers: item = int(item) integer_list.append(item) integer_list.sort() # print(integer_list) num_1s = 1 num_3s = 1 count = 0 for item in integer_list[1:]: ans = item - integer_list[count] count += 1 if ans == 1: num_1s += 1 elif ans == 3: num_3s += 1 print("1's: {} | 3's: {}".format(num_1s, num_3s)) print("Final Answer: ", num_3s * num_1s) # final answer is 2244
97dc5d4f60aea3eccef2bb82d1fbdcb6eba39bb1
2021-jgottschalk-projects/2020_Code_Advent
/AOC_Puzzle_07_v3.py
1,166
3.625
4
import re # Main routine goes here # write data from file f = open("2020_advent_07_data.txt", "r") content = f.read() whole_rules = content.split(". ") f.close() all_rules = [] for item in whole_rules: rules = re.split(r"contain | ,", item) all_rules.append(rules) total = 0 start_over = "" colors = ["shiny gold"] for color in colors: for item in all_rules: if start_over == "yes": continue for thing in item: print(thing) print() print("color list", colors) if start_over == "yes": continue color_result = re.search(color, thing) if color_result is not None: print("we have gold!!") total += 1 get_new = all_rules.index(item) new_color_raw = item[0] new_color_list = new_color_raw.split(" ") new_color = "{} {}".format(new_color_list[0], new_color_list[1]) if new_color not in colors: colors.append(new_color) print("total: ", total) # answer not 104 # it's not 6 either! # it's not 8
8fa01771b9f4a9281dc29576807ba7a3d5d7a4d9
Ayobamidele/python_projects
/dateofbirth.py
166
3.875
4
from datetime import datetime , timedelta birthyear = int(input("what is your birth: ")) current_time = datetime.now() x = current_time.year - birthyear print(str(x))
6aa1106207350a8504d987005b2fc9fcfdb308c9
Arsalan-Habib/python-projects
/random_guesser_V2.py
733
3.96875
4
import random def random_guesser(): tries=1 z=random.randint(1,10) x=int(input("\nEnter a number from 1 till 10\n")) win=False while win==False: if x==z: print("\nMubarak Ho! Tussi Jeet Gaye Janab\nIt took you only "+str(tries)+" tries.") check=int(input("\nPress 0 if you want to play again or press enter to exit.\n")) if check==0: win==True random_guesser() else: exit() elif x>z: x=int(input("\nThe number you entered was higher than the number i'm thinking of.\nPlease enter a number between 1 and 10 again.\n")) tries+=1 elif x<z: x=int(input("\nThe number you entered was lower than the number i'm thinking of.\nPlease enter a number between 1 and 10 again.\n")) tries+=1 random_guesser()
34e2f61b808885f8ef0f2a5073ba3ed90cc0d9fe
inwk6312winter2019/model-openbook2-NandanDadi96
/prog3.py
634
3.796875
4
file=open("Street_Centrelines.csv","r") def tuplelist(): for line in file: line=line.split(',') word=(line[2],line[4],line[6],line[7]) print(wo def histogram(): hist=dict() for line in file: line=line.split(',') word=(line[12]) if word not in hist: hist[word]=1 else: hist[word]+=1 print(hist) def uniquelist(): ulist=[] for line in file: line=line.split(',') word=line[11] if word not in ulist: ulist.append(word) print(ulist) def Strclass(): stclass=[] for line in file: line=line.split(',') word=line[10] if word not in stclass: stclass.append(word) print(stclass) Strclass()
5b3a03e924c9d6e15ba1e754c8df3e2c6f101f6c
weah79/Python
/EP4.py
4,874
3.71875
4
Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> friend = ['Prasong','Somsak','Loong'] >>> type(friend) <class 'list'> >>> print(friend[0]) Prasong >>> print(friend[1]) Somsak >>> print(friend[-1]) Loong >>> friend.append('Somchai') >>> print(friend[-1]) Somchai >>> pet = ('cat','dog') >>> type(pet) <class 'tuple'> >>> print(pet[0]) cat >>> friend.remove('Prasong') >>> animal = ('fish','lion','rabbit') >>> print(animal) ('fish', 'lion', 'rabbit') >>> frient.pop() Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> frient.pop() NameError: name 'frient' is not defined >>> friend.pop() 'Somchai' >>> print(friend) ['Somsak', 'Loong'] >>> friend.pop(0) 'Somsak' >>> friend.append('Robert') >>> friend.append('John') >>> friend.insert(0, 'Wanthong') >>> print(friend) ['Wanthong', 'Loong', 'Robert', 'John'] >>> friend.insert(1, 'Khun Chang') >>> print(friend) ['Wanthong', 'Khun Chang', 'Loong', 'Robert', 'John'] >>> friend[2] = 'Uncle' >>> print(friend) ['Wanthong', 'Khun Chang', 'Uncle', 'Robert', 'John'] >>> del friend[1] >>> print(friend) ['Wanthong', 'Uncle', 'Robert', 'John'] >>> for f in friend: print(f) Wanthong Uncle Robert John >>> for i,f in enumerate(friend): print(i,f) 0 Wanthong 1 Uncle 2 Robert 3 John >>> for i,f in enumerate(friend, start=1): print(i,f) 1 Wanthong 2 Uncle 3 Robert 4 John >>> len(friend) 4 >>> ord('ก') 3585 >>> ord('ฮ') 3630 >>> chr(3585) 'ก' >>> thaichar = [] >>> for i in range(3585,3630): thaichar.insert(char(i)) Traceback (most recent call last): File "<pyshell#42>", line 2, in <module> thaichar.insert(char(i)) NameError: name 'char' is not defined >>> for i in range(3585,3630): thaichar.insert(chr(i)) Traceback (most recent call last): File "<pyshell#44>", line 2, in <module> thaichar.insert(chr(i)) TypeError: insert expected 2 arguments, got 1 >>> for i in range(3585,3630): print(chr(i)) ก ข ฃ ค ฅ ฆ ง จ ฉ ช ซ ฌ ญ ฎ ฏ ฐ ฑ ฒ ณ ด ต ถ ท ธ น บ ป ผ ฝ พ ฟ ภ ม ย ร ฤ ล ฦ ว ศ ษ ส ห ฬ อ >>> for i,f in range(3585,3630): print(f, chr(i)) Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> for i,f in range(3585,3630): TypeError: cannot unpack non-iterable int object >>> for i,f in range(3585,3631): print(chr(i), f) Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> for i,f in range(3585,3631): TypeError: cannot unpack non-iterable int object >>> for i,f in range(3585,3631): print(chr(i)) Traceback (most recent call last): File "<pyshell#52>", line 1, in <module> for i,f in range(3585,3631): TypeError: cannot unpack non-iterable int object >>> for i in range(3585,3631): print(chr(i)) ก ข ฃ ค ฅ ฆ ง จ ฉ ช ซ ฌ ญ ฎ ฏ ฐ ฑ ฒ ณ ด ต ถ ท ธ น บ ป ผ ฝ พ ฟ ภ ม ย ร ฤ ล ฦ ว ศ ษ ส ห ฬ อ ฮ >>> for i in range(3585,3631): thaichar.append(chr(i)) >>> len(thaichar) 46 >>> thaichar.clear() >>> len(thaichar) 0 >>> for i in range(3585,3631): thaichar.append(chr(i)) >>> len(thaichar) 46 >>> print(thaichar) ['ก', 'ข', 'ฃ', 'ค', 'ฅ', 'ฆ', 'ง', 'จ', 'ฉ', 'ช', 'ซ', 'ฌ', 'ญ', 'ฎ', 'ฏ', 'ฐ', 'ฑ', 'ฒ', 'ณ', 'ด', 'ต', 'ถ', 'ท', 'ธ', 'น', 'บ', 'ป', 'ผ', 'ฝ', 'พ', 'ฟ', 'ภ', 'ม', 'ย', 'ร', 'ฤ', 'ล', 'ฦ', 'ว', 'ศ', 'ษ', 'ส', 'ห', 'ฬ', 'อ', 'ฮ'] >>> chr(3625) 'ษ' >>> chr(3622) 'ฦ' >>> chr(3620) 'ฤ' >>> thaichar.clear() >>> for i in range(3585,3631): if (i == 3622 || i == 3620) { continue; } thaichar.append(chr(i)) SyntaxError: invalid syntax >>> for i in range(3585,3631): if (i == 3622 or i == 3620) { continue; } thaichar.append(chr(i)) SyntaxError: invalid syntax >>> for i in range(3585,3631): if (i == 3622) { continue; } thaichar.append(chr(i)) SyntaxError: invalid syntax >>> for i in range(3585,3631): if i == 3620 or i == 3622: continue thaichar.append(chr(i)) SyntaxError: expected an indented block >>> for i in range(3585,3631): if i == 3620 or i == 3622: continue thaichar.append(chr(i)) >>> len(thaichar) 44 >>> print(thaichar) ['ก', 'ข', 'ฃ', 'ค', 'ฅ', 'ฆ', 'ง', 'จ', 'ฉ', 'ช', 'ซ', 'ฌ', 'ญ', 'ฎ', 'ฏ', 'ฐ', 'ฑ', 'ฒ', 'ณ', 'ด', 'ต', 'ถ', 'ท', 'ธ', 'น', 'บ', 'ป', 'ผ', 'ฝ', 'พ', 'ฟ', 'ภ', 'ม', 'ย', 'ร', 'ล', 'ว', 'ศ', 'ษ', 'ส', 'ห', 'ฬ', 'อ', 'ฮ'] >>> thaichar.index('ก') 0 >>> days = {'Mon':'จันทร์', 'Tue':'อังคาร', 'Wed':'พุธ'} >>> from datetime import datetime >>> dt = datetime.now().strftime('%a') >>> dt 'Fri' >>>
b6737c9c7caef4ce65543c8150519c03a54d9f32
bayan79/AlgoPythonLabs
/lab3.py
586
3.53125
4
from lab2 import fuzzy_compare_string ACCURACY = 0.7 # set of tuple(question: str, answer: str) answers = set() def get_answer(question: str): if question: if question == 'exit': exit() for quest, ans in answers: similarity = fuzzy_compare_string(question, quest) if similarity > ACCURACY: return f"уже спрашивали! {ans}" answer = "да" if hash(question) % 2 else "нет" answers.add((question, answer)) return answer while True: print(get_answer(input("Your question: ")))
5c55c69148cbd5e5c8528ee7383dbf65b9e664f6
MarcusJul/LeetCodewithPythonandCPP
/Python/Easy/69-Sqrt(x).py
936
3.671875
4
class Solution: def mySqrt(self, x: int) -> int: if x<=1: return x def binary(left, right): f = int((left+right)/2) if f*f>x: # larger than proper if (f-1)*(f-1)<=x: return f-1 else: return binary(left, f) elif f*f<x: if (f+1)*(f+1)>=x: return f else: return binary(f+1, right) else: return f return binary(0,x) ################################################# class Solution: def mySqrt(self, x: int) -> int: if x == 1 or x == 0: return x else: sf = 1 while(True): if sf*sf<=x: pass else: return sf-1 sf+=1
5f1e8aba3471c8bb3bf44663cea68d37894689d3
MarcusJul/LeetCodewithPythonandCPP
/Python/Medium/206-Reverse Linked List.py
773
3.890625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head==None: return None store = [] cur_node = head while(cur_node!=None): store.append(cur_node) cur_node = cur_node.next store = list(reversed(store)) head_node, cur_node = store[0],store[0] while(True): store = store[1:] if store==[]: break else: cur_node.next = store[0] cur_node = store[0] cur_node.next = None return head_node
52603fe5c21f1abd2b0e7bd0a666365eab1effbe
MarcusJul/LeetCodewithPythonandCPP
/Python/Easy/21-Merge Two Sorted Lists.py
1,051
3.78125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1, l2): head = [] if l1==None: pass else: cur_l = l1 while(True): head.append(cur_l.val) if cur_l.next==None: break else: cur_l = cur_l.next tail = [] if l2==None: pass else: cur_l = l2 while(True): tail.append(cur_l.val) if cur_l.next==None: break else: cur_l = cur_l.next mer = sorted(head+tail) if mer==[]: return None ret_l = ListNode(mer[0]) cur_l = ret_l for i in range(1,len(mer)): l = ListNode(mer[i]) cur_l.next = l cur_l = l return ret_l
07673c2513666dd0e04a85d37376e8bb48e6216d
AnnaRehorkova/pokusy
/nasobilka.py
121
3.671875
4
cislo = 0 for i in range(5): for i in range(5): print(cislo*i, end = " ") cislo += 1 print(end="\n")
e91f0477830d9570d288cb2e3383c48d93552927
siship/flask-tutorial-asr-school-2021
/app_test_1.py
1,601
4.09375
4
# Import Flask library from flask import Flask, request # Initialize the Flask application object, which contains data about the application and also methods, such as run(). app = Flask(__name__) # Flask will map the HTTP requests [GET or POST] to Python functions. # In this case, we’ve mapped one URL path (‘/’) to one function - home. # When we connect to the Flask server at http://127.0.0.1:6060/, Flask checks if there is a match between the path provided and a defined function. # If the were deployed on a server associated with the www.xxx.com domain name, then navigating to http://www.xxx.com on your browser would trigger home() to run on the server. # home, should be mapped to the path /, Flask runs the code in the home function and displays the returned result in the browser. # You can render HTML pages too. # The process of mapping URLs to functions is called routing. # GET requests : to send data from the application to the user # POST requests : to receive data from a user @app.route("/", methods=["GET", "POST"]) def home(): return "hello" @app.route("/about", methods=["GET", "POST"]) def about(): return "About me" @app.route('/<name>') def user(name): return '<h1>Hello, %s!</h1>' % name @app.route("/echo", methods=["GET"]) def echo(): to_echo = request.args.get("echo", "") response = "{}".format(to_echo) return response if __name__ == "__main__": # app.run(); is a method to run the app. If debug=True we can see the exact error, if the code is malformed. app.run(debug=True, port=6060) #http://127.0.0.1:6060/
36453e18ccf300af3c3f669007ac1e2d106284dd
jhb86253817/coursera-nlp
/week2/h1-p/part2.py
3,860
3.53125
4
#! /usr/bin/python __author__ = "Haibo Jin" import operator import part1 #part2, exercise of week2, from coursera course NLP lectured by Michael Collins #POS tagging with HMM model def pre_prob(): """calculate the probability for all the pairs of grams permutations""" prob_index = {} file_in = open('gene.counts2', 'rb') for line in file_in: line = line.split() if line[1] == '1-GRAM': prob_index[line[2]] = int(line[0]) elif line[1] == '2-GRAM': prob_index[(line[2], line[3])] = int(line[0]) elif line[1] == '3-GRAM': prob_index[(line[2], line[3], line[4])] = int(line[0]) file_in.close() return prob_index def trigram_prob(y1, y2, y3, prob_index): """calculate the probability of y3 given y1 and y2.""" return prob_index[(y1,y2,y3)] * 1.0 / prob_index[(y1,y2)] def tagger_set(index): """return the tagger set of a given index.""" s = ['O', 'I-GENE'] if int(index) == 0 or int(index) == -1: return ['*'] else: return s def sent_tagger(sent): """calculate the most possible sequence of tags given a sentence, using viterbi algorithm.""" #a table storing the maximum probability ending with specific two letters in specific position. pi_table = {} pi_table[(0, '*', '*')] = 1 #a table storing the best w which maximize the probability of trigram bp_table = {} #calculate the probability of trigram in advance prob_index = pre_prob() #calculate the emission probability in advance emission_index = part1.pre_emission() #finding most possible pair for certain positions with dynamic programming for k in range(1, len(sent)+1): for u in tagger_set(k-1): for v in tagger_set(k): for w in tagger_set(k-2): q = trigram_prob(w, u, v, prob_index) emission_o, emission_gene = part1.emission(sent[k-1], emission_index) if v == 'O': e = emission_o else: e = emission_gene if (k, u, v) not in pi_table.keys(): pi_table[(k, u, v)] = pi_table[(k-1, w, u)] * q * e bp_table[(k, u, v)] = w else: if pi_table[(k-1, w, u)] * q * e > pi_table[(k, u, v)]: pi_table[(k, u, v)] = pi_table[(k-1, w, u)] * q * e bp_table[(k, u, v)] = w #for the last two words, find the most possible taggers max_y = 0 for u in tagger_set(len(sent)-1): for v in tagger_set(len(sent)): r = pi_table[(len(sent), u, v)] * trigram_prob(u, v, 'STOP', prob_index) if r > max_y: max_y = r y = [u, v] #find the most possible taggers of the sentence based on bp_table for k in range(len(sent)-2, 0, -1): y_k = bp_table[(k+2, y[0], y[1])] y = [y_k] + y return zip(sent, y) def hmm_tagger(filename): """a HMM pos tagger which uses MLE to estimate parameters.""" file_in = open(filename, 'rb') file_out = open('gene_dev.p2.out', 'wb') sent = [] for word in file_in: word = word.strip() if not word: sent_tagged = sent_tagger(sent) for (w, t) in sent_tagged: file_out.write(str(w) + ' ' + str(t) + '\n') file_out.write('\n') sent = [] continue sent = sent + [word] file_in.close() file_out.close() if __name__ == '__main__': prob_index = pre_prob() print trigram_prob('O', 'O', 'STOP', prob_index) sent = "heart disease is the primary cause of morbidity and mortality among".split() y = sent_tagger(sent) print y hmm_tagger('gene.dev')
b58e1ff0fb886bfb2bd5287762fa262f3e1d3b5e
drkwons/study
/1.py
611
3.53125
4
class Cal(object): _history = [] def __init__(self, v1, v2): self.v1 = v1 self.v2 = v2 def add(self): result = self.v1+self.v2 Cal._history.append("add : %d+%d=%d" % (self.v1, self.v2, result)) return result @classmethod def history(cls): for rdhhdrh in Cal._history: print(rdhhdrh) class CalMultiply(Cal): def multiply(self): result = self.v1*self.v2 Cal._history.append("multiply : %d*%d=%d" % (self.v1, self.v2, result)) return result c1 = CalMultiply(10,10) print(c1.add()) Cal.history()
f4b6b9567c9029d08ab16e662169b963ce4d716b
jlindow/Python
/break.py
456
3.609375
4
# Break's a Caesar Shift Cipher import sys ciphertext = sys.argv[1] for k in range(0, 26): plaintextlist = [] for i in range(len(ciphertext)): char_num = ord(ciphertext[i]) - 65 #map to 0 - 25 shifted_num = (char_num - k) % 26 plainletter = chr(shifted_num + 65) plaintextlist.append(plainletter) plaintextstring = ''.join(plaintextlist) print("k = " + str(k) + " : " + plaintextstring)
2f8c743c539735310694c173f1fe79d52a4e8d05
Hohlenwerger/Python-Solution
/dbValidate/jsonUtils.py
796
3.578125
4
# Author: HohlenwergerMB # *Indented with tabs* # Import JSON methods import json def jsonReader(file): try: # Open JSON file with encoding UTF-8 to prevent problems with special chars with open(file, encoding="utf8") as data_file: return json.load(data_file) except: print("\nError: 'broken-database.json' file could not be open.") exit() def jsonWriter(data, newfile): try: # Create JSON file with encoding UTF-8 to prevent problems with special chars with open(newfile, 'w', encoding="utf8") as outfile: # dump indented json.dump(data, outfile, ensure_ascii = False, indent = 2) except: print("\nError: Could not save the repaired JSON file.") exit() # Beauty Print ^^ def jsonPrint(data): print(json.dumps(data,ensure_ascii = False, indent = 2))
645e8b3b2344d9792dae73cd90c2d91e1f86dce5
sichkar-valentyn/Variables_and_Branching_in_Python
/Variables_and_Branching_in_Python.py
1,575
3.59375
4
# File: Variables_and_Branching_in_Python.py # Description: Variables and Branching in Python # Environment: Spyder IDE in Anaconda environment # # MIT License # Copyright (c) 2018 Valentyn N Sichkar # github.com/sichkar-valentyn # # Reference to: # [1] Valentyn N Sichkar. Variables and Branching in Python // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Variables_and_Branching_in_Python (date of access: XX.XX.XXXX) """ Created on Sun Jan 07 00:05:15 2018 @author: Valentyn """ import os import psutil import sys print("This is a Great Python Program!") print("Hello there, programmer!") name = input("What is your name? ") print(name, ", Welcome!") answer = input("Let's work? (Y/N)") if answer == 'Y': print("Great choice!") # type "pass" for the empty construction print("I can do for you:") print("[1] - show list of files and folders in current directory") print("[2] - show information about System") print("[3] - show list of running tasks in the System") todo = int(input("Make your choice: ")) if todo == 1: print(os.listdir()) elif todo == 2: print("Current directory: ", os.getcwd()) print("Number of CPU: ", os.cpu_count()) print("Operation System: ", sys.platform) print("File system encoding: ", sys.getfilesystemencoding()) elif todo == 3: print("List of current running PIDs: ", psutil.pids()) else: pass # for the empty construction elif answer == 'N': print("Good by, see you next time!") else: print("Unknown input, try again")
c9195fab307d8291d6ea8b9e7d7109d91d59d6e3
jeantorresa190899/TrabajoFinal
/Desarrollo.py
8,779
3.890625
4
import os, sys os.system("cls") import random # Inicio de la Aplicación print("********* Hola, bienvenido a esta nueva plataforma de aprendizaje.***********") nombre = str(input("¿Cuál es tu nombre? -----------> ")) print("Hola", nombre) print("Este programa consiste en responder 20 preguntas de cultura" + " general, \nlas cuales te ayudarán a expandir tus conocimientos.") print("\n") print("----------------------------------------------------------------") print("| ¡COMENZEMOS! |") print("----------------------------------------------------------------") class Question: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer question_prompts = [ "¿Cuál es un tipo de sabor primario?\na)Quemado\nb)Rostizado\nc)Umami\nd)Sabroso\n\n", "¿Cuál es el lugar más frío de la tierra??\na)Antartida\nb)Suecia\nc)Groenlandia\nd)Islandia\n\n", "¿Quién escribió La Odisea?\na)Sócrates\nb)Pitágoras\nc)Homero\nd)Aristóteles\n\n", "¿Cuántos Estados tiene integrados Estados Unidos? \na)32\nb)49\nc)50\nd)55\n\n", "¿En qué continente está San Marino?\na)América del Norte\nb)América del Sur\nc)Europa\nd)Asia\n\n", "¿Quién inventó el primer avión?\na)Los hermanos Wright\nb)Los hermanos Warner\nc)Los hermanos Wachowski\nd)Los hermanos Lumiére\n\n", "¿Quién escribió Cien años de soledad?\na)Gabriel García Márquez\nb)Alfredo Bryce Echenique\nc)Cesar Vallejo\nd)Ricardo Úceda\n\n", "¿En qué deporte destacaba Toni Elías?\na)Motociclismo\nb)Fútbol\nc)Formula 1\nd)Voley\n\n", "¿Qué deporte practicaba Michael Jordan?\na)Baseball\nb)Football\nc)Basketball\nd)Golf\n\n", "¿Dónde se inventó el ping-pong?\na)Estados Unidos de América\nb)Inglaterra\nc)Canadá\nd)Irlanda\n\n", "¿De qué estilo arquitectónico es la Catedral de Notre Dame en París?\na)Rómanico\nb)Barroco\nc)Neoclásico\nd)Gótico\n\n", "¿Quién va a la cárcel?\na)Imputado\nb)Acusado\nc)Condenado\nd)Testigo\n\n", "¿A qué país pertenece la ciudad de Varsovia?\na)Polonia\nb)Austria\nc)Rusia\nd)Bielorusia\n\n", "¿Cuál es el metal más caro del mundo?\na)Oro\nb)Plata\nc)Rodio\nd)Aluminio\n\n", "¿Cuál es la nacionalidad de Pablo Neruda?\na)Chilena\nb)Boliviana\nc)Argentina\nd)Uruguaya\n\n", "¿Cuál es el país más poblado del mundo?\na)Rusia\nb)China\nc)EE.UU\nd)Canadá\n\n", "¿Quién fue el líder de los nazis durante la Segunda Guerra Mundial? \na)Mussolini \nb)Stalin \nc)Hitler \nd)F.Roosevelt\n\n", "¿En qué país se encuentra la torre de Pisa? \na)Italia \nb)Francia \nc)España \nd)Alemania \n\n", "¿Cuantos huesos tiene el cuerpo humano? \na)214 \nb)206 \nc)216 \nd)202 \n\n", "¿Cual de los siguientes animales es un marsupial? \na)Gato \nb)Koala \nc)Chimpancé \nd)Conejo\n\n", "Si una década tiene 10 años.¿Cuantos años tiene un lustro? \na)20 \nb)10 \nc)5 \nd)15\n\n", "¿En qué año llegó el primer hombre a la Luna?\na)1969 \nb)1979 \nc)1980 \nd)1976\n\n", "¿En que continente se encuentra Haití?\na)Africa \nb)Europa \nc)America \nd)Oceania\n\n", "¿Quién pintó “la última cena”?\na)Raffaello Sanzio de Urbino \nb)Miguel Angel \nc)Alessandro di Mariano \nd)Leonardo D'Vinci\n\n", "¿Cómo se llama el himno nacional de Francia?\na)Das Lied der Deutschen \nb)The Star-Spangled Banner\nc)Marsellesa \nd)Il Canto degli Italiani\n\n", "¿Qué año llegó Cristóbal Colón a América?\na)1512 \nb)1498 \nc)1492 \nd)1495\n\n", "¿Cuál es el río más largo del mundo?\na)Yangtsé \nb)Nilo \nc)Amazonas \nd)Misisipi\n\n", "¿Cuantos corazones tienen los pulpos?\na)2 \nb)1 \nc)3 \nd)5\n\n", "¿Cuál es el libro sagrado del Islam?\na)Biblia \nb)Coran \nc)Credo\nd)Documento de Damasco\n\n", "¿En qué país se ubica la Casa Rosada?\na)EE.UU \nb)Uruguay \nc)Argentina \nd)Chile\n\n", "¿Cuantas fueron las principales cruzadas(1095 - 1291)?\na)3 \nb)6 \nc)8 \nd)5\n\n", "¿Quién fue el primer presidente del Perú?\na)Don José de San Martín \nb)José Mariano de la Riva Agüero y Sánchez Boquete \nc)José Bernardo de Torre Tagle \nd)José de la Mar\n\n", "¿Cómo se la nombró a la primera computadora programable ?\na)Maquina de turing \nb)Z1 \nc)Eniac \nd)Osborne\n\n", "¿Cuál ha sido la guerra más sangrienta de la historia?\na)1ra guerra mundial \nb)2da guerra mubdial \nc)Guerra de vietnam \nd)Guerra civil española\n\n", "¿Cuántas patas tiene una abeja?\na)6 \nb)10 \nc)4 \nd)8\n\n", "¿Cuantos años tiene un lustro ?\na)5 \nb)10 \nc)25 \nd)50\n\n", "¿Con qué otro nombre se denomina al hexaedro?\na)cono \nb)piramide \nc)esfera \nd)cubo\n\n", "La capital de Irlanda es:\na)Budapest \nb)Berlín \nc)Atenas \nd)Dúblin\n\n", "Si el radio de un círculo mide 5 centímetros, ¿cuánto mide el diámetro?\na)5 centímetros \nb)20 centímetros \nc)10 centímetros \nd)2 centímetros\n\n", "¿Cuál es el planeta de mayor tamaño del Sistema Solar?\na)Mercurio \nb)Marte \nc)Júpiter \nd)Tierra\n\n", "Una carga positiva y otra negativa:\na)No pasa nada \nb)Se atraen \nc)Intercambian sus polos \nd)Se repelen\n\n", "Colón se embarcó en su viaje a América en tres embarcaciones, ¿Cuál no fue una de ellas?\na)Pinta \nb)Santa María \nc)La Niña \nd)Santa Cristina\n\n", "La unidad de volumen en el Sistema Internacional es:\na)Amperio por metro \nb)Amperio por metro cuadrado \nc)Metro cuadrado \nd)Metro cúbico\n\n", "La temperatura a la cual la materia pasa de estado líquido a estado gaseoso se denomina:\na)Ecuación de estado \nb)Punto de ebullición \nc)Transición de fase \nd)Punto de fusión\n\n", "¿Cuántas vueltas da el segundero en una vuelta completa en un reloj de doce horas?\na)720 \nb)800 \nc)420 \nd)360\n\n", ] questions = [ Question(question_prompts[0], "c"), Question(question_prompts[1], "a"), Question(question_prompts[2], "c"), Question(question_prompts[3], "c"), Question(question_prompts[4], "c"), Question(question_prompts[5], "a"), Question(question_prompts[6], "a"), Question(question_prompts[7], "a"), Question(question_prompts[8], "c"), Question(question_prompts[9], "b"), Question(question_prompts[10], "d"), Question(question_prompts[11], "c"), Question(question_prompts[12], "a"), Question(question_prompts[13], "c"), Question(question_prompts[14], "a"), Question(question_prompts[15], "b"), Question(question_prompts[16], "c"), Question(question_prompts[17], "a"), Question(question_prompts[18], "b"), Question(question_prompts[19], "b"), Question(question_prompts[20], "c"), Question(question_prompts[21], "b"), Question(question_prompts[22], "c"), Question(question_prompts[23], "d"), Question(question_prompts[24], "c"), Question(question_prompts[25], "c"), Question(question_prompts[26], "c"), Question(question_prompts[27], "c"), Question(question_prompts[28], "b"), Question(question_prompts[29], "c"), Question(question_prompts[30], "c"), Question(question_prompts[31], "b"), Question(question_prompts[32], "b"), Question(question_prompts[33], "b"), Question(question_prompts[34], "a"), Question(question_prompts[35], "a"), Question(question_prompts[36], "d"), Question(question_prompts[37], "d"), Question(question_prompts[38], "c"), Question(question_prompts[39], "c"), Question(question_prompts[40], "b"), Question(question_prompts[41], "d"), Question(question_prompts[42], "d"), Question(question_prompts[43], "b"), Question(question_prompts[44], "a") ] #Proceso def run_quiz(questions): score = 0 i = 0 random.shuffle(questions) questions = random.sample(questions, k=20) for question in questions: print("................") print("Pregunta:", i+1) print(question.prompt) from itertools import chain, repeat answer = {'a', 'b', 'c', 'd'} prompts = chain(["Ingrese una letra del listado: "], repeat("Ingresa una letra del listado: ")) replies = map(input, prompts) valid_response = next(filter(answer.__contains__, replies)) print(valid_response) i +=1 if valid_response == question.answer: score += 1 print("Tienes", score, "de", len(questions)) if score <= 5: mensaje = "- Vuelve a intentar" elif score <=10: mensaje = "- Not bad!" elif score <=15: mensaje = "- Buen intento!" else: mensaje = "- Buen trabajo!" print(mensaje) run_quiz(questions)
11a05408872bf65359cdc304c6a331669244ee58
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_3/Week3_8.py
125
3.734375
4
sum = 0 for i in range (100,5001): if(i%2==0): sum+=i print("Sum of even number between 100 to 5000 is {}".format(sum))
916526953bd5aa3d1a35cbe609fc38b3e1498290
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_4/Assignment1/prac5.py
218
4.03125
4
string = input("Enter string") digit=0 letter=0 for i in string: if i.isalpha(): letter=letter=1 elif i.isdigit(): digit=digit+1 else: pass print("Letters", letter) print("Digits", digit)
3ac1299605142a62c6c7c9e4df09020fccb95c75
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_4/Assignment2/4.py
731
4.15625
4
from collections import Counter list1 = [1, 2, 3, 2, 2, 2, 5, 6] counter = 0 num = list1[0] for i in list1: current = list1.count(i) if(current>counter): counter=current num=i print("Most common element in list: ",num) print("Count of element in list: ", counter) tuples = ("apple", 2, 3,"apple","apple", "apple", 5, 6) counter_t = 0 num_t = tuples[0] for j in tuples: current_t = tuples.count(j) if(current_t>counter_t): counter_t=current_t num_t=j print("Most common element in tuple: ",num_t) print("Count of element in tuple: ", counter_t) dict1={ "one": 1,"two": 2, "two2": 2, "two3": 2, "three": 4, "three3": 4 } res = Counter(dict1.values()) print("The frequency dictionary : " + str(dict(res)))
e1b1de73799d1d44e298b41c3f423c75cb3b4257
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_1/Practical6.py
411
4.03125
4
def countNotes(amount): notes = [2000, 500, 200, 100, 50, 20, 10, 5, 1] notes_counter = [0, 0, 0, 0, 0, 0, 0, 0, 0] print("Note count: ") for i,j in zip(notes, notes_counter): if(amount>=i): j = amount//i amount = amount - j*i print(i, "->", j) amt = int(input("Enter amount to calculate minimum number of currency notes required: ")) countNotes(amt)
59e4a6bab2feb777b3bec0b1ece5c6bccf1c2433
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_1/Practical7.py
501
4.21875
4
choice = int(input("To covert rupees to dollar- enter 1 and to convert dollar to rupees - enter 2 ")) if(choice==1): amt_rupees = float(input("Enter amount in rupees: ")) cnv_dollar = amt_rupees/70 print(amt_rupees, "rupees is equal to ", cnv_dollar, "dollar/s") elif(choice==2): amt_dollar = float(input("Enter amount in dollar: ")) cnv_rupees = amt_dollar*70 print(amt_dollar, "dollar/s is equal to ", cnv_rupees, "rupees") else: print("You have entered invalid choice")
2d3d24ee9b830952d42454b324fde4225ef0aa65
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_14/Exercise5.py
280
4.03125
4
import random num = random.randint(1,9) user_num = int(input("Enter a number: ")) if user_num<num: print("Your guess is too low") elif user_num>num: print("Your guess is too high") elif user_num==num: print("Your guess is exactly right") print("The number is: ",num)
341402e6ff696fcac7b2d8c49c7023d51d8da541
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_4/Assignment2/Dictionary/a.py
126
3.578125
4
studentdict={ "name":"Nidhi", "surname":"Gajjar", "id":"18IT033" } if "id" in studentdict: print("Yes, 'id' is key")
83b109d253ef300b87470547a79dfd0e0791a181
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_4/Assignment1/prac2.py
176
3.875
4
for num in range (1,101): if(num%6==0 and num%4==0): print("CHARUSAT_IT") elif(num%6==0): print("CHARUSAT") elif(num%4==0): print("IT") else: print(num)
1c1ce2d401051d1c3018287f316fbbab98a5b53f
generative-adversarial-networks/introduction-neural-networks
/train_two_layer_neural_network.py
6,340
4.40625
4
""" Author: Jamal Toutouh (toutouh@mit.edu) train-two-layer-neural-network.py contains the code to create and train a basic neural network with: - two inputs: x1, and x2 - a hidden layer with two neurons: h1 and h2 - an output layer with a neuron: o1 """ import numpy as np from neuron import ActivationFunctions from networks_loss import NetoworksLoss import matplotlib.pyplot as plt def show_output(loss): y = np.array(loss) fig, ax = plt.subplots() ax.plot(y) ax.set(xlabel='training epochs (x10)', ylabel='loss', title='Loss evolution') ax.grid() plt.show() class TrainedNeuralNetwork: """It encapsulates a two layer neural neuron with: - 2 inputs - a hidden layer with 2 neurons (h1, h2) - an output layer with 1 neuron (o1) Note that the code presented below is made for teaching proposes. I have not taken int account efficiency. """ def __init__(self, activation, activation_derivative, loss, learn_rate): self.activation = activation self.activation_derivative = activation_derivative self.loss = loss self.learn_rate = learn_rate # Weights self.w1 = np.random.normal() self.w2 = np.random.normal() self.w3 = np.random.normal() self.w4 = np.random.normal() self.w5 = np.random.normal() self.w6 = np.random.normal() # Biases self.b1 = np.random.normal() self.b2 = np.random.normal() self.b3 = np.random.normal() def feedforward(self, x): """ It computes feedforward of the network and also returns intermediate results used for different computations. :param x: numpy array of two elements :return: """ # h1 = self.activation(self.w1 * x[0] + self.w2 * x[1] + self.b1) # h2 = self.activation(self.w3 * x[0] + self.w4 * x[1] + self.b2) # o1 = self.activation(self.w5 * h1 + self.w6 * h2 + self.b3) sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.b1 h1 = self.activation(sum_h1)['result'] sum_h2 = self.w3 * x[0] + self.w4 * x[1] + self.b2 h2 = self.activation(sum_h2)['result'] sum_o1 = self.w5 * h1 + self.w6 * h2 + self.b3 o1 = self.activation(sum_o1)['result'] return o1, sum_h1, sum_h2, sum_o1, h1, h2 def train(self, data, all_y_trues, epochs=1000): """ It performs the training of the network :param data: a numppy array of nx2 elements where n is the number of samples in training dataset. :param all_y_trues: labels (expected output) of the training data. :param epochs: number of training epochs. :return: """ show = True loss_to_show = [] for epoch in range(epochs): for x, y_true in zip(data, all_y_trues): # First: Compute the output of the network (o1 = y_pred) and the partial sums and activations o1, sum_h1, sum_h2, sum_o1, h1, h2 = self.feedforward(x) y_pred = o1 # Second: - Compute partial derivatives. # p_L_p_ypred represents the partial derivative of L over derivative y_pred p_L_p_ypred = -2 * (y_true - y_pred) # - Output neuron (o1) p_ypred_p_w5 = h1 * self.activation_derivative(sum_o1) p_ypred_p_w6 = h2 * self.activation_derivative(sum_o1) p_ypred_p_b3 = self.activation_derivative(sum_o1) p_ypred_p_h1 = self.w5 * self.activation_derivative(sum_o1) p_ypred_p_h2 = self.w6 * self.activation_derivative(sum_o1) # - Hidden layer neuron (h1) p_h1_p_w1 = x[0] * self.activation_derivative(sum_h1) p_h1_p_w2 = x[1] * self.activation_derivative(sum_h1) p_h1_p_b1 = self.activation_derivative(sum_h1) # - Hidden layer neuron (h2) p_h2_p_w3 = x[0] * self.activation_derivative(sum_h2) p_h2_p_w4 = x[1] * self.activation_derivative(sum_h2) p_h2_p_b2 = self.activation_derivative(sum_h2) # Third: Update weights and biases # - Hidden layer neuron (h1) self.w1 -= self.learn_rate * p_L_p_ypred * p_ypred_p_h1 * p_h1_p_w1 self.w2 -= self.learn_rate * p_L_p_ypred * p_ypred_p_h1 * p_h1_p_w2 self.b1 -= self.learn_rate * p_L_p_ypred * p_ypred_p_h1 * p_h1_p_b1 # - Hidden layer neuron (h2) self.w3 -= self.learn_rate * p_L_p_ypred * p_ypred_p_h2 * p_h2_p_w3 self.w4 -= self.learn_rate * p_L_p_ypred * p_ypred_p_h2 * p_h2_p_w4 self.b2 -= self.learn_rate * p_L_p_ypred * p_ypred_p_h2 * p_h2_p_b2 # - Output neuron (o1) self.w5 -= self.learn_rate * p_L_p_ypred * p_ypred_p_w5 self.w6 -= self.learn_rate * p_L_p_ypred * p_ypred_p_w6 self.b3 -= self.learn_rate * p_L_p_ypred * p_ypred_p_b3 # For logging purposes if epoch % 10 == 0: y_preds = [self.feedforward(dat)[0] for dat in data] loss = self.loss(all_y_trues, y_preds) loss_to_show.append(loss) print("Epoch %d loss: %.3f" % (epoch, loss)) if show: show_output(loss_to_show) # Run example of the powerpoint # Define dataset input = np.array([ [-9, 0], # Michael (12 hours/week, 6 papers) [11, -2], # Shash (32 hours/week, 4 papers) [-10, -3], # Hannah (11 hours/week, 3 papers) [8, 5], # Lisa (29 hours/week, 11 papers) ]) real_y = np.array([ 0, # Michael 1, # Shash 0, # Hannah 1, # Lisa ]) activation = ActivationFunctions().sigmoid activation_derivative = ActivationFunctions.derivative_sigmoid loss = NetoworksLoss.mse_loss learning_rate = 0.1 # Train our neural network network = TrainedNeuralNetwork(activation, activation_derivative, loss, learning_rate) network.train(input, real_y) # Make some predictions jamal = np.array([-7, -3]) # 14 hours/week, 6 papers mina = np.array([10, -6]) # 31 hours/week, 0 papers print("Jamal: %.3f" % network.feedforward(jamal)[0]) # No Data Scientist 0.04 print("Mina: %.3f" % network.feedforward(mina)[0]) # Data Scientist 0.945
1ca2340361d2623294f76a41dc5181d62b5d17c9
melandres8/holbertonschool-higher_level_programming
/0x06-python-classes/3-square.py
733
4.375
4
#!/usr/bin/python3 """Square class""" class Square(): """Validating if size is an instance and if is greater and equal to 0 Attributes: attr1 (int): size is a main attr of a square """ def __init__(self, size=0): """isinstance function checks if the object is an instance or subclass of the second argument Args: size (int): size of my square """ if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") self.__size = size """Returning the Area of a square""" def area(self): return int(self.__size) * int(self.__size)
5f353edcbb4e50cf26f5b1ac3719426d694b0c59
melandres8/holbertonschool-higher_level_programming
/0x0B-python-input_output/14-pascal_triangle.py
470
3.921875
4
#!/usr/bin/python3 """ Pascal module """ def pascal_triangle(n): """ Returning a list of lists of integer representing the pascal's triangle of n """ my_list = [] if n <= 0: return my_list for item1 in range(1, n + 1): number = 1 row = [] for item2 in range(1, item1 + 1): row += [number] number = number * (item1 - item2) // item2 my_list += [row] return my_list
213fba542e50c8878410245e7f63ee82d4747ae8
melandres8/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
136
3.703125
4
#!/usr/bin/python3 def uniq_add(my_list=[]): new = set(my_list) add = 0 for item in new: add += item return add
648d3e6898443d625148a4fa7b6a4d1836f940a8
melandres8/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/101-remove_char_at.py
290
3.828125
4
#!/usr/bin/python3 def listToString(lista): str1 = "" for item in lista: str1 += item return str1 def remove_char_at(str, n): lista1 = [] for index, char in enumerate(str): if index != n: lista1.append(char) return listToString(lista1)
44c5024a42eaf96442266aadb0f4b4a948a2af37
melandres8/holbertonschool-higher_level_programming
/0x02-python-import_modules/3-infinite_add.py
267
3.671875
4
#!/usr/bin/python3 from sys import argv if __name__ == '__main__': ind = 0 argv.remove(argv[0]) if len(argv) is 0: print("{:d}".format(len(argv))) else: for index in argv: ind += int(index) print("{}".format(ind))
9a956a51c89fe66441040b2db5ab0b5dd3bf53fe
melandres8/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
758
4.1875
4
#!/usr/bin/python3 """ Handling new lines, some special characters and tabs function. """ def text_indentation(text): """ Print a text with two new line at the end after each of these characters '.'':''?' Args: text: (string) Given text Raises: TypeError: "text must be a string" """ if (not isinstance(text, str)): raise TypeError("text must be a string") string = "" for i in text: if i == '\n': pass else: string += i if i in '.:?': string = string.strip(" ") print(string, end="") print("\n") string = "" string = string.strip(" ") print(string, end="")
9923d3414c6e87199ffca081c646b80967cac9d8
melandres8/holbertonschool-higher_level_programming
/0x0A-python-inheritance/10-square.py
445
4.1875
4
#!/usr/bin/python3 """ Applying inheritance and super() method """ Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """ Defining constructor """ def __init__(self, size): """Constructor method Args: size: square size """ self.integer_validator("size", size) super().__init__(size, size) # call init of rectangle class self.__size = size
aae62d6b9cace68fca666fce4a8a4ee290f67c6c
LookerKy/Python_start
/src/section07-2.py
1,858
3.734375
4
# Section07-2 # 파이썬 클래스 상세 이해 # 상속 다중 상속 # 예제 1 # 상속 기본 # 슈퍼클래스 및 서브클래스 -> 모든 속성 및 메소드를 사용 가능 # 상속을 통해 코딩을하면 재사용성, 공통 속성 제거, # 라면 -> 속성(종류, 회사, 맛, 면 종류 ,이름) : 슈퍼클래스 (공통적인부분) # 예제 1 class Car: """Parent Class""" def __init__(self, tp, color): self.type = tp self.color = color def show(self): return 'Car Class "show Method"' class BmwCar(Car): """Sub class""" def __init__(self, car_name, tp, color): super().__init__(tp, color) self.car_name = car_name def show_model(self) -> None: return "your car Name : %s" % self.car_name class BenzCar(Car): """Sub class""" def __init__(self, car_name, tp, color): super().__init__(tp, color) self.car_name = car_name def show_model(self) -> None: return "your car Name : %s" % self.car_name def show(self): print(super().show()) return "Car Info : %s %s %s" % (self.car_name, self.type, self.color) model1 = BmwCar('520d', 'sedan', 'red') print(model1.color) # super print(model1.type) # super print(model1.car_name) # Sub print(model1.show()) # Super print(model1.show_model()) print(model1.__dict__) # Method Overriding model2 = BenzCar("220d", 'suv', 'black') print(model2.show()) # Parend Method call model3 = BenzCar("350s", "sedan", "silver") print(model3.show()) # 상속(Inheritance)의 depth가 깊을때 확인하는 방법 print(BmwCar.mro()) print(BenzCar.mro()) # 예제 2 # 다중 상속 class X: pass class Y: pass class Z: pass class A(X, Y): pass class B(Y, Z): pass class M(B, A, Z): pass print(M.mro()) print(A.mro())
c2581e430f7eb8be0524bc38a01ac904ae043ab3
komararyna/homework_2
/task5.py
86
3.8125
4
x=int(input('insert number of 3 digits:')) a=x%10 b=x%100 //10 c=x//100 print(a+b+c)
599dbcf884a3f5fa0ac02c6af742577cff6c33fe
Rillell/2_Grade_Project
/Python/2주차/0407.py
468
3.6875
4
num10 = 0 sel = int(input("입력진수 : ")) num = input("값 입력 : ") if sel == 16 : num10 = int(num, 16) if sel == 10 : num10 = int(num, 10) if sel == 8 : num10 = int(num, 8) if sel == 2 : num10 = int(num, 2) if num10 == 0: print("입력진수는 16, 10, 8, 2 진수여야 합니다") else : print("16 : ", hex(num10)) print("10 : %d"% num10) print("8 : ", oct(num10)) print("2 : ", bin(num10))
780e738f5917bf1de28f62cecd04413f8de1fa2d
Rillell/2_Grade_Project
/Python/3주차/0414_3.py
209
3.96875
4
#반복문 출력 0부터 시작, 3미만까지, 1씩 증가 for i in range(0, 3, 1) : print(i, end=', ') #end=' ' => 옆으로 출력 print() for i in ['S',0,1.12] : print(i, type(i))
54e2d54dd28d97bb6233eaacf045e9fb4c5b7fbf
Penultimatum/discord-boar-bot
/src/boarbot/modules/dice/diceroll.py
2,759
3.671875
4
import random, regex def roll_dice(num_dice: int, num_sides: int) -> [int]: num_dice = int(num_dice) num_sides = int(num_sides) if num_dice < 1: raise ValueError("Number of dice less than 0", num_dice) if num_sides < 1: raise ValueError("Number of sides less than 0", num_sides) rolls = [random.randint(1, num_sides) for i in range(num_dice)] return rolls DICE_REGEX = regex.compile("\A([0-9]+d[0-9]+)([+-][0-9]+(?:d[0-9]+)?)*\Z") class DiceRoll(object): def __init__(self, rolldef: str, comment=""): #Clear whitespace self.rolldef_dirty = rolldef self.rolldef = regex.split('[ \r\n\t]', rolldef) self.rolldef = ''.join(self.rolldef).lower() self.comment = comment self.rolls = [] self.roll_results = [] self.roll_total = 0 self._parse() self.do_roll() def _parse(self): match = DICE_REGEX.search(self.rolldef) if not match: raise ValueError("Invalid dice", self.rolldef) firstroll = '+' + match.captures(1)[0] self.rolls = [firstroll] + match.captures(2) @property def roll(self) -> (int, int, int, int): if not self.roll_results: self.do_roll() return self.roll_total, self.roll_min, self.roll_max, self.roll_results def do_roll(self, reroll=False): if not reroll and self.roll_results: return self.roll_results = [] for roll_exp in self.rolls: roll_entry = {} roll_entry['roll_exp'] = roll_exp roll_sign = roll_exp[0] if "d" in roll_exp: num_dice, num_sides = roll_exp[1:].split("d") roll_entry['num_dice'] = int(num_dice) roll_entry['num_sides'] = int(num_sides) dice_rolls = roll_dice(num_dice, num_sides) roll_entry['rolls'] = dice_rolls roll_entry['min'] = roll_entry['num_dice'] roll_entry['max'] = roll_entry['num_dice'] * roll_entry['num_sides'] else: # Constant value roll_entry['num_dice'] = 0 roll_entry['num_sides'] = 0 roll_entry['rolls'] = [] dice_rolls = [int(roll_exp[1:])] roll_entry['min'] = dice_rolls[0] roll_entry['max'] = dice_rolls[0] roll_entry['value'] = sum(dice_rolls) * {'+':1,'-':-1}[roll_sign] self.roll_results.append(roll_entry) self.roll_total = sum([entry['value'] for entry in self.roll_results]) self.roll_min = sum([entry['min'] for entry in self.roll_results]) self.roll_max = sum([entry['max'] for entry in self.roll_results])
b4e03131c51c1925d26fe5703e2edcd3c06b01c1
Wanbli83470/SCRIPT_ILLUSTRATOR
/TEXTE.py
421
3.953125
4
lettre = input("Indiquer la lettre en majuscule : ") nb_page = input("indiquer nombre de page : ") nb_page = int(nb_page) numerotation = 1 while numerotation <= nb_page : texte = "493165 "+ lettre + str(numerotation)+" AROMA ZONE" numerotation += 1 print(texte) print(texte) """import pyperclip pyperclip.copy('The text to be copied to the clipboard.') pyperclip.paste() 'The text to be copied to the clipboard."""
6397f2dda17c503e09fae36399e79926821442ea
lvvvmd/leetcode
/Partition List/Solution.py
819
3.84375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ small_list = ListNode(0) large_list = ListNode(0) small_head = small_list large_head = large_list while(head != None): if head.val >= x: large_list.next = ListNode(head.val) large_list = large_list.next else: small_list.next = ListNode(head.val) small_list = small_list.next head = head.next small_list.next = large_head.next return small_head.next
507aacd87c59aa891d10d3bc69b90134e4ad1c5d
aravindanath/Target2020PyAuto
/Assignment/tax_assignment_chinu.py
361
3.78125
4
def calculator(gross ,state): state_tax={"BOS":9,"NJ":8,"TX":7,"CA":10,"NY":6} netIncome=gross-(gross*.10) if state in state_tax: netIncome=netIncome-(gross*state_tax[state]/100) print("your net income is:" +str(netIncome)) return netIncome else: print("enter your details correctly") d=calculator(123456,"NY")
05f66f08d121afec9e6ff846a5649fa30ffd2ff4
aravindanath/Target2020PyAuto
/day4/whileDemo.py
332
3.828125
4
# # l1 = [] # x=0 # # while x <10: # # x= x+1 # # print(x) # x = x+1 # l1.append(x) # continue # # # print(l1) empty = [] print(empty) # Initialization x = 0 # Condition while x < 10: # Increment x = x +1; print(x) empty.append(x) else: print("Just broke out of the loop") print(empty)
2350c2ab05499f1b40ba61f2101c51d9581d57f6
aravindanath/Target2020PyAuto
/day4/methods.py
155
3.9375
4
def addnumber(i,j): sum= i+j print(sum) num1 = int(input("Enter 1st number")) num2 = int(input("Enter 2nd number")) z = addnumber(num1,num2)
e65119c8890ffa65825199cb4debb8cc20078782
aravindanath/Target2020PyAuto
/Assignment/TaxAssignment.py
421
3.640625
4
def taxCaluculator(gross,state): state_tax={"BOS":9.9,"NJ":8.3,"Tx":7.99,"CA":10.3,"NY":6.43} net = gross - (gross * .10) if state in state_tax: net = net - (gross * state_tax[state] / 100) print("Your net income after all the heavy taxes is : " + str(net)) return net else: print("Enter your details correctly!") return none d = taxCaluculator(7388276,"NJ")
7a96fb5c6d3cc968ea845478e958d64c646a9df5
aravindanath/Target2020PyAuto
/Day3/NestedDict.py
223
3.84375
4
student = {"name":{"Arvind","Naina","Bhavya","Kumar"}} print(student) cars={"Bmw":{"model":"2020","colour":"Blue"},"Audi":{"model":"Q5","colur":"red"}} print(cars["Bmw"]["colour"]) print(cars.keys()) print(cars.values())
4a81edb424f544664d9a6e279783923424e5d7bf
aravindanath/Target2020PyAuto
/day5/homeWork.py
200
3.671875
4
def exception(): try: car = {"make": "bmw", "Model": '550i', 'year': 2019} print(car["colour"]) except: print("Colour not found") # raise exception() exception()
d1c52c1792e509f17666cf35d6c43fdf162f21c2
KNU-CS09/Baekjoon
/2/kdh/7_2558.py
77
3.65625
4
a = int(input()) b = int(input()) if(0 < a < 10 and 0 < b < 10): print(a+b)
e89d2a1bb8619dd97424585534da78618f6c4bf7
ml-nic/Algorithms
/src/typical_string_processing_functions.py
1,007
4.125
4
def is_palindrome(string: str) -> bool: """ Is the string a palindrome? :param string: :return: """ length = len(string) for i in range(int(length / 2)): if string[i] != string[-i - 1]: return False return True assert is_palindrome("HelloolleH") is True assert is_palindrome("Hello") is False assert is_palindrome("") is True def extract_filename_and_extension(string: str) -> tuple: """ Extracts filename and extension of given string. :param string: :return: """ dot = string.index(".") base = string[0:dot] extension = string[dot+1:] return base, extension assert ("test", "txt") == extract_filename_and_extension("test.txt") def is_list_of_strings_sorted(list : list) -> bool: for i in range(1,len(list)): if list[i-1] > list[i]: return False return True assert is_list_of_strings_sorted(["hello", "world"]) is True assert is_list_of_strings_sorted(["world", "hello"]) is False
fd48332d351fb0b6f96ddf552e760b5529c5a70c
Rojina99/DesignPatterns-Python
/project/observer.py
1,338
3.515625
4
class Subject: observers = [] def Attach(self, obj): self.observers.append(obj) def Detach(self, obj): pass def Notify(self): for observer in self.observers: observer.Update() # print(self.observers) class ConcreteSubject(Subject): def __init__(self): self.state = None def SetState(self, value): self.state = value self.Notify() def GetState(self): return self.state class Observer: def Update(self): raise NotImplementedError("Update() must be defined in subclass") class ConcreteObserverA(Observer): def __init__(self, obj): self.conSub = obj self.conSub.Attach(self) def Update(self): print("Inside ConcreteObserverA: Update()") self.state = self.conSub.GetState() print("State ", self.state) class ConcreteObserverB(Observer): def __init__(self, obj): self.conSub = obj self.conSub.Attach(self) def Update(self): print("Inside ConcreteObserverB: Update()") self.state = self.conSub.GetState() print("State ", self.state) conSubObj = ConcreteSubject() obsObj1 = ConcreteObserverA(conSubObj) obsObj2 = ConcreteObserverB(conSubObj) conSubObj.SetState(1) conSubObj.SetState(2) # obsObj1.Update() # obsObj2.Update()
9b3581f4110efd5c01ce48a302015bc286ff2780
jackie500/python
/első két szám összege egyenlő e a harmadikkal.txt
602
3.765625
4
szám1 = int(input("szám1: ")) szám2 = int(input("szám2: ")) szám3 = int(input("szám3: ")) összeg1 = szám1 + szám2 összeg2 = szám1 + szám3 összeg3 = szám2 + szám3 if összeg1 == szám3: print("igen a", szám1, "és", szám2, " összege egyenlő", szám3, "-al") elif összeg2 == szám2: print("igen a", szám1, "és", szám3, " összege egyenlő", szám2, "-al") elif összeg3 == szám1: print("igen a", szám2, "és", szám3, " összege egyenlő", szám1, "-al") else: print("semelyik számpáros összege nem egyenlő a harmadik számmal ")
b5673ec003759f8e063728be0d5d5ebaf3d11173
jackie500/python
/26..py
329
3.578125
4
# 26 """ Írj egy Python programot, amely a temp.txt szöveges fájl minden második szavát (szóközzel elválasztott részsztringjét) a képernyőre írja! """ f = open("temp2.txt") fS = f.read() f.close() fSList = [] fSList = fS.split(" ") for i in range(1, len(fSList), 2): print(fSList[i])
aacb52f8c34cfc45c04c4339c5c4b6d317023541
jackie500/python
/12..py
290
3.890625
4
# 12. Írj egy Python programot, amely bekér egy szót (sztringet) a felhasználótól és kiírja a képernyőre a szó betűit, úgy, hogy minden betű egy új sorba kerüljön! szó = input("adjon meg egy szót: ") for i in range(len(szó)): print(szó[i], end=" ")
81e46e52df2c2e9d9f79df2b5711150b636fc740
jackie500/python
/6..py
382
3.796875
4
#6. Írj egy Python programot, amely bekér három egész számot a felhasználótól és kiírja a képernyőre, hogy mind a három páros szám-e (igen/nem)! összeg = int(input("szám1: ")) + int(input("szám2: ")) + int(input("szám3: ")) if összeg % 2 == 0: print("igen") else: print("nem") #folytatni tovább: egyesével vizsgálja meg hoyg páros szám e
db53c9384a2aa95036c7e4d2ad7d675a9950c1cc
jackie500/python
/main2.py
194
3.875
4
x = input("Írj egy számot: ") y = input("Írj egy számot:") z = input("Írj egy számot:") if x > y and z: print(x) if y > x and z: print(y) if z > x and y: print(z)
89217f458279e92ee6df66f495d97f41b62ee5eb
khanmaster/building_packages
/app/fizzbuzz.py
756
3.765625
4
class Fizzbuzz: def __init__(self, start_of_range, end_of_range): self.fizzrange = range(start_of_range, end_of_range) self.fizzbuzz_list = [] self._fizzbuzz_iterator() def _divisible_by(self, num1, num2): if num1 % num2 == 0: return True else: return False def _fizzbuzz_iterator(self): for num in self.fizzrange: if self._divisible_by(num, 15): self.fizzbuzz_list.append("fizzbuzz") elif self._divisible_by(num, 5): self.fizzbuzz_list.append("buzz") elif self._divisible_by(num, 3): self.fizzbuzz_list.append("fizz") else: self.fizzbuzz_list.append(num)
15c27949ec5d743e326a2f92936a2798db959939
AbdeAMNR/python-training
/00 expose Py/matplotlib - pandas - scipy (visualisation)/visualisation.py
1,137
3.640625
4
import pandas from matplotlib import pyplot from scipy import stats my_data = pandas.read_csv("univariate_linear_regression_dataset.csv") print("head : ") print(my_data.head()) print("tail : ") print(my_data.tail()) X = my_data.iloc[0:len(my_data), 0] Y = my_data.iloc[0:len(my_data), 1] pyplot.xlim([0, 25]) pyplot.ylim([0, 25]) pyplot.title("Le diagramme de dispersion de Y en fonction de X") pyplot.ylabel("L'axe des ordonnees") pyplot.xlabel("L'axe des abscisses") pyplot.scatter(X, Y) # this line allows saving a picture for a scatter # in this needs to give the path were to save the picture pyplot.savefig("python.png") slope, intercept, r_value, p_value, std_err = stats.linregress(X, Y) def predict(x): return slope * x + intercept YY = predict(X) pyplot.plot(X, YY, c='r') pyplot.show() print("\n=====================================================") print("Estimation pour X = 20 : ", predict(20)) print("Coeficient de regression : ", slope) print("Coeficient de corrélation : ", r_value) print("Qualité d'ajustement : ", r_value * r_value) print("=====================================================\n")
131aab97b27accfe995276674ee6a2959f51140d
AbdeAMNR/python-training
/Lecture 03 OOP/Person.py
1,327
3.96875
4
class Person(object): __first_name = "" __last_name = "" __age = "" def __init__(self, first_name, last_name, age): self.__first_name = first_name self.__last_name = last_name self.__age = age def full_name(self): return "{} {}".format(self.__first_name, self.__last_name) def get_first_name(self): return self.__first_name def get_last_name(self): return self.__last_name class Salary(Person): __salary = "" def __init__(self, first, last, age, salaire): Person.__init__(self, first, last, age) self.__salary = salaire def cmpSalaire(self, other): if self.__salary > other: return 1 elif self.__salary < other: return -1 elif self.__salary == other: return 0 def __eq__(self, other): return self.__salary == other.__salary and other.__salary == self.__salary def get_salaire(self): return self.__salary import time salarie1 = Salary("abdo", "amanar", 52, 18255) salarie2 = Salary("med", "aitHammou", 14, 1255) print(salarie1.cmpSalaire(salarie2.get_salaire())) print("================================") print(salarie1.__eq__(salarie2)) ticks = time.time() print("Number of ticks since 12:00am, January 1, 1970:", ticks)
f4bd7f39b23698c8328b007ce20f8147d1020699
AbdeAMNR/python-training
/Lecture 03 OOP/ClassInOneLine.py
769
3.671875
4
# create a class in one single line. # pros: # less lines of code # dynamic class creation # cons: the code cold be be missy: not recommended for long classes BaseClass = type("BaseClass", (object,), {"att": 2, "att2": 5}) C1 = type("C1", (BaseClass,), {"firstAtt": "hello", "SecAtt": 52}) C2 = type("C2", (BaseClass,), {"a": 5, "b": 88}) def myFactury(Bool_isTrue): return C1 if Bool_isTrue else C2 newClass = myFactury(False) print(str(newClass.a) + " this is a factory class") print("===================") ClassInOneLine = type("ClassInOneLine", (object,), {"attribute": 154}) c = ClassInOneLine() print(c.attribute) def list(*args): ls = [] for arg in args: ls.append(arg) return ls l = list("44", "zds", "ss", 5) print(l)
422c8cd0e2bcc3bce513c2a4b412d775b328e138
massivetarget/mtar_a
/capping.py
201
4.1875
4
# this is python file for capitalisation of give string nm = str(input("please Enter word to capitilise it: ")) print(nm.capitalize()) # this will do the real work print("adding 23 to 34", 23 + 34)
8d3475b6b96b34f9f280eba1124ae6e5583a45fe
Girech/infosatc-lp-avaliativo-01
/ex10.py
119
3.953125
4
km = float(input("Digite uma velocidade em Km/h:")) ms = km/3.6 print("A velocidade de {} em M/S é: {}".format(km,ms))
db5e1ae7eee9779208aaf0aaa7f46e67f3a589e4
Girech/infosatc-lp-avaliativo-01
/ex26.py
115
3.53125
4
m2 = float(input("Digite o valor em m²")) hectares = m2*0.0001 print("o valor em hectares é:{}".format(hectares))
1477902c7c0c5bdb2d9353ee1bad8d3f2ea6cd8e
rsamit26/AlgorithmsAndDatastructure
/EulerProject/10001st prime.py
999
3.96875
4
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ class Solution: def isPrime(self, n): if n == 1: return False elif n < 4: return True elif n%2 == 0: return False elif n<9: return True elif n%3 == 0: return False else: import math r = math.floor(math.sqrt(n)) f = 5 while f <=r: if n%f==0: return False if n% (f+2) == 0: return False f+=6 return True def genratePrime(self, n): if n==1: return 2 idx, nth_prime = 1,1 while idx < n: nth_prime+= 2 if self.isPrime(nth_prime): idx+= 1 return nth_prime s = Solution() print(s.genratePrime(1))
a20abaa8905d70a8f84992151cf381cd884f1f78
rsamit26/AlgorithmsAndDatastructure
/algorithms/Python/sorting/bucketSort.py
1,012
3.90625
4
""" Bucket sort algorithm :: """ import math def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def hashing(arr): m = max(arr) result = [m, int(math.sqrt(len(arr)))] return result def re_hashing(i, code): return int(i / code[0] * (code[1] - 1)) def bucketSort(array): code = hashing(array) buckets = [list() for _ in range(code[1])] for i in array: x = re_hashing(i, code) buck = buckets[x] buck.append(i) for bucket in buckets: insertion_sort(bucket) ndx = 0 for b in range(len(buckets)): for v in buckets[b]: array[ndx] = v ndx += 1 """ Test code """ ar = [.78, .17, .39, .26, .72, .94, .21, .12, .23, .68] # ar = [6, 8, 1, 45, 12] bucketSort(ar) print(ar) # result :: [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
aec494fc191d4c4ad71c109b09c2e47abb558776
rnu/Python_Freecell
/Python_Freecell.py
15,751
3.8125
4
################################################################## # Section 3 # Computer Project #8 ################################################################## # Algorithm # 1.Call main() # 2. Build game board # 3. Print Gameboard() # 4. Ask user input. # 5. Validate user move # 6. Perform user move, check if user won. # 7. Repeat til user wins. import cards from string import punctuation class Game( object ): suit_list = ['x','Clubs(1)','Diamonds(2)','Hearts(3)','Spades(4)'] """ Builds deck of cards, shuffles deck, initialize board dictionaries (tableau, cell, foundation), build tableaus. Receive: self Return: None Algorithm: 1. Build Deck of cards. 2. Shuffle cards. 3. Initialize tab, cell, foundation dictionaries. 4. Build tableaus 5. Print help() """ def __init__(self): #Build deck self.__deck = cards.Deck() #Shuffle deck self.__deck.shuffle() #Build Tableau, Cell and Foundation dictionaries self.__tab_dic={} self.__cell_dic={1:[],2:[],3:[],4:[]} self.__foundation_dic={1:[],2:[], 3:[],4:[]} #Build board self.build_Tab() #Print options self.help() """ Returns None Receive: self Return: None """ def __str__(self): return None """ Returns None Receive: self Return: None """ def __repr__(self): return None """ Builds the individual tableaus. Receive: self Return: None 1. Build 8 indexes for __tab_dic 2. Populate each index with card using cards.Deck.deal() """ def build_Tab(self): i=1 #Build 8 Tableaus while i<9: self.__tab_dic[i]=[] #Add 7 cards to the first 4 if len(self.__tab_dic)<5: t=0 while t<7: self.__tab_dic[i].append(self.__deck.deal()) t+=1 else: t=0 #Add 6 cards to the last tableaus while t <6: self.__tab_dic[i].append(self.__deck.deal()) t+=1 i+=1 return None """ Prints current state of board Receive: self Return: None Algorithm: 1. Print orientation directions, along with contents of tableaus 2. Prints contents of cells. 3. prints contents of foundations. """ def print_Board(self): #Print tableau print(" "*3,"Top", "\t"*2, "Bottom") for k,v in self.__tab_dic.items(): print("{}. {}".format(k,v)) #Print Cells print("-"*7+ " Cells") for k,v in self.__cell_dic.items(): if len(v) == 0: print("Cell {}: Empty".format(k)) else: print("Cell {}: {}".format(k,v)) #Print Foundation print("-"*7+ " Foundation") for k,v in self.__foundation_dic.items(): if len(v) == 0: print("{}: Empty".format(self.suit_list[k])) else: print("{}: {}".format(self.suit_list[k],v)) print("\n\n") return None """ Transfers card from tableau to tableau. Receive: self, tab_from, tab_to Return: None Algorithm: 1. Pop the last card off tab_from. 2. Pop the last card off tab_to. 3. Check if they match in suit or rank, if they do it is an invalid move. 4. Checks if the from_card is black and to_card is red (vice versa) and that the difference in rank is one. 5. Append cards to approiate tableau. """ def __t2t(self, tab_from ,tab_to): #Try to pop cards from tab from_card = '' to_card = '' from_card = self.__tab_dic[tab_from].pop() to_card = self.__tab_dic[tab_to].pop() #If tableau is empty, append if(len(self.__tab_dic[tab_to])==0): self.__tab_dic[tab_to].append(from_card) return #If ranks match, invalid move if(from_card.get_rank() == to_card.get_rank()): self.__tab_dic[tab_to].append(to_card) self.__tab_dic[tab_from].append(from_card) print("Invalid Move") return else: None #If suits match, invalid move if(from_card.get_suit() == to_card.get_suit()): self.__tab_dic[tab_to].append(to_card) self.__tab_dic[tab_from].append(from_card) print("Invalid Move") return else: None #If from_card is black and to_card is red, and the difference is one, append if (from_card.get_suit() in [1,4]) and (to_card.get_suit() in [2,3]): if(to_card.get_rank() - from_card.get_rank())==1: self.__tab_dic[tab_to].append(to_card) self.__tab_dic[tab_to].append(from_card) else: pass #If from_Card is red and to_card is black, and the difference is one, append. elif (from_card.get_suit() in [2,3]) and (to_card.get_suit() in [1,4]): if(to_card.get_rank() - from_card.get_rank())==1: self.__tab_dic[tab_to].append(to_card) self.__tab_dic[tab_to].append(from_card) else: pass else: self.__tab_dic[tab_to].append(to_card) self.__tab_dic[tab_from].append(from_card) print("Invalid Move") """ Transfers card from tableau to cell. Receive: self, tab, cell Return: None Algorithm: 1. Pop the last card off tab 2. Pop the last card off cell 3. If there isn't a card in self.__cell_dic, than append. 4. If there is a card in self.__cell_dic, invalid move. """ def __t2c(self, tab, cell): if len(self.__cell_dic[cell]) == 0: self.__cell_dic[cell].append(self.__tab_dic[tab].pop()) else: print("Invalid move\n") """ Transfers card from tableau to foundation. Receive: self, tab, found Return: None Algorithm: 1. Pop the last card off tab. 2. Pop the last card off foundation. 3. If the suit of the tableau card doesn't match the foundation, invalid move. 4. If the foundation is empty, and card is an Ace, append. 5. If the found has a card, and the difference in ranks is 1, append. """ def __t2f(self, tab, found): #Tableau card (tab_card) try: tab_card = self.__tab_dic[tab].pop() except IndexError: print("There is not a card here.\n") #If tab_card suit and 'found' don't match, return tab_card to tableau and send an error. if tab_card.get_suit() != found: self.__tab_dic[tab].append(tab_card) print("Error, Sent card to wrong foundation\n") return #If foundation has a card pop it. if len(self.__foundation_dic[found])!= 0: f_card = self.__foundation_dic[found].pop() #If it doesn't, create one. else: f_card = cards.Card() #If foundation is empty and tab_card is an Ace, append if (len(self.__foundation_dic[found])== 0) and (tab_card.get_rank() == 1): self.__foundation_dic[found].append(tab_card) #If foundation has card and the difference in values is 1, append. elif tab_card.get_rank() != 1 and (tab_card.get_rank() - f_card.get_rank()) == 1: self.__foundation_dic[found].append(tab_card) #If all test fail, append tab_card back to tableau and report error else: self.__tab_dic[tab].append(tab_card) self.__foundation_dic[found].append(f_card) print("Invalid move...\n") """ Transfers card from cell to tableau. Receive: self, cell, tab Return: None Algorithm: 1. Pop the last card off tab. 2. Pop the last card off cell. 3. Check if they match in suit or rank, if they do it is an invalid move. 4. Checks if the cell_card is black and tab_card is red (vice versa) and that the difference in rank is one. 5. Append cards to approiate tableau. """ def __c2t(self,cell,tab): #Try to pop cards from cell try: cell_card = self.__cell_dic[cell].pop() tab_card = self.__tab_dic[tab].pop() #if cards have same rank, don't append if(cell_card.get_rank() == tab_card.get_rank()): self.__tab_dic[tab].append(tab_card) self.__cell_dic[cell].append(cell_card) print("Invalid Move") return #If cards have same suit, don't append if(cell_card.get_suit() == tab_card.get_suit()): self.__tab_dic[tab].append(tab_card) self.__cell_dic[cell].append(cell_card) print("Invalid Move") return #If tableau is empty, append if(len(self.__tab_dic[tab])==0): self.__tab_dic[tab].append(cell_card) return #If cell_card is black and tab_card is red, and the difference is one, append if (cell_card.get_suit() in [1,4]) and (tab_card.get_suit() in [2,3]): if(tab_card.get_rank() - cell_card.get_rank())==1: self.__tab_dic[tab].append(tab_card) self.__tab_dic[tab].append(cell_card) else: pass #If cell_card is red and tab_card is black, and the difference is one, append. elif (cell_card.get_suit() in [2,3]) and (tab_card.get_suit() in [1,4]): if(tab_card.get_rank() - cell_card.get_rank())==1: self.__tab_dic[tab].append(tab_card) self.__tab_dic[tab].append(cell_card) else: pass else: self.__tab_dic[tab].append(tab_card) self.__cell_dic[cell].append(cell_card) print("Invalid Move") except (IndexError, UnboundLocalError): print("Card not found") """ Transfers card from cell to foundation. Receive: self, cell, found Return: None Algorithm: 1. Pop the last card off foundation. 2. Pop the last card off cell. 3. If the suit of the cell card doesn't match the foundation, invalid move. 4. If the foundation is empty, and card is an Ace, append. 5. If the found has a card, and the difference in ranks is 1, append. """ def __c2f(self, cell, found): #cell card (cell_card) try: cell_card = self.__cell_dic[cell].pop() except IndexError: print("There is not a card here.\n") #If cell_card suit and 'found' don't match, return cell_card to cell and send an error. if cell_card.get_suit() != found: self.__cell_dic[cell].append(cell_card) print("Error, Sent card to wrong foundation\n") return #If foundation has a card pop it. if len(self.__foundation_dic[found])!= 0: f_card = self.__foundation_dic[found].pop() #If it doesn't, create one. else: f_card = cards.Card() #If foundation is empty and cell_card is an Ace, append() if len(self.__foundation_dic[found])== 0 and (cell_card.get_value() == 1): self.__foundation_dic[found].append(cell_card) #If foundation has card and the difference in values is 1, append. (As long as cell_card isn't an Ace(1)) elif cell_card.get_rank() != 1 and (cell_card.get_rank() - f_card.get_rank()) == 1: self.__foundation_dic[found].append(cell_card) #If all test fail, append cell_card back to cell and report error else: self.__cell_dic[cell].append(cell_card) self.__foundation_dic[found].append(f_card) print("Invalid move...\n") """ Ask for user input and makes approiate actions. (Menu) Receive: self Return: None, (or read_player() if input isn' t correct) Algorithm: 1. Ask user for input. 2. Split user input into a list. 3. Check user input for correct function. 4. Ask again if user input isn't correct. """ def read_player(self): #Format player's input temp = input("Which move would you like to make\n") temp = temp.lower() temp = ''.join(ch for ch in temp if ch not in punctuation) choice = temp.split() #Quit -- Not working!!!!!!!!!!!!! if len(choice) != 3: if choice[0] in ['help', 'h']: self.help() elif choice[0] in ['q','quit']: return 'q' elif choice[0] in ['c']: self.cheat() else: print("Choice not found") return self.read_player() #T2T elif choice[0] in ['t2t']: self.__t2t(int(choice[1]), int(choice[2])) #T2C elif choice[0] in ['t2c']: self.__t2c(int(choice[1]), int(choice[2])) #T2F elif choice[0] in ['t2f']: self.__t2f(int(choice[1]), int(choice[2])) #C2T elif choice[0] in ['c2t']: self.__c2t(int(choice[1]), int(choice[2])) #C2F elif choice[0] in ['c2f']: self.__c2f(int(choice[1]), int(choice[2])) #Non-valid choice else: print("Choice not found") return self.read_player() """ Print instructions Receive: self Return: None Algorithm: 1.Print instructions """ def help(self): print("*"*10) print("t2t tableau1 tableau2 (Tableau to Tableau)\n"\ "t2c tableau cell (Tableau to Cell)\n"\ "t2f tableau foundation (Tableau to Foundation\n"\ "c2t cell tableau (Cell to Tableau)\n"\ "c2f cell foundation (Cell to Foundation)\n"\ "h (Help)\n"\ "q (Quit)") print("*"*10,"\n") """ Check if user has won. Receive: self, temp Return: has_won Algorithm: 1. For every king in foundation, add won to has_won. 2. 'q' automatically sets has_won to 5, to exit program. """ def game_Won(self, temp = 0): #If foundations all have Aces, game has been won has_won = 0 for k,v in self.__foundation_dic.items(): if len(v) != 0: #If top card is a King if v[0].get_rank() == 13: has_won +=1 else: pass if temp > 0: has_won = temp print("Good Bye") return has_won """ Debug function. Cheater. Receive: self Return: has_won Algorithm: 1. It's called. 2. It wins. (By setting foundation to all kings.) """ def cheat(self): for k,v in self.__foundation_dic.items(): newCard = cards.Card(rank = 13, suit = k) self.__foundation_dic[k].append(newCard) ### """ Main game cycle Receive: None Return: None Algorithm: 1. Initialize game. 2. Loop through test.print_Board() and test.read_player() """ def main(): #Initialize board test = Game() while test.game_Won() < 4: test.print_Board() if test.read_player() == 'q': break print("You won!") main()
ec6d87abbc3b27ae1bfcac34c4c921f3c493eb69
jsourabh1/Striver-s_sheet_Solution
/Day-12_Bits/question1_power_of_2.py
265
4.03125
4
class Solution: ##Complete this function # Function to check if given number n is a power of two. def isPowerofTwo(self,n): if n==0: return False if (n&(n-1))==0: return True return False
cde8cc5295ece077049c3e4c432419aa331c0c59
jsourabh1/Striver-s_sheet_Solution
/Day-19_BinaryTree3/question1_maximum_sum.py
736
3.5
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(self, root: Optional[TreeNode]) -> int: ans=-float("inf") def helper(root): nonlocal ans if not root: return 0 left=helper(root.left) right=helper(root.right) ans=max(ans,root.val+left+right,root.val,root.val+max(left,right)) return max(root.val,root.val+max(left,right)) helper(root) return ans
eb7746e1dcdccaecbde4b17f2f6db92830b0751d
jsourabh1/Striver-s_sheet_Solution
/Day-17_BinaryTree/question1_inorder.py
1,522
4.09375
4
class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # With recursion def inorder(root): if not root: return inorder(root.left) print(root.data, end=" ") inorder(root.right) # With stack and without recursion def inorder2(root): if not root: return queue = [] ans = [] while queue or root: if root: queue.append(root) root = root.left else: ans.append(queue[-1].data) root = queue.pop().right print(ans) # Without recursion and stack only iterative with space O(1) def inorder3(root): if not root: return current = root while current is not None: if current.left is None: print(current.data, end=" ") current = current.right else: pre = current.left while (pre.right is not None) and (pre.right is not current): pre = pre.right if pre.right is None: pre.right = current current = current.left else: print(current.data,end=" ") pre.right = None current = current.right root = Node(10) root.left = Node(8) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(5) root.right.left = Node(2) inorder(root) print() inorder2(root) print() inorder3(root)
569a69d27cd52c961e1fa7a3f63b7effe2bcdbc6
jsourabh1/Striver-s_sheet_Solution
/Day-16_String2/question4_anagrams.py
378
3.84375
4
class Solution: #Function is to check whether two strings are anagram of each other or not. def isAnagram(self,a,b): a=sorted(a) b=sorted(b) if len(a)!=len(b): return False for i in range(len(a)): if a[i]!=b[i]: return False return True
776570db6172e6379b4dc91afd491c5b05871515
jsourabh1/Striver-s_sheet_Solution
/Day-13_Stack/question3_queue_using_stack.py
562
4.125
4
def Push(x,stack1,stack2): ''' x: value to push stack1: list stack2: list ''' #code here stack1.append(x) #Function to pop an element from queue by using 2 stacks. def Pop(stack1,stack2): ''' stack1: list stack2: list ''' #code here if stack1: stack2=[] while stack1: temp=stack1.pop() stack2.append(temp) temp=stack2.pop() while stack2: stack1.append(stack2.pop()) return temp return -1
45e57b00ed86166064a52861f7249a2d68024c64
alongigi/K-MeansClustering
/Cluster.py
1,925
3.609375
4
import matplotlib.pyplot as plt import plotly.plotly as py from sklearn.cluster import KMeans """ Responsible for the K-means idea as taught in class. :Param {df} the the frame of the program :Param {n_clusters} The number of clusters :Param {n_init} Num of runs. """ def KMean(df, n_clusters, n_init): km = KMeans(n_clusters=int(n_clusters), n_init=int(n_init)) km.fit(df) df['Clustering'] = km.fit_predict(df) """ Responsible for saving the results extracting the cluster column data from the data frame :Param {df} the the frame of the program :Param {path} Path of the folder. """ def save_result(df, path): clustering = df['Clustering'] df1 = df[['Social support']] df2 = df[['Generosity']] t = plt.scatter(df1, df2, c=clustering) plt.colorbar(t) plt.xlabel('Social support') plt.ylabel('Generosity') plt.title('Scatter') plt.legend() plt.savefig(path + 'Scatter.png') py.sign_in(username="avi123456789", api_key="JRT8ZyGZ3fIUwGH8AIl5") df.reset_index(inplace=True) data = [dict( type='choropleth', locations=df['country'], z=clustering, locationmode='country names', colorscale=[[0, "rgb(5, 10, 172)"], [0.35, "rgb(40, 60, 190)"], [0.5, "rgb(70, 100, 245)"], [0.6, "rgb(90, 120, 245)"], [0.7, "rgb(106, 137, 247)"], [1, "rgb(220, 220, 220)"]], autocolorscale=False, reversescale=True, marker=dict( line=dict( color='rgb(180,180,180)', width=0.5 )), colorbar=dict( autotick=False, title='cluster'), )] layout = dict(title='Horopleth Map', geo=dict(showframe=False, showcoastlines=False, projection=dict(type='Mercator'))) fig = dict(data=data, layout=layout) py.iplot(fig, validate=False, filename='world-map') py.image.save_as(fig, filename=path + 'HoroplethMap.png')
1ba233bf6d91df731ef3347bfe864e6b353f2be8
elinaavintisa/Python_2variants
/2uzdevums.py
900
4.1875
4
""" Funkcija akrs akceptē trīs argumentus - skaiļus viens, divi un trīs, aprēķina to kvadrātu starpību un atgriež to. Pārbaudiet funkcijas darbību ar dažādiem argumentiem, parādot skaitli ar četriem simboliem aiz komata. Argumenti: viens {int vai float} -- pirmais skaitlis divi {int vai float} -- otrais skaitlis tris {int vai float} -- trešais skaitlis Atgriež: int vai float -- argumentu summa """ """ import math import decimal def akrs(a, b, c): kvadrats=float(pow(a,2)+pow(b,2)+pow(c,2)) return kvadrats print('%.2f'% akrs(2, 3, 4)) """ """Kļudu labojums:""" import math import decimal def akrs(a, b, c): kvadrats=float(pow(a,2)+pow(b,2)+pow(c,2)) return kvadrats print("%.4f" % akrs(2, 3, 4)) """ 2f vietā ieliku 4f, jo uzdevumā tiek prasīti 4 cipari aiz komata."""
0d8629a72beac9a6c1320dd45867c30e60060638
CAVIND46016/Academic-Coursework
/Artificial Intelligence/NQueens/nqueens.py
4,091
4.0625
4
import sys import time def count_on_row(board, row): """ Count # of pieces in given row :param board: :param row: :return: """ return sum(board[row]) def count_on_col(board, col): """ Count # of pieces in given column :param board: :param col: :return: """ return sum([row[col] for row in board]) def count_pieces(board): """ Count total # of pieces on board :param board: :return: """ return sum([sum(row) for row in board]) def printable_board(board): """ Return a string with the board rendered in a human-friendly format :param board: :return: """ text = "" for r in range(N): for c in range(N): # Unavailable position of the board if r == x - 1 and c == y - 1: text += "X " continue if board[r][c]: text += sym + " " else: text += "_ " text += "\n" return text def add_piece(board, row, col): """ Add a piece to the board at the given position, and return a new board (doesn't change original) :param board: :param row: :param col: :return: """ return board[0:row] + [board[row][0:col] + [1, ] + board[row][col + 1:]] + board[row + 1:] def successors2(board): """ Retrieve a list of the successor states for a given board configuration. :param board: :return: """ successor_list = [] if count_pieces(board) < N: valid_r = [r for r in range(N) if (count_on_row(board, r) < 1)] valid_c = [c for c in range(N) if (count_on_col(board, c) < 1)] for r in valid_r: for c in valid_c: # if position is unavailable, do not add to the successor list. if r == x - 1 and c == y - 1: continue successor_list.append(add_piece(board, r, c)) break return successor_list def validate(board, row, col): """ to validate that given a queen, there is no other queen on its upper or lower diagonal conflicting with it. :param board: :param row: :param col: :return: """ for r in range(row + 1, N): for c in range(N): if r - row == c - col or r + c == row + col: if board[r][c]: return False return True # check if board is a goal state def is_goal(board): if (count_pieces(board) == N and all([count_on_row(board, r) <= 1 for r in range(N)]) and all([count_on_col(board, c) <= 1 for c in range(N)])): if type_ == "nrook": return True else: for r in range(N): for c in range(N): if board[r][c]: xx = validate(board, r, c) if not xx: return xx return True return False def solve(board): """ Solve n-rooks! :param board: :return: """ fringe = [board] while len(fringe) > 0: for successor in successors2(fringe.pop()): if is_goal(successor): return successor fringe.append(successor) return False # This is N, the size of the board. It is passed through command line arguments. type_ = "nqueen" N = 9 x = 1 y = 1 if type_ not in ("nrook", "nqueen") or x not in range(1, N + 1) or y not in range(1, N + 1): print("Invalid Input") sys.exit(0) if type_ == "nrook": sym = "R" else: sym = "Q" # The board is stored as a list-of-lists. Each inner list is a row of the board. # A zero in a given square indicates no piece, and a 1 indicates a piece. initial_board = [[0] * N] * N print("Starting from initial board:\n" + printable_board(initial_board) + "\n\nLooking for solution...\n") s = time.time() solution = solve(initial_board) print(printable_board(str(solution)) + "\n" + "{} secs".format( time.time() - s) if solution else "Sorry, no solution found. :(")
5bf9c62989dce3cd7176735ac06f56a8cc57fa2f
CAVIND46016/Academic-Coursework
/Strassens Matrix Multiplication/generate_test_matrices.py
1,338
3.671875
4
""" Creates two test matrices and writes it into two text files ==> 'matRead1.txt' and 'matRead2.txt' """ import random MATRIX_INPUT_1 = 'matRead1.txt' MATRIX_INPUT_2 = 'matRead2.txt' def write_random_matrix_to_file(filename, mat_dim1, mat_dim2, l_range, h_range): """ Writes matrix to text file :param filename: :param mat_dim1: :param mat_dim2: :param l_range: :param h_range: :return: """ with open(filename, "w", encoding="utf8") as file: for _ in range(mat_dim1): for j in range(mat_dim2): if j != mat_dim2 - 1: file.write(str(random.randint(l_range, h_range)) + ",") else: file.write(str(random.randint(l_range, h_range))) file.write("\n") def main(): rows1, columns1 = 512, 512 rows2, columns2 = 512, 512 assert columns1 == rows2 num_low, num_high = 1, 9 for value in [ (MATRIX_INPUT_1, rows1, columns1), (MATRIX_INPUT_2, rows2, columns2) ]: write_random_matrix_to_file( value[0], value[1], value[2], num_low, num_high ) print("Matrices generated successfully.") if __name__ == "__main__": main()
79350df0310993beaf47d0dd72d3ec301e18a876
Sebsiee/PLD-Assignment-2-SANTOS-BSCOE-1-6-
/Money & Apple.py
575
3.828125
4
print("Welcome!") moneyAmount=int(input("Enter the amount of your money: ")) applePrice=int(input("What is the price of an apple? ")) totalApples=(moneyAmount / applePrice) totalChange=(moneyAmount - applePrice ) if totalApples > 1: print("You can buy " + str("%.0f" % totalApples) + " apples and your change is " + str(totalChange) + " pesos.") elif totalApples == 1: print("You can buy " + str("%.0f" % totalApples) + " apple and your change is " + str(totalChange) + " pesos.") else: print("You can't buy an apple and your change is " + str(totalChange) + " pesos.")
2c60d95891b60bc6a950004a12620d80286c4296
RasaHQ/sphinx-markdown-builder
/sphinx_markdown_builder/depth.py
758
3.609375
4
class Depth: depth = 0 sub_depth = {} def get(self, name=None): if name: return self.sub_depth[name] if name in self.sub_depth else 0 return depth def descend(self, name=None): self.depth = self.depth + 1 if name: sub_depth = ( self.sub_depth[name] if name in self.sub_depth else 0 ) + 1 self.sub_depth[name] = sub_depth return self.get(name) def ascend(self, name=None): self.depth = max(0, self.depth - 1) if name: sub_depth = max( 0, (self.sub_depth[name] if name in self.sub_depth else 0) - 1 ) self.sub_depth[name] = sub_depth return self.get(name)
71971acd89b0650884c1c909e322cf06867d5732
mehulsharma3795/Stock-Options-Pricing-Model
/binomial_option_model.py
975
3.625
4
import numpy as np def binomial_model(N, S0, u, r, K): """ N = number of binomial iterations S0 = initial stock price u = factor change of upstate r = risk free interest rate per annum K = strike price """ d = 1 / u p = (1 + r - d) / (u - d) q = 1 - p # make stock price tree stock = np.zeros([N + 1, N + 1]) for i in range(N + 1): for j in range(i + 1): stock[j, i] = S0 * (u ** (i - j)) * (d ** j) # Generate option prices recursively option = np.zeros([N + 1, N + 1]) option[:, N] = np.maximum(np.zeros(N + 1), (stock[:, N] - K)) for i in range(N - 1, -1, -1): for j in range(0, i + 1): option[j, i] = ( 1 / (1 + r) * (p * option[j, i + 1] + q * option[j + 1, i + 1]) ) return option if __name__ == "__main__": print("Calculating example option price:") op_price = binomial_model(5, 4, 2, 0.25, 8) print(op_price)
07456dd2e3e0d57f305f7963cda5d31ecec92da6
BhavyaTeja/Python-Mini-Projects
/GuessTheNumber.py
684
4.09375
4
#importing the libraries import random #Random function which generates the random numbers between 1 and 100 def rando(): a = random.randint(1, 100) b = int(input('Guess the number between 1 and 100: ')) compare(a,b) choice = input('You want to try again: Yes/No - ') if choice == 'Yes' or choice == 'yes': rando() #Compare function compares the guessed number with the random number def compare(a,b): if b > a: b = int(input('Wrong Guess! Enter a smaller number: ')) compare(a,b) elif b < a: b = int(input('Wrong Guess! Enter a greater number: ')) compare(a,b) else: print('Correct Guess') rando()
933fcf4d71b8cbc8cb825b279feaee9a9fb5d44c
cas-gh/Black-Hole-Tutorial
/blackHole.py
836
3.9375
4
from decimal import Decimal from math import sqrt #### CONSTANTS #### G = 6.674 * 10**-11 # in m^3 * kg^-1 * s^-2 c = 299792458 # in m/s def blackHole(): # Uses formula for Schwarzschild radius to give size of # black hole, photon sphere, M = input("Enter a mass in kg: ") rs = (2 * G * float(M)) / c**2 photonRad = 1.5 * rs ve = sqrt((2 * G * float(M)) / rs) rounded_pR = '%.2E' % Decimal(str(photonRad)) rounded_rs = '%.2E' % Decimal(str(rs)) rounded_ve = '%.2E' % Decimal(str(ve)) print("The Schwarzschild radius of your black hole would be: " + rounded_rs + " meters.") print("The radius of the photon sphere would be: " + rounded_pR + " meters.") print("Escape velocity at the Schwarzschild radius is: " + rounded_ve + "m/s.") if __name__ == '__main__': blackHole()
84bcfb6116c879af56bc8ff3e433b488259d0828
ibrhmerdogan/emojiFindAll
/venv/Lib/site-packages/emot/core.py
3,151
3.75
4
import re from emot import emo_unicode #import emo_unicode '''emot library to detect emoji and emoticons. >>> import emot >>> text = "I love python 👨 :-)" >>> emot.emoji(text) >>> {'value': ['👨'], 'mean': [':man:'], 'location': [[14, 14]], 'flag': True} >>> emot.emoticons(text) >>> {'value': [':-)'], 'location': [[16, 19]], 'mean': ['Happy face smiley'], 'flag': True} ''' __all__ = ['emoji','emoticons'] def emoji(string): '''emot.emoji is use to detect emoji from text >>> text = "I love python 👨 :-)" >>> emot.emoji(text) >>> {'value': ['👨'], 'mean': [':man:'], 'location': [[14, 14]], 'flag': True} ''' __entities = {} __value = [] __mean = [] __location = [] flag = True try: pro_string = str(string) for pos,ej in enumerate(pro_string): if ej in emo_unicode.UNICODE_EMO: try: __value.append(ej) __mean.append(emo_unicode.UNICODE_EMO[ej]) __location.append([pos,pos]) except Exception as e: flag = False __entities.append({"flag": False}) return __entities except Exception as e: flag = False __entities.append({"flag": False}) return __entities if len(__value) < 1: flag = False __entities = { 'value' : __value, 'mean' : __mean, 'location' : __location, 'flag' : flag } return __entities def emoticons(string): '''emot.emoticons is use to detect emoticons from text >>> text = "I love python 👨 :-)" >>> emot.emoticons(text) >>> {'value': [':-)'], 'location': [[16, 19]], 'mean': ['Happy face smiley'], 'flag': True} ''' __entities = [] flag = True try: pattern = u'(' + u'|'.join(k for k in emo_unicode.EMOTICONS) + u')' __entities = [] __value = [] __location = [] matches = re.finditer(r"%s"%pattern,str(string),re.IGNORECASE) for et in matches: __value.append(et.group().strip()) __location.append([et.start(),et.end()]) __mean = [] for each in __value: __mean.append(emo_unicode.EMOTICONS_EMO[each]) if len(__value) < 1: flag = False __entities = { 'value' : __value, 'location' : __location, 'mean' : __mean, 'flag' : flag } except Exception as e: __entities = [{'flag' : False}] #print("No emoiticons found") return __entities return __entities def test_emo(): test = "I love python 👨 :-)" print(emoji(test)) print(emoticons(test)) return None def about(): text = "emot library: emoji and emoticons library for python. It return emoji or emoticons from string with location of it. \nAuthors: \n Neel Shah: neelknightme@gmail.com or https://github.com/NeelShah18 \n Subham Rohilla: kaka.shubham@gmail.com or https://github.com/kakashubham" print(text) return None if __name__ == '__main__': test_emo()
68a12531e11433cc86e5b6806f64e8ffa3a774a7
RobinChien/python-study-notes
/Speed of 'while True' and 'while 1'/demo.py
72
3.65625
4
def add(a, b): return a+b c = add(1, 2) print("Result of add:", c)
8aa22a1316b830c4b0c78d374adff5f099ea2bd5
annikaheiling/CompOrgLabs
/Lab 3a - Week 7/binsearch.py
395
3.953125
4
def binSearch(arr, size, target): low = 0 high = size while(low+1 < high): test = (low+high) // 2 if (arr[test] > target): high = test else: low = test if (arr[low] == target): print("target found at index "+str(low)) else: print("target not found") arr = [1, 15, 19, 20, 21, 25, 30, 39] size = len(arr) binSearch(arr, size, 15)
7d01b52b9d8b59a8016479921a1219282ad55d15
5l1v3r1/small_decipher_for_arg
/decipher.py
573
3.578125
4
s1 = "Fgzgrb qftc citkt om cal egdofu ykgd. 28 btakl samtk, ct ktetoxtr a loufas miam cal asdglm mit ladt.".lower() s2 = "Nobody knew where it was coming from. 28 years later, we received a signal that was almost the same.".lower() def decipher(s): decoded_message = "" for c in range(0, len(s)): for c1 in range(0, len(s1)): if s[c] == s1[c1]: decoded_message = decoded_message + s2[c1] break print(decoded_message) # print(string_name[c]) decipher("FADT GY LOUFAS".lower()) input()
0887a6ce4c4a9ef5c05529f1804c367bc95b05d7
jijessicam/COW-analysis
/scripts/tutorial.py
360
3.78125
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.set_option('max_columns', 50) # Part 1: series # Create series with arbitrary list s = pd.Series([7, 'Heisenberg', 3.14, -12312412512, 'Happy Eating!']) # can specify index when creating series print s # reading in a CSV from_csv = pd.read_csv("interstate_wars.csv") from_csv.head()
f5d59978eb41fa768c32f83a8270359687f00c85
green-fox-academy/ZaitzeV16
/python_solutions/week-02/day-2/data_structures/telephone_book.py
1,155
4.53125
5
""" # Telephone book We are going to represent our contacts in a map where the keys are going to be strings and the values are going to be strings as well. - Create a map with the following key-value pairs. | Name (key) | Phone number (value) | | :------------------ | :------------------- | | William A. Lathan | 405-709-1865 | | John K. Miller | 402-247-8568 | | Hortensia E. Foster | 606-481-6467 | | Amanda D. Newland | 319-243-5613 | | Brooke P. Askew | 307-687-2982 | - Create an application which solves the following problems. - What is John K. Miller's phone number? - Whose phone number is 307-687-2982? - Do we know Chris E. Myers' phone number? """ phone_book = { "William A. Lathan": "405-709-1865", "John K. Miller": "402-247-8568", "Hortensia E. Foster": "606-481-6467", "Amanda D. Newland": "319-243-5613", "Brooke P. Askew": "307-687-2982" } print("What is John K. Miller's phone number?") print(phone_book.get("John K. Miller")) print("Whose phone number is 307-687-2982?") for k, v in phone_book.items(): if v == "307-687-2982": print(k) print("Do we know Chris E. Myers' phone number?") print("yes :)" if phone_book.__contains__("Chris E. Myers") else "nope, sorry")
c76f110e5956d21b2f2c0d32ed1667af9a131297
green-fox-academy/ZaitzeV16
/python_solutions/week-02/day-1/arrays/print_all.py
171
3.953125
4
# - Create an array variable named `numbers` # with the following content: `[4, 5, 6, 7]` # - Print all the elements of `numbers` numbers = [4, 5, 6, 7] print(numbers)
be8feb35e445c3b3e7034c0ab972fad87038d645
green-fox-academy/ZaitzeV16
/python_solutions/week-02/day-2/data_structures/is_in_list.py
516
4.09375
4
# Check if list contains all of the following elements: 4,8,12,16 # Create a function that accepts list_of_numbers as an input # it should return "True" if it contains all, otherwise "False" list_of_numbers = [2, 4, 6, 8, 10, 12, 14, 16] def check_nums(list_of_numbers: list): numbers_to_check = [4, 8, 12, 16] for number in numbers_to_check: if not list_of_numbers.__contains__(number): return False return True if __name__ == '__main__': print(check_nums(list_of_numbers))