blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
f78f63eee3f5c35d2a564abb81adf7a24f5dba3f
BryCant/Intro-to-Programming-MSMS-
/FInal/finalLibrary.py
2,489
3.84375
4
import random class Student: def __init__(self, name, age, glasses, volume, nag_level): self.name = name self.age = age self.glasses = glasses self.volume = volume self.nag_level = nag_level def __str__(self): return f"Hi I am {self.name} and I am {self.age} years old {'!' * self.volume}" class Vehicle: def __init__(self, wheels, door_num, color, **car_stuffs): self.wheels = wheels self.door_num = door_num self.color = color if car_stuffs is not None: if "top_speed" in car_stuffs.keys(): self.top_speed = car_stuffs["top_speed"] else: self.top_speed = None if "passengers" in car_stuffs.keys(): self.passengers = car_stuffs["passengers"] else: self.passengers = None else: self.car_stuffs = None def get_max_pass(self): if self.wheels == 2: return 2 elif self.wheels > 2: return random.randint(4, 8) def get_driver_name(self): # first passenger is driver return self.passengers[0] def __str__(self): # car go HONK! print("HONK!!" + "!" * self.wheels) return "HONK!!" + "!" * self.wheels class SchoolBus(Vehicle): def __init__(self, wheels=4, door_num=2, color="yellow", **car_stuffs): super().__init__(wheels, door_num, color, **car_stuffs) self.bus_num = random.randint(100,999) def get_max_pass(self): return random.randint(len(self.passengers), len(self.passengers) + 12) def __add__(self, other): if type(other) == SchoolBus: self.passengers, other.passengers[:] = (self.passengers[:] + other.passengers), [] return f"Passengers on Bus #{other.bus_num} have moved to Bus #{self.bus_num}" elif type(other) == Student: self.passengers = self.passengers[:] + [other.name] return f"{other.name} (student) is now on Bus #{self.bus_num}" else: print("Operation unsuccessful. Verify compatible types.") keyan = Student("Keyan", 17, True, 7, 10) ewingBus = SchoolBus(top_speed=90, passengers=["Ewing", "Bryant", "Avery", "Blake", "Hayden"]) jordanBus = SchoolBus(top_speed=90, passengers=["Jordan", "Other Jordan", "Jayden", "Aaron", "Natalie"]) print(ewingBus + keyan) print(ewingBus.passengers) print(ewingBus + jordanBus) print(ewingBus.passengers)
53439bc9fed95069408cec769fddd8fc2fc9376d
BryCant/Intro-to-Programming-MSMS-
/Chapter13.py
2,435
4.34375
4
# Exception Handling # encapsulation take all data associated with an object and put it in one class # data hiding # inheritance # polymorphism ; function that syntactically looks same is different based on how you use it """ # basic syntax try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except: # If any exception was raised, then execute this code block # catching specific exceptions try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except ExceptionName: # If ExceptionName was raise, then execute this block # catching multiple specific exceptions try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except Exception_one: # If Exception_one was raised, then execute this block except Exception_two: # If Exception_two was raised, then execute this block else: # If there was no exception, then execute this block # clean-up after exceptions (if you have code that you want to be executed even if exceptions occur) try: # Your normal code goes here. # Your code might include functions which might raise exceptions. # If an exception is raised, some of these statements might not be executed finally: # This block of code WILL ALWAYS execute, even if there are exceptions raised """ # example with some file I/O (great place to include exception handling try: # the outer try:except: block takes care of a missing file or the fact that the file can't be opened for writing f = open("my_file.txt", "w") try: # the inner: except: block protects against output errors, such as trying to write to a device that is full f.write("Writing some data to the file") finally: # the finally code guarantees that the file is closed properly, even if there are errors during writing f.close() except IOError: print("Error: my_file.txt does not exist or it can't be opened for output.") # as long as a function that is capable of handling an exception exists above where the exception is raised in the stack # the exception can be handled def main() A() def A(): B() def B(): C() def C(): # processes try: if condition: raise MyException except MyException: # what to do if this exception occurs
ec9dc44facac9d6f6bdda9f3eb7c178c0b67ff0f
iannase/win2k17
/cycles.py
508
3.796875
4
wholeString = input() shifter = "" stringList = [] stringSize = "" stringShift = "" shift = 0 size = 0 z = 0 for x in wholeString: if z == 0: stringSize += x if z == 1: stringList.append(x) if z == 2: stringShift+= x if x == " ": z += 1 size = int(stringSize) shift = int(stringShift) stringList.pop(size) for i in range(size): for i in range(shift): shifter = stringList[0] stringList.pop(0) stringList.insert(size,shifter) result = "" for x in stringList: result += x print(result)
2679e524fb70ea8bc6a8801a3a9149ee258d9090
daviscuen/Astro-119-hw-1
/check_in_solution.py
818
4.125
4
#this imports numpy import numpy as np #this step creates a function called main def main(): i = 0 #sets a variable i equal to 0 x = 119. # sets a variable x equal to 119 and the decimal makes it a float (do you need the 0?) for i in range(120): #starting at i, add one everytime the program gets to the end of the for loop if (i%2) == 0: #if the value of i divided by 2 is exactly 0, then do the below part x += 3.0 #resets the variable x to 3 more than it was before else: # if the above condition is not true, do what is below x -= 5.0 #resets the variable x to 5 less than it was before s = "%3.2e" % x #puts it in sci notation (need help with why) print(s) #prints the above string s if __name__ == "__main__": main()
d0da8ed0d77bc22e2b4212747ecbcf6c82b9a30c
mvinovivek/BA_Python
/Class_3/1_4_ValueError.py
303
3.671875
4
#Value error will be raised when you try to change the type of an argument with improper value #most common example of the value error is while converting string to int or float number=int("number") #The above statement will throw an error as "number" as a string cannot be considered as int or float
0d4aad51ef559c9bf11cd905cf14de63a6011457
mvinovivek/BA_Python
/Class_3/8_functions_with_return.py
982
4.375
4
#Function can return a value #Defining the function def cbrt(X): """ This is called as docstring short form of Document String This is useful to give information about the function. For example, This function computes the cube root of the given number """ cuberoot=X**(1/3) return cuberoot #This is returning value to the place where function is called print(cbrt(27)) #calling using a variable number=64 print("Cube root of {} is {}".format(number,cbrt(number))) #Mentioning Type of the arguments #Defining the function def cbrt(X: float) -> float: cuberoot=X**(1/3) return cuberoot #This is returning value to the place where function is called print(cbrt(50)) #Mutiple returns def calculation(X): sqrt=X**0.5 cbrt=X**(1/3) return sqrt,cbrt # print(calculation(9)) # values=calculation(9) # print(values) # values=calculation(9) # print(values[0]) # sqrt,cbrt=calculation(9) # print(sqrt,cbrt)
53cee6f939c97b0d84be910eee64b6e7f515b12f
mvinovivek/BA_Python
/Class_3/7_functions_with_default.py
680
4.1875
4
# We can set some default values for the function arguments #Passing Multiple Arguments def greet(name, message="How are you!"): print("Hi {}".format(name)) print(message) greet("Bellatrix", "You are Awesome!") greet("Bellatrix") #NOTE Default arguments must come at the last. All arguments before default are called positional arguments def greet(message="How are you!", name): #This will Throw error print("Hi {}".format(name)) print(message) #You can mix the positional values when using their name #Passing Multiple Arguments def greet(name, message): print("Hi {}".format(name)) print(message) greet( message="You are Awesome!",name="Bellatrix")
626da3ed48d7dabc2074e13c6c6fda948a5ab34c
mvinovivek/BA_Python
/Class_3/1_7_IndexError.py
327
3.953125
4
#index errors will be raised when you try to access an index which is not present in the list or tuple or array X=[1,2,3,4,5] print(X[41]) #in case of dictionaries it will be KeyError Person={ 'Name': 'Vivek', 'Company' : 'Bellatrix' } print(Person['Name']) #it will work print(Person['Age']) #it will throw KeyError
0eb58cd27ce6822be0c7dc2d66524bbd6a207659
mvinovivek/BA_Python
/Class_4/10_comparting_projectiles_class.py
2,365
3.90625
4
import numpy as np import matplotlib.pyplot as plt class projectile(): g=9.81 def __init__(self,launch_angle,launch_velocity): self.launch_angle=launch_angle self.launch_velocity=launch_velocity def duration(self): duration=2*self.launch_velocity*np.sin(np.radians(self.launch_angle))/self.g return duration def range_dist(self): range_dist=self.launch_velocity**2*np.sin(np.radians(2*self.launch_angle))/self.g return range_dist def ceiling(self): ceiling=((self.launch_velocity**2)*((np.sin(np.radians(self.launch_angle)))**2))/(2*self.g) return ceiling def coordinates(self): duration_val = self.duration() t=np.linspace(0,duration_val,100) x=self.launch_velocity*t*np.cos(np.radians(self.launch_angle)) y=(self.launch_velocity*t*np.sin(np.radians(self.launch_angle)))-(0.5*self.g*t**2) return x,y angle=20 velocity=50 our_projectile=projectile(angle,velocity) print("Range of projectile with V={} m/s,launched at {} degrees is {} m".format(velocity,angle, our_projectile.range_dist())) print("Ceiling of projectile with V={} m/s,launched at {} degrees is {} m".format(velocity,angle, our_projectile.ceiling())) print("Duration of projectile with V={} m/s,launched at {} degrees is {} s".format(velocity,angle, our_projectile.duration())) X,Y=our_projectile.coordinates() plt.plot(X,Y) plt.xlabel("Range, m") plt.ylabel("Altitude, m") plt.title("A projectile") plt.show() # launch_angles=[10,20,30] # launch_velocities=[50,100,150] # for angle in launch_angles: # for velocity in launch_velocities: # our_projectile=projectile(angle,velocity) # # print("Range of projectile with V={} m/s,launched at {} degrees is {} m".format(velocity,angle, our_projectile.range_dist())) # # print("Ceiling of projectile with V={} m/s,launched at {} degrees is {} m".format(velocity,angle, our_projectile.ceiling())) # # print("Duration of projectile with V={} m/s,launched at {} degrees is {} s".format(velocity,angle, our_projectile.duration())) # # print('\n\n') # x,y=our_projectile.coordinates() # plt.plot(x,y,label="V= {}, T={}".format(angle,velocity)) # plt.title("Comparing Projectiles") # plt.xlabel("Range, m") # plt.ylabel("Altitude, m") # plt.legend() # plt.show()
3cb1bc2560b5771e4c9ec69d429fcfd9c0eadd2c
mvinovivek/BA_Python
/Class_2/7_for_loop_2.py
1,009
4.625
5
#In case if we want to loop over several lists in one go, or need to access corresponding #values of any list pairs, we can make use of the range method # # range is a method when called will create an array of integers upto the given value # for example range(3) will return an array with elements [0,1,2] #now we can see that this is an array which can act as control variables #Combining this with the len function, we can iterate over any number of lists #Simple range example numbers=[1,2,3,4,6,6,7,8,9,10] squares=[] cubes=[] for number in numbers: squares.append(number**2) cubes.append(number**3) for i in range(len(numbers)): print("The Square of {} is {}".format(numbers[i], squares[i])) for i in range(len(numbers)): print("The Cube of {} is {}".format(numbers[i], cubes[i])) #Finding sum of numbers upto a given number number = 5 sum_value=0 for i in range(number + 1): sum_value = sum_value + i print("The sum of numbers upto {} is {}".format(number,sum_value))
3cbfde72e5c26d2a8f498273e1e11ce7c8d65fe1
mvinovivek/BA_Python
/Class_5/7_widgets_radio_use.py
855
3.71875
4
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons Xvals=np.linspace(0,2*np.pi,50) Yvals=np.sin(Xvals) Zvals=np.cos(Xvals) #Creating the Plot # Plotting fig = plt.figure() ax = fig.subplots() plt.subplots_adjust(right=0.8) plt.title("Click the Radio Button to Change the Colors") ax_color = plt.axes([0.81, 0.5, 0.18, 0.25]) color_button = RadioButtons(ax_color, ['sin', 'cos'],[True, False], activecolor= 'k') # function for changing the plot color def color(curve): if curve=="sin": ax.clear() ax.plot(Xvals,Yvals) ax.set_title("Sine Curve") fig.canvas.draw() elif curve =="cos": ax.clear() ax.plot(Xvals,Zvals) ax.set_title("Cos Curve") fig.canvas.draw() else: pass color_button.on_clicked(color) plt.show()
c9a6c2f6b8f0655b3e417057f7e52015794d26d6
316126510004/ostlab04
/scramble.py
1,456
4.40625
4
def scramble(word, stop): ''' scramble(word, stop) word -> the text to be scrambled stop -> The last index it can extract word from returns a scrambled version of the word. This function takes a word as input and returns a scrambled version of it. However, the letters in the beginning and ending do not change. ''' import random pre, suf = word[0], word[stop:] word = list(word) mid_word = word[1:stop] random.shuffle(mid_word) word = pre + ''.join(mid_word) + suf return word def unpack_and_scramble(words): ''' unpack_and_scramble(words) words -> a list of words to be scrambled. returns a list of scrambled strings This function unpacks all the words and checks if len(word) < 3 If true then it scrambles the word Now, it will be appended to a new list ''' words = words.split() scrambled_words = [] for word in words: if len(word) <3: scrambled_words.append(word) continue if word.endswith((',', '?', '.', ';', '!')): stop = -2 else: stop = -3 scrambled_word = scramble(word, stop) scrambled_words.append(scrambled_word) return ' '.join(scrambled_words) file_name = input('Enter file name:') try: file = open(file_name, 'r') new_file = file.name + 'Scrambled' words = file.read() file.close() scrambed_words = unpack_and_scramble(words) file_name = open(new_file, 'w') file_name.write(scrambed_words) file_name.close() except OSError as ose: print('Please enter file name properly')
c456b13bb5316097a6856510e0e0140765216f18
Rahulllkumarrr/Simple-Program
/Cut the sticks.py
2,366
3.65625
4
''' Cut the stick ------------- You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them. Given the lengths of n sticks, print the number of sticks that are left before each iteration until there are none left. Note: Before each iteration you must determine the current shortest stick. ----- Input Format ------------- The first line contains a single integer n . The next line contains n space-separated integers: a0, a1,...an-1, where ai represents the length of the ith stick in array arr. Output Format -------------- For each operation, print the number of sticks that are cut, on separate lines. Sample Input 0 6 5 4 4 2 2 8 Sample Output 0 6 4 2 1 X--------X----------X--------X---------X----------X-----------------X----------X Sample Input 1 8 1 2 3 4 3 3 2 1 Sample Output 1 8 6 4 1 ''' def cutTheSticks(arr): count1 = 0 arr.sort() left = len(arr) list = [] while left > 0: mini = min(arr) if left > 0: list.append(left) count1 = arr.count(mini) for i in range(len(arr)): arr[i] = arr[i] - mini for i in range(count1): arr.pop(0) left = len(arr) return list if __name__ == "__main__": n = int(input().strip()) arr = list(map(int, input().strip().split(' '))) result = cutTheSticks(arr) print("\n".join(map(str, result)))
a7a2abaa6a70a9da4f81c1c5a9d7d231e9551434
Rahulllkumarrr/Simple-Program
/diagonal Difference.py
492
3.796875
4
def diagonalDifference(a): right,left=0,0 n=len(a) l=n-1 r=0 for i in range(n): right=right+(a[r][r]) left=left+a[r][l] r+=1 l+=-1 difference=abs(right-left) return difference if __name__ == "__main__": n = int(input().strip()) a = [] for a_i in range(n): a_t = [int(a_temp) for a_temp in input().strip().split(' ')] a.append(a_t) result = diagonalDifference(a) print(result)
476f71e3734a9ab494dd28662b5ceac58f321ffc
TundraStorm/raticus
/MyGame/on_key_press.py
555
3.671875
4
import arcade def on_key_press(self, key, modifiers): """Called whenever a key is pressed. """ # If the player presses a key, update the speed if key == arcade.key.UP: self.player_sprite.change_y = 7 #self.player_sprite.change_y = -MOVEMENT_SPEED*0.5 elif key == arcade.key.DOWN: self.player_sprite.change_y = 0#-MOVEMENT_SPEED elif key == arcade.key.LEFT: self.player_sprite.change_x = - self.movement_speed elif key == arcade.key.RIGHT: self.player_sprite.change_x = self.movement_speed
d24514f8bed4e72aaaee68ae96076ec3921f5898
ChanghaoWang/py4e
/Chapter9_Dictionaries/TwoIterationVariable.py
429
4.375
4
# Two iteration varibales # We can have multiple itertion variables in a for loop name = {'first name':'Changhao','middle name':None,'last name':'Wang'} keys = list(name.keys()) values = list(name.values()) items = list(name.items()) print("Keys of the dict:",keys) print("Values of the dict:",values) print("Items of the dict:",items) for key,value in items: # Two Itertion Values print('Keys and Values of the dict:',key)
d22d71b73ef371210d49a71f2abb69383e97cca8
ChanghaoWang/py4e
/Chapter2/assignment2_3.py
260
3.78125
4
inp_hour=float(input('Enter the hour:')) inp_rate=float(input('Enter the rate per hour:')) if inp_hour > 40: inp_rate_new=1.5*inp_rate grosspay = inp_rate_new*(inp_hour-40)+40*inp_rate else: grosspay=inp_hour*inp_rate print('Grosspay is',grosspay)
47675250b07dd0f5a0c3eae348b35ee4885a04a2
ChanghaoWang/py4e
/Chapter10_Tuples/Commonwords.py
671
3.921875
4
#Count words Chapter 10 Page 131 import string inp = input("Please enter the filename: ") if len(inp) < 1: inp = 'romeo-full.txt' try: fhand = open(inp) except: print("Cannot open the file:",inp) quit() count_dict = dict() for line in fhand: line = line.translate(str.maketrans('','',string.punctuation)) line = line.lower() words = line.split() for word in words: count_dict[word] = count_dict.get(word,0) + 1 count_list = list() for (key,value) in list(count_dict.items()): count_list.append((value,key)) count_list.sort(reverse = True) print('The most common word is',count_list[0][1],"It appears",count_list[0][0],'times')
3cae3e36c80ac6d2040d872705091194edc954af
ChanghaoWang/py4e
/Chapter8_Lists/modify.py
612
4.09375
4
# List modify #It's important to remember which methods modify the list or create a new one def delete_head(t): del t[0] def pop_head(t): t.pop(0) def add_append(t1,t2): t1.append(t2) def add(t1,t2): return t1 + t2 def delete_head_alternative(t): return t[1:] letters = ['a',1,'b',2,'c',3] delete_head(letters) print(letters) pop_head(letters) print(letters) letters_new = ['Another',1] add_append(letters,letters_new) print(letters) letters_new_1 = add(letters,letters_new) print('Another',letters_new_1) letters_delete = delete_head_alternative(letters) print('Delete head',letters_delete)
6d325039a3caa4c331ecc6fa6bb058ff431218f8
ChanghaoWang/py4e
/Chapter8_Lists/note.py
921
4.21875
4
# Chapter 8 Lists Page 97 a = ['Changhao','Wang','scores',[100,200],'points','.'] # method: append & extend a.append('Yeah!') #Note, the method returns None. it is different with str a.extend(['He','is','so','clever','!']) # method : sort (arranges the elements of the list from low to high) b= ['He','is','clever','!'] b.sort() print(b) # method : delete (pop) retrus the element we removed. c = ['a',1,'c'] x = c.pop(0) print('After remove:',c) print('What we removed is:',x) # method : del c = ['a',1,'c'] del c[0] print(c) # method : remove attention: it can only remove one element c = ['a',1,'c',1] c.remove(1) print(c) # convert string to List d = 'Changhao' e = list(d) print(e) f = 'Changhao Wang' g = f.split() print(g) # string method : split() s = 'spam-spam-spam' s_new = s.split('-') print(s_new) # convert lists to string t = ['pining','for','the','fjords'] delimiter = ' ' t_str = delimiter.join(t) print(t_str)
4be436e6a4b5aff0bcdd99dded5d1a2c3ce0763e
ChanghaoWang/py4e
/Chapter11_Expressions/Exercise1.py
329
3.921875
4
# Exercise 1 Chapter 11 Page 149 import re inp = input("Enter a regular expression: ") if len(inp) < 1: inp = '^From:' fhand = open("mbox.txt") count = 0 for line in fhand: line = line.strip() words = re.findall(inp,line) if len(words) > 0: count += 1 print("mbox.txt had",count,"lines that matched",inp)
c2b24f3f587202bdea4e6ec7895d06f70e9c3d04
celine5/GUVIrepo
/even.py
118
4.25
4
num=int(input("enter a number:")) if(num%2)==0: print("{0} is even".fomat(num)) else: print("{0} is odd".format(num))
802707f723581bda40c9d53b34d12858a58592d5
celine5/GUVIrepo
/vowelc.py
245
3.859375
4
original =input('Enter a character:') character= original.lower() first =character[0] if len(original) > 0 and original.isalpha(): if first in 'aeiou': print("Vowel") else: print("Consonant") else: print ("invalid")
1f36f982a91c6257911b91f1f5005d900fac104c
junbeomLim/Algorithm
/BOJ/backjoon 2750.py
129
3.59375
4
N = int(input()) n = [0 for i in range(N)] for i in range(N): n[i] = int(input()) n.sort() for i in range(N): print(n[i])
d21ea5dda881f239defc04d28018acc89ac99c86
ArpitaBawgi/Devops-Training
/third.py
274
3.984375
4
name='' condition=True while(condition): print('who are you') name=input() if(name!='joe'): continue else: print("Hello Joe, What is password?(it is fish)"); password=input(); if(password =='swoardfish'): #condition=False; break; print('Access Granted')
a632cf8c425a392504331ee4413aeb4727ea4318
wesyang/sudoku_solver
/misc/findIslands.py
1,606
3.625
4
class Solution(object): def printMap(self, map): for r in map: for c in r: print(f'{c} ', end='') print() print('-----------------') def checkAndMarkIsland(self, map, x, y, cc, rc): if x < 0 or y < 0: return if x >= cc or y >= rc: return if map[y][x] == 1: map[y][x] = 'x' self.markIsland(map, x, y, cc, rc) def markIsland(self, map, x, y, cc, rc): self.checkAndMarkIsland(map, x - 1, y - 1, cc, rc) self.checkAndMarkIsland(map, x - 1, y, cc, rc) self.checkAndMarkIsland(map, x - 1, y + 1, cc, rc) self.checkAndMarkIsland(map, x, y - 1, cc, rc) self.checkAndMarkIsland(map, x, y + 1, cc, rc) self.checkAndMarkIsland(map, x + 1, y - 1, cc, rc) self.checkAndMarkIsland(map, x + 1, y, cc, rc) self.checkAndMarkIsland(map, x + 1, y + 1, cc, rc) def findIslands(self, map): pass if not map: return 0 rc = len(map) cc = len(map[0]) print(rc, cc) total = 0 for y in range(rc): for x in range(cc): if map[y][x] == 1: map[y][x] = 'x' self.markIsland(map, x, y, cc, rc) self.printMap(map) total += 1 return total if __name__ == "__main__": solution = Solution() map = [ [1, 0, 0, 0, 1], [1, 0, 1, 0, 1], [1, 0, 0, 0, 0], [1, 1, 0, 1, 1], ] solution.printMap(map) print(solution.findIslands(map))
63155a1d3a461b958561d57c38adbea2c8be1e26
wesyang/sudoku_solver
/misc/getSqrt.py
1,394
3.65625
4
class Solution(object): @staticmethod def getSqrt(min, max, x): while (True): mid = int((max - min +1) / 2) + min mm = mid * mid #print (min, mid, max, mm, x) if mm == x: return mid elif mm < x: nextSqrt = (mid + 1) * (mid + 1) if nextSqrt == x: return mid + 1 elif nextSqrt > x: return mid min = mid else: prevSprt = (mid - 1) * (mid - 1) if prevSprt <= x: return mid - 1 max = mid def mySqrt(self, x): """ :type x: int :rtype: int """ return Solution.getSqrt(0, 2 ** 32, x) @staticmethod def checkSqrt(min, max, x): while (max >= min ): mid = int((max - min +1) / 2) + min mm = mid * mid print (min, mid, max, mm, x) if mm == x: return True elif mm < x: min = mid +1 else: max = mid -1 return False def isPerfectSquare(self, x): """ :type x: int :rtype: int """ return Solution.checkSqrt(0, 2 ** 32, x) if __name__ == "__main__": solution = Solution() print(solution.isPerfectSquare(25))
c76f613f2855a56d738d64439a2d857d1ca15781
jayashreemohan29/pmemkv-testing
/count_ops.py
882
3.640625
4
#!/usr/bin/env python import getopt import sys def main(): #input arg : file name if (len(sys.argv) != 2): print("Please input log file") exit(1) log_file = sys.argv[1] count = 0 count_fence = 0 count_flush = 0 count_store = 0 count_others = 0 operations = open(log_file).read().split("|") for op in operations: count+=1 op_value = op.split(";")[0] if (op_value == "FENCE"): count_fence += 1 elif (op_value == "STORE"): count_store += 1 elif (op_value == "FLUSH"): count_flush += 1 else: count_others +=1 #print(str(op)) print("\n----- OP SUMMARY --------\n") print("\n Total Ops : " + str(count)) print("\n Total store ops : " + str(count_store)) print("\n Total flush ops : " + str(count_flush)) print("\n Total fence ops : " + str(count_fence)) print("\n Other ops : " + str(count_others)) if __name__ == "__main__": main()
007064524296a592bf238f413029a41a12bafc0b
bharath144/PythonWorkshop
/sorting/bubble_sort.py
1,481
3.703125
4
import random import time input_a = [x for x in range(0, 1000)] input_b = random.sample(input_a, 10) input_c = input_b.copy() def iterative_sort(unsorted_list): print(unsorted_list) for i in range(0, len(unsorted_list)): # Improved exit condition, if there are no swaps, all numbers are sorted swapped = False for j in range(0, len(unsorted_list) - i - 1): if unsorted_list[j] > unsorted_list[j+1]: # The actual in-place swap, a semantic that's unique to Python. # This is similar to temp = x, x = y, y = temp unsorted_list[j], unsorted_list[j+1] = \ unsorted_list[j+1], unsorted_list[j] print(" " + str(unsorted_list)) # Indicates if we swapped something swapped = True print(unsorted_list) if not swapped: break def recurseive_sort(unsorted_list): print(unsorted_list) for i, num in enumerate(unsorted_list): try: if unsorted_list[i + 1] < num: # Swap unsorted_list[i] = unsorted_list[i + 1] unsorted_list[i + 1] = num print(" " + str(unsorted_list)) recurseive_sort(unsorted_list) except IndexError: print(unsorted_list) pass return unsorted_list recurseive_sort(input_b) print("") print("") print("") print("") iterative_sort(input_c)
3422c8df4de8e5e1bf18e154be725f7879f797c5
MaxMcCarthy/Recommender-System
/Scraper/web_scraper.py
6,479
3.71875
4
from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import csv # with help from: # https://realpython.com/python-web-scraping-practical-introduction/ def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None """ try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: print('Error during requests to {0} : {1}'.format(url, str(e))) return None def is_good_response(resp): """ Returns true if the response seems to be HTML, false otherwise """ content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1) def scrape_academic(): headings = ['CS', 'STAT', 'LAS', 'ENG', 'GRAD'] urls = ['http://calendars.illinois.edu/list/504', 'https://calendars.illinois.edu/list/1439', "http://calendars.illinois.edu/list/1249", 'http://calendars.illinois.edu/list/2568', 'http://calendars.illinois.edu/list/3695'] count = 0 for url in urls: base_url = 'http://calendars.illinois.edu' html = simple_get(url) html = BeautifulSoup(html, 'html.parser') for p in html.select('ul'): for h3 in p.select('h3'): for a in h3.select('a'): print(a['href']) print(a.text) print('') event = simple_get(base_url + a['href']) event = BeautifulSoup(event, 'html.parser') for dd in event.findAll("section", {"class": "detail-content"}): for desc, info in zip(dd.select('dt'), dd.select('dd')): print("{} : {}\n".format(desc.text, info.text)) for summary in dd.findAll('dd', {"class": 'ws-description'}): print(summary.text.strip()) print('\n\n\n') print(count) count += 1 def scrape_arc(): urls = ['http://calendars.illinois.edu/list/7'] count = 0 for url in urls: base_url = 'http://calendars.illinois.edu' html = simple_get(url) html = BeautifulSoup(html, 'html.parser') for p in html.select('ul'): for h3 in p.select('h3'): for a in h3.select('a'): print(a['href']) print(a.text) print('') event = simple_get(base_url + a['href']) event = BeautifulSoup(event, 'html.parser') for dd in event.findAll("section", {"class": "detail-content"}): for desc, info in zip(dd.select('dt'), dd.select('dd')): print("{} : {}\n".format(desc.text, info.text)) for summary in dd.findAll('dd', {"class": 'ws-description'}): print(summary.text.strip()) print('\n\n\n') print(count) count += 1 def scrape_url(urls): count = 0 with open('events.csv', 'a+') as csvfile: headers = ['doc_id', 'title', 'url', 'event_type', 'sponsor', 'location', 'date', 'speaker', 'views', 'originating_calendar', 'topics', 'cost', 'contact', 'e-mail', 'phone', 'registration', 'description'] writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() base_url = 'http://calendars.illinois.edu' for url in urls: html = simple_get(url) html = BeautifulSoup(html, 'html.parser') for p in html.select('ul'): for h3 in p.select('h3'): row = {'doc_id': 'NA', 'title': 'NA', 'url': 'NA', 'event_type': 'NA', 'sponsor': 'NA', 'location': 'NA', 'date': 'NA', 'speaker': 'NA', 'views': 'NA', 'originating_calendar': 'NA', 'topics': 'NA', 'cost': 'NA', 'contact': 'NA', 'e-mail': 'NA', 'phone': 'NA', 'registration': 'NA', 'description': 'NA'} for a in h3.select('a'): row['doc_id'] = count row['title'] = a.text row['url'] = base_url + a['href'] event = simple_get(base_url + a['href']) event = BeautifulSoup(event, 'html.parser') for dd in event.findAll("section", {"class": "detail-content"}): for desc, info in zip(dd.select('dt'), dd.select('dd')): # print("{} : {}\n".format(desc.text, info.text)) name = desc.text.lower().strip().replace(" ", "_") if name == 'topic': name += 's' row[name] = info.text description = '' for summary in dd.findAll('dd', {"class": 'ws-description'}): description += summary.text.strip() # print(summary.text.strip()) if description != '': row['description'] = description writer.writerow(row) # print('\n\n\n') print(count) count += 1 if __name__ == '__main__': # optional smaller calendars # scrape_academic() fitness_classes = 'https://calendars.illinois.edu/list/4046' krannert_perf = 'https://calendars.illinois.edu/list/33' campus_rec = 'http://calendars.illinois.edu/list/2628' student_affairs = 'http://calendars.illinois.edu/list/1771' master = 'http://calendars.illinois.edu/list/7' scrape_url([fitness_classes, krannert_perf, campus_rec, student_affairs, master]) # scrape_url(krannert_perf) # scrape_url(campus_rec) # scrape_url(student_affairs) # scrape_url(master)
b2e057bd9d63ba6da9a755f2c879bc58ae65086b
tomcat1969/CodingDojo_python_stack
/python/fundamentals/forloopbasic2.py
1,654
3.953125
4
# def biggie_size(list): # for i in range(len(list)): # if list[i] > 0: # list[i] = "big" # return list # print(biggie_size([-1,3,5,-5])) # def count_positives(list): # count = 0 # for i in range(len(list)): # if list[i] > 0: # count = count + 1 # list[len(list)-1] = count # return list # print(count_positives([1,6,-4,-2,-7,-2])) # def sum_total(list): # sum = 0 # for i in range(len(list)): # sum = sum + list[i] # return sum # print(sum_total([1,2,3,4])) # def average(list): # sum = 0 # for i in range(len(list)): # sum = sum + list[i] # return sum / len(list) # print(average([1,2,3,4])) # def length(list): # return len(list) # print(length([])) # def minimum(list): # if len(list) == 0: # return False # global_min = list[0] # for i in range(len(list)): # if list[i] < global_min: # global_min = list[i] # return global_min # print(minimum([37,2,1,-9])) # def maximum(list): # if len(list) == 0: # return False # global_max = list[0] # for i in range(len(list)): # if list[i] > global_max: # global_max = list[i] # return global_max # print(maximum([37,2,1,-9])) # def ultimate_analysis(list): # result = {} # result['sumTotal'] = sum_total(list) # result['average'] = average(list) # result['minimum'] = minimum(list) # result['maximum'] = maximum(list) # result['length'] = length(list) # return result # print(ultimate_analysis([37,2,1,-9])) def reverse_list(list): l = 0 r = len(list) - 1 while l < r: temp = list[l] list[l] = list[r] list[r] = temp l = l + 1 r = r - 1 return list print(reverse_list([37,2,1,-9]))
d593ffafc59015480c713c213b59f6304914d660
Ayush10/python-programs
/vowel_or_consonant.py
1,451
4.40625
4
# Program to check if the given alphabet is vowel or consonant # Taking user input alphabet = input("Enter any alphabet: ") # Function to check if the given alphabet is vowel or consonant def check_alphabets(letter): lower_case_letter = letter.lower() if lower_case_letter == 'a' or lower_case_letter == 'e' or lower_case_letter == 'i' or lower_case_letter == 'o' \ or lower_case_letter == 'u': # or lower_case_letter == 'A' or lower_case_letter == 'E' or lower_case_letter == \ # 'I' or lower_case_letter == 'U': return "vowel" else: return "consonant" # Checking if the first character is an alphabet or not: if 65 <= ord(alphabet[0]) <= 90 or 97 <= ord(alphabet[0]) <= 122: # Checking if there are more than 1 characters in the given string. if len(alphabet) > 1: print("Please enter only one character!") print("The first character {0} of the given string {1} is {2}.".format(alphabet[0], alphabet, check_alphabets(alphabet[0]))) # If only one character in the given string. else: print("The given character {0} is {1}.".format(alphabet, check_alphabets(alphabet))) # If the condition is not satisfied then returning the error to the user without calculation. else: print("Please enter a valid alphabet. The character {0} is not an alphabet.".format(alphabet[0]))
2676477d211e0702d1c44802f9295e8457df21a8
Ayush10/python-programs
/greatest_of_three_numbers.py
492
4.3125
4
# Program to find greatest among three numbers # Taking user input a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = int(input("Enter third number: ")) # Comparison Algorithm and displaying result if a > b > c: print("%d is the greatest number among %d, %d and %d." % (a, a, b, c)) elif b > a > c: print("%d is the greatest number among %d, %d and %d." % (b, a, b, c)) else: print("%d is the greatest number among %d, %d and %d." % (c, a, b, c))
172102809e9f1fc0ebf8516b78f7dab417f05e5e
ecarlos09/procedural-python-exercises
/name_generator/penguin_name.py
423
3.5
4
penguin_converter = { "January": "Mumble", "February": "Squeak", "March": "Skipper", "April": "Gloria", "May": "Kowalski", "June": "Rico", "July": "Private", "August": "King", "September": "Pingu", "October": "Feathers McGraw", "November": "Chocolatey", "December": "Ice Cold" } def user_penguin(birth_month): penguin_name = penguin_converter[birth_month] return penguin_name
82b3b3358fc08521b6e714a7d1b5cf2c40aee47c
MiriSilva/Avaliacao1
/Questao2.py
354
4.09375
4
n1 = int(input("informe um numero inteiro: ")) n2 = int(input("informe um numero inteiro: ")) n3 = float(input("informe um numero real: ")) print ("o produto do dobro do primeiro com metade do segundo è :", n1*2*(n2/2)) print ("a soma do triplo do primeiro com o terceiro é:", (n1*3)+n3 ) print ("o terceiro elevado ao cubo é: ", (n3**3))
a42ff81b035de48e6628dbac29315ae1e2e78bb1
MiriSilva/Avaliacao1
/Questao4.py
363
3.828125
4
x = float(input("Informe quanto ganha por hora:")) y = float(input("Informe quantas horas trabalhadas no mês:")) SB = (x*y) IR = SB * 0.11 INSS = SB* 0.08 SD = SB*0.05 SL = SB-(IR+INSS+SD) print("Salário Bruto : R$",SB) print("IR (11%) : R$",IR ) print("INSS (8%) : R$",INSS ) print("Sindicato ( 5%) : R$",SD ) print("Salário Liquido : R$",SL )
3fefcd97afaccac58e7c18e5303c44d2c11699a0
hendy3/A-beautiful-code-in-Python
/Teil_15_Sudoku_Algorithm_x.py
2,701
3.8125
4
#!/usr/bin/env python3 # Author: Ali Assaf <[email protected]> # Copyright: (C) 2010 Ali Assaf # License: GNU General Public License <http://www.gnu.org/licenses/> from itertools import product import time def solve_sudoku(size, grid): """ An efficient Sudoku solver using Algorithm X. """ R, C = size N = R * C X = ([("rc", rc) for rc in product(range(N), range(N))] + [("rn", rn) for rn in product(range(N), range(1, N + 1))] + [("cn", cn) for cn in product(range(N), range(1, N + 1))] + [("bn", bn) for bn in product(range(N), range(1, N + 1))]) Y = dict() for r, c, n in product(range(N), range(N), range(1, N + 1)): b = r // R * R + c // C # Box number Y[(r, c, n)] = [ ("rc", (r, c)), ("rn", (r, n)), ("cn", (c, n)), ("bn", (b, n))] X, Y = exact_cover(X, Y) for i, row in enumerate(grid): for j, n in enumerate(row): if n: select(X, Y, (i, j, n)) for solution in solve(X, Y, []): for (r, c, n) in solution: grid[r][c] = n yield grid def exact_cover(X, Y): X = {j: set() for j in X} for i, row in Y.items(): for j in row: X[j].add(i) return X, Y def solve(X, Y, solution): if not X: yield list(solution) else: c = min(X, key=lambda c: len(X[c])) for r in list(X[c]): solution.append(r) cols = select(X, Y, r) for s in solve(X, Y, solution): yield s deselect(X, Y, r, cols) solution.pop() def select(X, Y, r): cols = [] for j in Y[r]: for i in X[j]: for k in Y[i]: if k != j: X[k].remove(i) cols.append(X.pop(j)) return cols def deselect(X, Y, r, cols): for j in reversed(Y[r]): X[j] = cols.pop() for i in X[j]: for k in Y[i]: if k != j: X[k].add(i) def string2grid(aufgabe): grid, zeile = [], [] for i, char in enumerate(aufgabe): if char == '.': zahl = 0 else: zahl = int(char) zeile.append(zahl) if (i+1) % 9 == 0: grid.append(zeile) zeile = [] return grid lösungen = [] start1 = time.perf_counter() with open('Teil_15_Sudoku_2365_hard.txt') as f: for i, zeile in enumerate(f): zeile = zeile.rstrip() start = time.perf_counter() solutions = solve_sudoku((3, 3), string2grid(zeile)) for solution in solutions: pass end = time.perf_counter() lösungen.append((end-start, i+1)) summe = sum(x for x, y in lösungen) print(f'Lösung von {i+1:,} Sudokus in {summe:,.2f} Sek. (durchschn. {summe/len(lösungen)*1000:,.2f} Millisek.)\n') lösungen.sort(reverse=True) for i in range(10): zeit, nr = lösungen[i] print(f'Nr. {nr:5d} in {zeit*1000:5,.0f} Millisek.')
e50f8e37210054df2e5c54eb55e7dee381a91aff
super468/leetcode
/python/src/BestMeetingPoint.py
1,219
4.15625
4
class Solution: def minTotalDistance(self, grid): """ the point is that median can minimize the total distance of different points. the math explanation is https://leetcode.com/problems/best-meeting-point/discuss/74217/The-theory-behind-(why-the-median-works) the more human language version is that there are two groups of people, it will decrease the distance if you put the point closer to the group with more people. At end of the day, the two sides will be equal. :type grid: List[List[int]] :rtype: int """ list_y = [] list_x = [] for row in range(0, len(grid)): for col in range(0, len(grid[row])): if grid[row][col] == 1: list_y.append(row) list_x.append(col) list_y.sort() list_x.sort() median_y = list_y[int(len(list_y) / 2)] median_x = list_x[int(len(list_x) / 2)] sum_y = 0 for y in list_y: sum_y += median_y - y if median_y > y else y - median_y sum_x = 0 for x in list_x: sum_x += median_x - x if median_x > x else x - median_x return sum_x + sum_y
71c87f644ac21e84586fa2fcb51e9c160151c6a7
super468/leetcode
/python/src/FlipGameII.py
749
3.734375
4
""" the basic idea is that track every movement of the first player, if the other player can not make a movement, then movement the first player made is a winning movement. the optimization is to use memorization to memorize the string state that we have seen. this is a backtracking problem with memorization optimization """ class Solution1: mem = {} def canWin(self, s): if s not in self.mem: self.mem[s] = any(s[i:i+2]=='++' and not self.canWin(s[:i]+'--'+s[i+2:]) for i in range(len(s)-1)) return self.mem[s] class Solution2(object): def canWin(self, s): for i in range(len(s)-1): if s[i]=='+' and s[i+1]=='+' and not self.canWin(s[:i]+'--'+s[i+2:]): return True return False
3228d9c857bd5e39ca56b0d8d5f4f43b8c8f8d5c
scotchka/scotchka.github.io
/2018/06/16/balance_brackets.py
821
3.578125
4
import inspect BRACKETS = {")": "(", "]": "[", "}": "{"} def _stack(chars): """Push/pop frames to/from call stack.""" while chars: char = chars.pop(0) if char in BRACKETS.values(): _stack(chars) # push elif char in BRACKETS: previous = inspect.stack()[1] if ( previous.function != "_stack" or previous.frame.f_locals["char"] != BRACKETS[char] ): raise IndexError return # pop if inspect.stack()[1].function == "_stack": # check no brackets remain raise IndexError def is_balanced(string): """Check whether brackets in given string balanced.""" try: _stack(list(string)) except IndexError: return False else: return True
cdccb6138c604da36be9d9b97d65e0270bc57cb8
monicadsong/matrix_factorization_mp
/test_multiprocessing.py
3,289
3.5625
4
import multiprocessing from multiprocessing import pool print("cpu count: ", multiprocessing.pool.cpu_count()) import os, time # g_cnt is not shared with each worker def test_process_with_global_variable(): g_cnt = 4 def worker(idx, data, g_cnt): global g_cnt g_cnt += 1 time.sleep(1) print("worker", idx, g_cnt, data) return g_cnt #i is in another virtual memory space for i in range(5): p = multiprocessing.Process(target=worker, args=(i, "pp", g_cnt) ) p.start() #p.join() #all processes have ended print("g_cnt: ", g_cnt) # show several processes run in parallel by pool of processes # does not work yet class XY(): def __init__(self, x, y): self.x = x self.y = y # g_v is not reliable in this case g_v = 4 g_lock = multiprocessing.Lock() def square(d): # print 'module name:', __name__ # if hasattr(os, 'getppid'): # print 'parent process:', os.getppid() # print 'process id:', os.getpid() global g_v with g_lock: #print(g_v) g_v += 1 return d.x*d.x + d.y def test_process_pool_map(): pool = multiprocessing.Pool(processes=multiprocessing.pool.cpu_count()) print('Starting run at ' + time.strftime('%Y-%m-%d-%H:%M:%S', time.gmtime())) tot = 0 iter_cnt = 10000 proc_cnt = 16 for j in xrange(iter_cnt): dl = [XY(1.1111113+i,2.133+j) for i in xrange(proc_cnt)] sqr = pool.map(square, dl) tot += sum(sqr) print(tot) print('Ending run at ' + time.strftime('%Y-%m-%d-%H:%M:%S', time.gmtime())) def test_shared_class(): class SharedClass(): def __init__(self): self.queue = multiprocessing.Queue() self.lock = multiprocessing.Lock() self.process_cnt = 2 self.data = 5.1111 def _process(self, idx): max_cnt = 20 cnt = 0 while cnt < max_cnt: with self.lock: s = "{} + {}".format(idx, cnt) self.queue.put([s, self.data]) cnt += 1 def run(self): pool = [] for i in range(self.process_cnt): self.data += i p = multiprocessing.Process(target=self._process, args=(i,) ) p.start() pool.append(p) for p in pool: p.join() while not self.queue.empty(): d = self.queue.get() print(d) s = SharedClass() s.run() # send back message to parent by pipe def test_shared_by_pipe(): def send_by_pipe(conn): conn.send([42, None, 'hello']) conn.close() parent_conn, child_conn = multiprocessing.Pipe() p = multiprocessing.Process(target=send_by_pipe, args=(child_conn,)) p.start() print parent_conn.recv() p.join() # synchronization among processes def test_locked_print(): def locked_print(lock, i): with lock: print('hello world', i) print('hello world', i+100) time.sleep(0.1) print('hello world', i+200) print('hello world', i+300) l = multiprocessing.Lock() pool = [] for i in range(50): p = multiprocessing.Process(target=locked_print, args=(l, i) ) pool.append(p) p.start() for p in pool: p.join() # python documentation have very good examples for addtional features #test_process_pool_map() # test_locked_print() # test_shared_by_pipe() test_process_with_global_variable() # test_shared_class()
a5333df631bfbbc3f2ab5e6f8631eb7cb17611f1
PanchoF1/56107-Francisco-Saldana
/Clase05 Calculadora/calculadora_test.py
1,052
3.546875
4
import unittest from clases import Calculator class TestCalculador(unittest.TestCase): def resul_calculator_1_add_1_(self): calc = Calculator() calc.ingresar('1') calc.ingresar('+') calc.ingresar('1') calc.ingresar('=') self.assertEqual(calc.display(),'2') def resul_calculator_2_rest_1_(self): calc = Calculator() calc.ingresar('2') calc.ingresar('-') calc.ingresar('1') calc.ingresar('=') self.assertEqual(calc.display(),'1') def resul_calculator_2_x_2_(self): calc = Calculator() calc.ingresar('2') calc.ingresar('*') calc.ingresar('2') calc.ingresar('=') self.assertEqual(calc.display(),'4') def resul_calculator_10_div_5_(self): calc = Calculator() calc.ingresar('10') calc.ingresar('/') calc.ingresar('5') calc.ingresar('=') self.assertEqual(calc.display(),'2') if __name__ == "__main__": unittest.main()
3da888a1d429023b69d7e4efd7e4f7d6909e3f75
afterthought325/cp_lab
/atm_machine-0.5.py
3,095
3.84375
4
################################################################################ # Name: Chaise Farrar Date Assigned:10/16/2014 # # Partner: Rebecca Siciliano # # Course: CSE 1284 Sec 10 Date Due: 10/16/2014 # # File name:ATM Machine # # Program Description: Simulates an ATM experiance, from logging in with # # a pin to checking acount balance # ################################################################################ import getpass def main(): checking_balance = 50000 saving_balance = 10000 pin = int(getpass.getpass('\nHello! Welocome! Please enter your four digit PIN: ')) while pin == 7894: while True: try: choose = int(input('\n1. Inquiry \n'+ '2. Deposit to checking \n' + '3. Deposit to savings \n' + '4. Withdrawl from checking \n' + '5. Withdrawl from savings \n' + '6. Quit \n\nPlease choose an option: ')) except ValueError: print('Input is not valid.') raise SystemExit(0) if choose == 1: inquiry(checking_balance,saving_balance) input('\n Press any key to go back: ') elif choose == 2: checking_balance = deposit(checking_balance) input('\n Press any key to go back: ') elif choose == 3: saving_balance = deposit(saving_balance) input('\n Press any key to go back: ') break elif choose == 4: checking_balance = withdrawl(checking_balance) input('\n Press any key to go back: ') break elif choose == 5: saving_balance = withdrawl(saving_balance) input('\n Press any key to go back: ') elif choose == 6: print('Thank You for your Business') raise SystemExit(0) print('\n Unknown PIN.') input('\n Press any key to go back: ') main() def inquiry(checking_balance,saving_balance): print('\n Checking balance: ',checking_balance) print('\n Savings balance: ',saving_balance) def deposit(balance): dep = int(input('\n Please enter how much you want to deposit: ')) balance += dep print('\n Your new balance is: ', balance) return balance def withdrawl(balance): withdrawl = int(input('\n Please enter how much you want to withdrawl: ')) while withdrawl > balance: print('\n You broke foo.') withdrawl = int(input('\n Please enter how much you want to withdrawl: ')) balance = balance - withdrawl print('\n Your new balance is: ', balance) return balance main()
977125662ad8ba83bbe8cedc6bce54ab9836d207
kunxin-chor/tgc-python
/select-example/main.py
343
3.515625
4
import pymysql connection = pymysql.connect(host='localhost', user="admin", password="password", database="Chinook" ) cursor = connection.cursor() cursor.execute("SELECT * from Employee") for r in cursor: # print (r) # We have to refer each field by its index print ("Name: " + r[1] + " " + r[2] + " is a " + r[3])
8b46f6ce79908a511e258e2af636e398387f0474
accimeesterlin/scrape_linkedin
/filter_contact.py
2,087
3.59375
4
import json from pprint import pprint data = json.load(open("contacts.json")) def set_max(arr, limit): for index, contact in enumerate(arr): if index <= int(limit) - 1: print("_______________________________________") print("_______________________________________") print("Index: ", index + 1) print("Name: ", contact["name"]) print("Occupation: ", contact["occupation"]) print("Link: ", contact["link"]) def search_contact(detail, val, limit): status = False results = [] for index, contact in enumerate(data): if contact[detail].find(val) != -1: status = True current_search = {} current_search["name"] = contact["name"] current_search["link"] = contact["link"] current_search["occupation"] = contact["occupation"] results.append(current_search) if status == False: print("No results found!!!") set_max(results, limit) # TODO # Cleaning def honoring_user_input(_input): if _input == "Company Name": text = input("Enter the company name: ") num = input("How many results do you want? ") search_contact("occupation", text, num) elif _input == "Name": text = input("Enter the name: ") num = input("How many results do you want? ") search_contact("name", text, num) elif _input == "Title": text = input("Enter the title: ") num = input("How many results do you want? ") search_contact("occupation", text, num) options = ["Company Name", "Name", "Title"] # Let user enter based on the option def let_user_pick(options): print("Search people by: ") for idx, element in enumerate(options): print("{}) {}".format(idx + 1, element)) i = input("Enter number: ") try: if 0 < int(i) <= len(options): honoring_user_input(options[int(i) - 1]) return options[int(i) - 1] # value selected except: pass return None let_user_pick(options)
5e6544c168eba12bfd9cc44e1734ec5dd5691dac
ajaycode/study
/class05/math/tests/test_temperature.py
827
3.5
4
# ..\tests>python test_fraction.py import unittest from unittest import TestCase __author__ = 'Ajay' import sys sys.path.append('..\\') from temperature import * class TestTemperature(TestCase): def test_celsius_from_fahrenheit(self): question, answer = celsius_from_fahrenheit (60) self.assertEqual("{}{}C".format (15.6, u'\N{DEGREE SIGN}'), answer) question, answer = celsius_from_fahrenheit (80) self.assertEqual("{}{}C".format (26.7,u'\N{DEGREE SIGN}'), answer) def test_fahrenheit_from_celsius (self): q, a = fahrenheit_from_celsius (60) self.assertEqual("140.0{}F".format (u'\N{DEGREE SIGN}'), a) q, a = fahrenheit_from_celsius (80) self.assertEqual("176.0{}F".format (u'\N{DEGREE SIGN}'), a) if __name__ == '__main__': unittest.main()
d60032107ecb73851a9abeb29cc1f5dedcf0b111
nicolassnider/udemy_machine_learning_r_python
/testProject/seccion08/tuplas.py
268
3.78125
4
p1=(1,) p2=(1,2,3,4) p3=(1,2,'e',3.1415) print(p1) print(p2) print(p3) print(p3[0:2]) a,b,c,d=p3 print(a) print(c) # L4 = list(p3) print(L4) p5=tuple(L4) print(p5) # L=tuple(input('Escribe numeros separados por comas: \n').split(',')) for n in L: print(2*int(n))
10c930abce072e05a3e4b1f1608f918c3b7c5afe
vinaybommana/twitter-analytics
/step_4/influentials_users.py
1,671
3.625
4
import csv import codecs import math def read_csv(filename): rows = list() with open(str(filename), "r") as c: csvreader = csv.reader(c) next(csvreader) for row in csvreader: rows.append(row) return rows def main(): second_rows = read_csv("step_two_output.csv") third_rows = read_csv("step_three_output.csv") unique_users = list() no_of_tweets = list() dict_of_user_retweet = dict() users = list() for second_row in second_rows: user = second_row[1] retweet = second_row[3] if user not in users: dict_of_user_retweet[user] = int(retweet) users.append(user) else: dict_of_user_retweet[user] += int(retweet) for third_row in third_rows: unique_users.append(third_row[1]) no_of_tweets.append(third_row[2]) dict_user_number_tweet = dict(zip(unique_users, no_of_tweets)) # print(dict_of_user_retweet) # serial_number, username@mention, userid, tweet_count, retweet_count, log(retweet_count) with codecs.open('step_four_output.csv', 'w+', 'utf-8') as o: o.write("Serial_number\t" + "," + "screen_name\t" + "," + "No of Tweets" + "," + "No of retweets" + "," + "log base 2 (retweet_count)\n") count = 1 for user, no_of_tweets in dict_user_number_tweet.items(): line = str(count) + "," + str(user) + "," + str(no_of_tweets) + "," + \ str(dict_of_user_retweet[user]) + "," + str(math.log(int(dict_of_user_retweet[user]), 2)) + "\n" o.write(line) count += 1 if __name__ == '__main__': main()
819cdf9e9e096ce54c22847b91c165171bba45be
Ruslan-Skira/PythonHW1
/listModification.py
4,631
4.375
4
"""Первая версия функции извлекает первый аргумент (args – это кортеж) и обходит остальную часть коллекции, отсекая первый элемент (нет никакого смысла сравнивать объект сам с собой, особенно если это довольно крупная структура данных).""" def min1(*args): current = args[0] for i in args[1:]: # all but the first element if i < current: current = i print(current) #min1(1,55,3,2) """Вторая версия позволяет интерпретатору самому выбрать первый аргумент и остаток, благодаря чему отпадает необходимость извлекать первый аргумент и получать срез.""" def min2(first,*rest): for arg in rest: if arg < first: first = arg return first #print(min2(999,44,24,66)) """Третья версия преобразует кортеж в список с помощью встроенной функции list и использует метод списка sort.""" def min3(*args): tmp = list(args) tmp.sort() return tmp[0] #print(min3(8,2,45)) """ обобщить функцию так, что она будет отыскивать либо минимальное, либо максимальное значение, определяя отношения элементов за счет интерпретации строки выражения с помощью таких средств, как встроенная функция eval """ def minmax(func, *args): current = args[0] for i in args[1:]: if func(i, current): current = i return current def lessthan(x, y): return x < y def grtrthan(x, y): return x > y #print(minmax(lessthan, 4,3,2,5,6)) #print(minmax(grtrthan, 4,3,2,5,6)) """found unic I don't know why but it is works only for 2 arg not for all shit""" def union (*args): res = [] for seq in args: for x in seq: if not x in res: res.append(x) return res s1, s2, s3 = "SPAM", "SCAM", "SLAM" print(union(s1, s2, s3)) """write map funciton""" def mymap(func, seq): res = [] for x in seq: res.append(func(x)) return res """lessons for the map function you have different city with temperature""" teps = [("berlin", 23), ("kharkiv", 33), ("barsa", 45)] c_to_t= lambda data: (data[0], (9/5)*data[1]+32)# formula fro the celsius to farengait print(list(map(c_to_t, teps))) """write your own reduce""" def myreduce(function, sequence): tally = sequence[0] for next in sequence[1:]: tally = function(tally, next) return tally #testing myreduce((lambda x, y: x + y), [1,2,3,4,5]) """write your own reduce with for""" L = [1,2,3,4,5] res = L[0] for x in L[1:]: res = res + x """create list with map function for n**2 in range (10)""" list(map((lambda x: x **2), (range(10)))) """wrire generator witch will be concatanate first letter of the spam SPAM like sS sP sA""" print([x + y for x in 'spam' for y in 'SPAM']) """"row in matrix""" M = [[1,2,3],[4,5,6],[7,8,9]] [row[1] for row in M] """matrix diagonal""" [M[i][i] for i in range(len(M))] """multiply 2 matrix""" res = [] for row in range(3): tmp = [] for col in range(3): tmp.append(M[row][col] * N[row][col]) res.append(tmp) res """write the same with lambda""" def f1(x): return x ** 2 def f2(x): return x ** 3 def f3(x): return x ** 4 L = [f1,f2,f3] for f in L: print(f(2)) print(L[0](3)) #answer M = [lambda z: z+1, lambda z: z+2, lambda z: z+3] for k in M: print(k(3)) print(M[2](3)) """create new list with modifided previous list""" counters_ = [1, 2, 3, 4] updated=[] for x in counters_: updated.append(x + 10) print(updated) """create the same with map function""" def inc(x) : x + 10 map(inc, counters_) """put lambda inside map""" list(map((lambda x: x + 3), counters_)) """range""" #1 line of odd numbers res = [] for i in range(1, 25, 2): res.append(i) print(res) #2use the list comprehension res = [x for x in range(1, 20, 2)] print(res) #3 exclude the squares and don't show squares multiples 3 res = [x ** 2 for x in range (1, 100, 2) if x %3 != 0] #4 you have dic = {'John': 1200, 'Paul': 1000, 'jones':450} # output the John = 1200 dic = {'John': 1200, 'Paul': 1000, 'jones':450} print = ("\n".join([f"{name} = {salary:d}" for name, salary in dic.items()]))
69c903b677e32ce1de2e292ef315f68c05361452
Ruslan-Skira/PythonHW1
/OOP/test_resource.py
349
3.703125
4
import unittest from math import pi import resource class TestCircleArea(unittest.TestCase): def test_area(self): # Test areas when radius > = 0 self.assertAlmostEqual(resource.circle_area(1), pi) self.assertAlmostEqual(resource.circle_area(55), 1) self.assertAlmostEqual(resource.circle_area(2.1), pi * 2.1**2)
f40434748d69a754a43d733df64129d39bc12e48
kevinmartinjos/mapleblow
/game.py
2,270
3.640625
4
import pygame from world import Hurdle from vector2 import Vector2 from pygame.locals import * from sys import exit from leaf import Leaf from wind import Wind import wx start=False def run_game(run_is_pressed): pygame.init() clock=pygame.time.Clock() screen=pygame.display.set_mode((640,480)) picture='leaf.png' blocks=[] i=0 while i<5: #blocks.append(Hurdle()) i=i+1 SCREEN_SIZE=(screen.get_width(),screen.get_height()) leaf_velocity=Vector2((0,0.5)) maple=Leaf(SCREEN_SIZE[0]/2,0,leaf_velocity,picture) print maple.w,maple.h gale=Wind(0) while True: for event in pygame.event.get(): if event.type==QUIT: exit() elif pygame.mouse.get_pressed()[0]: pos=pygame.mouse.get_pos() gale.get_dir(maple.get_pos(),pos) maple.wind_affect(gale) elif pygame.mouse.get_pressed()[2]: maple.x=SCREEN_SIZE[0]/2 maple.y=0 maple.velocity=Vector2((0,0.2)) clock.tick(60) screen.fill((255,255,255)) maple.render(screen) i=0 #while(i<5): #blocks[i].render(screen) maple.simple_collision_check() # i=i+1 maple.fall() pygame.display.update() def show_help(info_pressed): wx.MessageBox('Welcome to Maple Blow. Maple Blow is a simple program which lets you control a maple leaf floating in the air. Click anywhere inside the playing area and an imaginary wind (yeah, Imaginary) will blow from that point to the centre of the leaf.The closer you click to the leaf, the stronger the wind that blows. As of now, there is no particular \'objective\' associated with the program (that\' why i call it a program and not a game :D). In case the leaf go out of bounds, right click anywhere to reset','Help') app=wx.App() frame=wx.Frame(None,-1,'Leaves',size=(640,480)) def about_show(about_pressed): about_text=""" Maple Blow V 0.0001 Developer : Kevin Martin Jose License:Freeware/Open Source webpage:www.kevinkoder.tk""" wx.MessageBox(about_text,'About') panel=wx.Panel(frame,-1) run=wx.Button(panel,-1,'RUN',(280,220)) info=wx.Button(panel,0,'HELP',(280,180)) about=wx.Button(panel,1,'ABOUT',(280,260)) panel.Bind(wx.EVT_BUTTON,run_game,id=run.GetId()) panel.Bind(wx.EVT_BUTTON,about_show,id=about.GetId()) panel.Bind(wx.EVT_BUTTON,show_help,id=info.GetId()) frame.Show() app.MainLoop()
5234c1163f18bfd1e095b287f5a75ec97a37a898
tfmorris/wrangler
/runtime/python/wrangler/sort.py
1,806
3.5
4
from transform import Transform def mergesort(list, comparison): if len(list) < 2: return list else: middle = len(list) / 2 left = mergesort(list[:middle], comparison) right = mergesort(list[middle:], comparison) return merge(left, right, comparison) def merge(left, right, comparison): result = [] i ,j = 0, 0 while i < len(left) and j < len(right): if(comparison(left[i], right[i]) == 1): result.append(right[j]) j += 1 else: result.append(left[i]) i += 1 result += left[i:] result += right[j:] return result class Sort(Transform): def __init__(self): super(Sort,self).__init__() self['direction'] = [] self['as_type'] = [] def apply(self, tables): columns = self.get_columns(tables) table = tables[0] types = self['as_type'] directions = [d for d in self['direction']] for d in range(len(self['direction']), len(columns)): directions.append('asc') directions = [(1 if d=='asc' else -1) for d in directions] def sort_fn(a, b): for i in range(0, len(columns)): col = columns[i] result = types[i].compare(col[a], col[b]); if not result == 0: return directions[i]*result if(a<b): return -1 if(a==b): return 0 return 1; # sorted_rows = mergesort(range(0, table.rows()), sort_fn) sorted_rows = range(0, table.rows()) sorted_rows.sort(sort_fn) results = [columns[0][i] for i in sorted_rows] new_table = table.slice(0, table.rows()) for col in range(0, table.cols()): column = table[col]; new_column = new_table[col] for row in range(0, table.rows()): new_column[row] = column[sorted_rows[row]] table.clear() for col in new_table: table.insert_column(col, {})
72cdf859ab9d5adcbddf25295b4da9dea6015c90
EdwardTFS/TensorflowExamples
/example1.py
999
3.84375
4
#based on https://developers.google.com/codelabs/tensorflow-1-helloworld #fitting a linear function import sys print("Python version:",sys.version) import tensorflow as tf import numpy as np print("TensorFlow version:", tf.__version__) from tensorflow import keras #create model model = keras.Sequential([keras.layers.Dense(units=1, input_shape=(1,))]) #compile model model.compile(optimizer='sgd', loss='mean_squared_error') #function for creating data f = lambda x: x * 3 + 1 #learn data xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = f(xs) #test data x_test = np.array([-0.5, 0.5, 1.5, 2.5, 3.5], dtype=float) y_test = f(x_test) #fit 1 print("FIT") model.fit(xs, ys, epochs=20) #evaluate after fit 1 print("EVALUATE") model.evaluate(x_test, y_test, verbose=2) #fit 2 print("FIT2") model.fit(xs, ys, epochs=100) #evaluate after fit 2 print("EVALUATE2") model.evaluate(x_test, y_test, verbose=2) #predict print("PREDICT") print(model.predict(np.array(range(5))))
5d0b56e2c02f10090b62c259d5b7782c144eb840
prajwolshakya/visualization-sorting-algorithms
/shell_sort.py
762
3.859375
4
from cube import Run def shell_sort(): run = Run() arr = run.display() sublistcount = len(arr) // 2 while sublistcount > 0: for start in range(sublistcount): gap_insertion_sort(arr,start,sublistcount,run) #print(sublistcount) #print(arr) sublistcount = sublistcount // 2 return arr def gap_insertion_sort(arr, start, gap,run): for i in range(start+gap, len(arr),gap): currentvalue = arr[i] position = i while position >= gap and arr[position-gap] > currentvalue: run.remove(arr[position-gap],position-gap) run.remove(arr[position],position) arr[position] = arr[position-gap] run.add( arr[position],position) position = position-gap arr[position] = currentvalue run.add( arr[position],position) # shell_sort()
42167b22a0b27f5172f2c432979a397201cffde4
2508Fernan/Taller-3
/FernandaUshcasina_EstrellaPar_Turtle.py
507
3.921875
4
from turtle import* import time import turtle t= turtle.Pen() ##tamaño de la ventana turtle.setup (500,600) ##establecer el objeto en pantalla wn= turtle.Screen() ##color de la pantalla wn.bgcolor("pink") ##titulo de la pantalla wn.title("Estrella de Puntas Pares") a=int(input("ingrese un numero par:")) print(a) for x in range (1,21): t.pencolor("sky blue") t.pensize(4) t.forward(100) an=180/a ang=180 - an t.left(ang) turtle.getscreen()._root.mainloop()
045cc9ae2292052a918ccca9ab13c76b442ea0bc
SamSweere/MRS
/gui/localization_path.py
2,861
3.578125
4
import pygame import math # Draws a dashed curve # Works by using the fraction variable to keep track of the dash strokes # fraction from 0 to 1 means dash # fraction from 1 to 2 means no dash def draw_dashed_curve(surf, color, start, end, fraction, dash_length=10): start = pygame.Vector2(start) end = pygame.Vector2(end) delta = end - start length = delta.length() if length < 0.0000001: return fraction + length new_fraction = fraction + length / dash_length slope = delta / length if fraction < 1: # If we're in the middle of drawing an dash, finish or continue it dash_end = start + slope * (min(1 - fraction, new_fraction - fraction)) * dash_length pygame.draw.line(surf, color, start, dash_end, 2) # Draw the remaining full-dashes for index in range(2, int(new_fraction), 2): dash_start = start + (slope * index * dash_length) dash_end = start + (slope * (index + 1) * dash_length) pygame.draw.line(surf, color, dash_start, dash_end, 2) if (new_fraction % 2) < 1: # There is still an half finished dash left to draw dash_start = start + slope * int(new_fraction - fraction) * dash_length pygame.draw.line(surf, color, dash_start, end, 2) return new_fraction % 2 class LocalizationPath: def __init__(self, game): self.game = game self.robot = game.robot self.localizer = self.robot.localizer self.path_surface = pygame.Surface((game.screen_width, game.screen_height), pygame.SRCALPHA) self.path_color = pygame.Color('orange') self.old_pos = (self.localizer.state_mu[0], self.localizer.state_mu[1]) self.passed_time = 0 self.dash_fraction = 0 def update(self, delta_time): new_pos = (self.localizer.state_mu[0], self.localizer.state_mu[1]) self.dash_fraction = draw_dashed_curve(surf=self.path_surface, color=self.path_color, start=self.old_pos, end=new_pos, fraction=self.dash_fraction) self.old_pos = new_pos # Freeze the uncertainty ellipse after a set amount of time self.passed_time += delta_time if self.passed_time > 2: self.__draw_uncertainty_ellipse__(self.path_surface) self.passed_time = 0 def draw(self, surface): surface.blit(self.path_surface, (0,0), (0,0, self.game.screen_width, self.game.screen_height)) self.__draw_uncertainty_ellipse__(surface) def __draw_uncertainty_ellipse__(self, surface): x_mu = self.localizer.state_mu[0] y_mu = self.localizer.state_mu[1] x_std = self.localizer.state_std[0,0] y_std = self.localizer.state_std[1,1] pygame.gfxdraw.ellipse(surface, int(x_mu), int(y_mu), int(x_std), int(y_std), self.path_color)
4934d8f72ee6a0b00a6350c29e00f9994ef862ed
marccathomen/troccas
/app/card.py
516
3.5625
4
class Card: def __init__(self, id, power, value, suit, label): self.id = id # unique identification number self.power = power # beating power # value of the card in points self.value = value # suit of the card [r osa,s pada,c uppa,b astun,t rocca,n arr] self.suit = suit # label as on the real card [1,2,3,...,9,10,b uod, c cavagl, f emna, r etg, n arr, 1,2,...,20,21] self.label = label def show(self): print(self.label, self.suit)
1e37be68e28933fc50eb1eff40c74f6fb2d08da0
Krikiba/ATM
/fonction_atm.py
466
3.515625
4
def withdraw(request): i=0 liste=[100,50,10,5,4,3,2,1] for lis in liste: if request>=lis : request-=lis return request else : i+=1 def atm(money,request): balence=request print "Current balance =" +str(money) while request>0: if request>money : print ("le montant n'existe pas en ATM") break else : d=request request=withdraw(request) print "give " +str(d-request) return money-balence print atm(500,455)
3aeec4d5aae9f02d788af92f97af7e1ad5453940
mhurtad14/1500-intergration
/intergration project version 2.py
6,185
4
4
#Mijail Hurtado #Integration Project #COP 1500 #Professor Vanselow import math def get_bmr(): gender = input("What is your gender: M or F?") age = int(input("What is your age?")) height = int(input("What is your height in inches?")) weight = (int(input("What is your weight in pounds?"))) bmr_wght_constant = 4.536 bmr_hght_constant = 15.88 bmr_age_constant = 5 if gender == 'M': bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) + 5) elif gender == 'F': bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) - 161) else: print("Please try again.") return bmr def get_daily_calorie_requirement(bmr): dcr_1 = 1.2 dcr_2 = 1.375 dcr_3 = 1.55 dcr_4 = 1.725 dcr_5 = 1.9 act_lvl = int(input("What is your activity level?")) if act_lvl == 1: daily_calorie_requirement = int(bmr * dcr_1) elif act_lvl == 2: daily_calorie_requirement = int(bmr * dcr_2) elif act_lvl == 3: daily_calorie_requirement = int(bmr * dcr_3) elif act_lvl == 4: daily_calorie_requirement = int(bmr * dcr_4) elif act_lvl == 5: daily_calorie_requirement = int(bmr * dcr_5) else: print("Please choose a number 1-5.") return daily_calorie_requirement def main(): print("Hello, welcome to my intergration project!") print("The purpose of this program is to help the user reach their goal and provide helpful suggestions.") print("It will do this by taking your age, gender, height and your level of physical activity in order to calculate your Basal Metabolic Rate(BMR)") print("Your BMR is how many calories you burn in a single day. Combining your BMR with your goals we can suggest a meal plan and excercises that will help reach your goals") print("Let's get started! I will start by asking you a few questions in order to make a profile and give you the best informed advice.") bmr = get_bmr() print("Your BMR is: ", bmr) print("Great! Now that we have calculated your Basal Metabolic Rate, let's calculate your daily calorie requirement!") print("This is the calories you should be taking in to maintain your current weight") print("How active are you on a scale of 1-5?") print("1 being you are sedentary (little to no exercise)") print("2 being lightly active (light exercise or sports 1-3 days a week)") print("3 being moderately active (moderate exercise 3-5 days a week)") print("4 being very active (hard exercise 6-7 days a week)") print("5 being super active (very hard exercise and a physical job)") print("Exercise would be 15 to 30 minutes of having an elevated heart rate.") print("Hard exercise would be 2 plus hours of elevated heart rate.") daily_calorie_requirement = get_daily_calorie_requirement(bmr) print("The amount of calories you should be consuming are: ", daily_calorie_requirement) print("Now that we have calculated your daily caloric requirement, let's figure out your goals.") print("If you are trying to lose weight enter 1, if you are trying to maintain enter 2 or if you are trying to gain weight enter 3.") goal = int(input("What is the goal you are setting for yourself?")) if goal == 1: print("In order to reach your goal safely you will have to reduce your daily caloric intake by 500 in order to lose one pound a week") print("In order to reach your goal, will keep track of the amount of calories you consume.") print("The best way to keep track of your calories is to record the amount of calories consumed after every meal.") cal_goal_1 = daily_calorie_requirement - 500 cal_consumed_1 = 0 while cal_goal_1 >= cal_consumed_1: cal_taken = int(input("How many calories have was your last meal?")) cal_consumed_1 += cal_taken if cal_goal_1 <= cal_consumed_1: print("Congratulations! You have reached your goal for the day by taking in", cal_consumed_1, "calories!") elif goal == 2: print("If you are trying to maintain your current level then just continue taking in the same about of calories daily.") print("In order to reach your goal, will keep track of the amount of calories you consume.") print("The best way to keep track of your calories is to record the amount of calories consumed after every meal.") cal_goal_2 = daily_calorie_requirement cal_consumed_2 = 0 while cal_goal_2 >= cal_consumed_2: cal_taken = int(input("How many calories have was your last meal?")) cal_consumed_2 += cal_taken if cal_goal_2 <= cal_consumed_2: print("Congratulations! You have reached your goal for the day", cal_consumed_2, "calories!") elif goal == 3: print("If you want to bulk up and build lean muscle mass you need to consume 300 to 500 more calories than your daily metabolic requirement") print("If you are just starting out, I would suggest you begin with 300 calories as taking more calories than need will lead to fat also being produced.") print("In order to reach your goal safely you will have to increase your daily caloric intake by 300 in order to gain one half a pound to half a pound a week") print("In order to reach your goal, will keep track of the amount of calories you consume.") print("The best way to keep track of your calories is to record the amount of calories consumed after every meal.") cal_goal_3 = daily_calorie_requirement + 300 cal_consumed_3 = 0 while cal_goal_3 >= cal_consumed_3: cal_taken = int(input("How many calories have was your last meal?")) cal_consumed_3 += cal_taken if cal_goal_3 <= cal_consumed_3: print("Congratulations! You have reached your goal for the day!",cal_consumed_3, "calories!") else: print("Please try again.") main()
aec194198be1a68b82f0fa306aff480d9e4fc396
rbusquet/advent-of-code
/aoc_2021/day11.py
1,880
3.53125
4
from itertools import count, product from pathlib import Path from typing import Iterator Point = tuple[int, int] def neighborhood(point: Point) -> Iterator[Point]: x, y = point for i, j in product([-1, 0, 1], repeat=2): if i == j == 0: continue yield x + i, y + j def flash(point: Point, universe: dict[Point, int], flashed: set[Point]) -> None: for n in neighborhood(point): if n not in universe: continue universe[n] += 1 if universe[n] > 9 and n not in flashed: flashed.add(n) flash(n, universe, flashed) def part_1_and_2() -> tuple[int, int]: universe = dict[Point, int]() with open(Path(__file__).parent / "input.txt") as file: for i, line in enumerate(file): for j, brightness in enumerate(line.strip()): universe[i, j] = int(brightness) flashes_after_100 = 0 for step in count(): flashed = propagate_energy(universe) if step <= 99: flashes_after_100 += len(flashed) if len(flashed) == 100: break # zero flashed for point in universe: if universe[point] > 9: universe[point] = 0 return flashes_after_100, step def propagate_energy(universe: dict[Point, int]) -> set[Point]: for point in universe: universe[point] += 1 flashed = set[Point]() while True: flashing = [ point for point in universe if universe[point] > 9 and point not in flashed ] if not flashing: break for point in flashing: flashed.add(point) for n in neighborhood(point): if n not in universe: continue universe[n] += 1 return flashed if __name__ == "__main__": print(part_1_and_2())
c1232f17b340a952c18208ffe66c59ad3e5b9243
rbusquet/advent-of-code
/aoc_2015/day1.py
622
3.640625
4
from pathlib import Path def part_1() -> int: with open(Path(__file__).parent / "input.txt") as file: floor = 0 while step := file.read(1): floor += step == "(" or -1 return floor def part_2() -> int: with open(Path(__file__).parent / "input.txt") as file: floor = 0 position = 1 while step := file.read(1): floor += step == "(" or -1 if floor == -1: return position position += 1 raise Exception("Something went wrong") if __name__ == "__main__": print(part_1()) print(part_2())
48a7d98ef8acfdd3fc5c7ace832810e2fe3c6092
rbusquet/advent-of-code
/aoc_2020/day3.py
771
3.65625
4
from functools import reduce from itertools import count from operator import mul from typing import Iterator def read_file() -> Iterator[str]: with open("./input.txt") as f: yield from f.readlines() def count_trees(right: int, down: int) -> int: counter = count(step=right) total_trees = 0 for i, line in enumerate(read_file()): if i % down != 0: continue line = line.strip() position = next(counter) % len(line) total_trees += line[position] == "#" return total_trees print("--- part 1 ---") print(count_trees(3, 1)) print("-- part 2 ---") vals = [ count_trees(1, 1), count_trees(3, 1), count_trees(5, 1), count_trees(7, 1), count_trees(1, 2), ] print(reduce(mul, vals))
9abc4c7c745318043728354a75b0e6cc58e532e7
rbusquet/advent-of-code
/aoc_2020/day24.py
2,339
3.78125
4
from collections import defaultdict from dataclasses import dataclass @dataclass class Cube: x: int y: int z: int def __add__(self, cube: "Cube") -> "Cube": return Cube(self.x + cube.x, self.y + cube.y, self.z + cube.z) @classmethod def new(cls) -> "Cube": return Cube(0, 0, 0) # https://www.redblobgames.com/grids/hexagons/#neighbors-cube cube_directions = { "e": Cube(+1, -1, 0), "ne": Cube(+1, 0, -1), "nw": Cube(0, +1, -1), "w": Cube(-1, +1, 0), "sw": Cube(-1, 0, +1), "se": Cube(0, -1, +1), } def read_file(): with open("./input.txt") as f: yield from (c.strip() for c in f.readlines()) hex_grid = defaultdict[Cube, bool](bool) def find_cube(instruction) -> Cube: p = 0 cube = Cube.new() while p < len(instruction): direction = instruction[p : p + 1] if direction not in cube_directions: direction = instruction[p : p + 2] p += 1 p += 1 offset = cube_directions[direction] cube += offset # print(cube) return cube hex_grid = defaultdict[Cube, bool](bool) for instruction in read_file(): cube = find_cube(instruction) hex_grid[cube] = not hex_grid[cube] print(sum(hex_grid.values())) def neighborhood(cube: Cube): yield cube for direction in cube_directions: yield cube + cube_directions[direction] def full_cycle(grid, days): for _ in range(days): cube_to_active_count = defaultdict[Cube, int](int) for cube in grid: if not grid[cube]: continue for n in neighborhood(cube): # neighborhood contains cube and all its neighbors. # `cube_to_active_count[n] += n != cube` ensures # active cubes without active neighbors are counted # and proper deactivated by underpopulation in the # next for-loop. cube_to_active_count[n] += n != cube and grid[cube] for n, count in cube_to_active_count.items(): if grid[n]: if count == 0 or count > 2: grid[n] = False else: if count == 2: grid[n] = True return grid final = full_cycle(hex_grid, 100) print(sum(final.values()))
bedc3696e18c0810fffc6e0095d884de1c42b970
rbusquet/advent-of-code
/aoc_2020/day17.py
1,673
3.578125
4
from collections import defaultdict from itertools import product initial = """ ####.#.. .......# #..##### .....##. ##...### #..#.#.# .##...#. #...##.. """.strip() def neighborhood(*position: int): for diff in product([-1, 0, 1], repeat=len(position)): neighbor = tuple(pos + diff[i] for i, pos in enumerate(position)) yield neighbor def full_cycle(initial, dimensions): space = defaultdict(lambda: ".") padding = (0,) * (dimensions - 2) for x, line in enumerate(initial.splitlines()): for y, state in enumerate(line): cube = (x, y) + padding space[cube] = state for _ in range(6): cube_to_active_count = defaultdict(int) for cube in space: if space[cube] == ".": continue for n in neighborhood(*cube): # neighborhood contains cube and all its neighbors. # `cube_to_active_count[n] += n != cube` ensures # active cubes without active neighbors are counted # and proper deactivated by underpopulation in the # next for-loop. cube_to_active_count[n] += n != cube and space[cube] == "#" for n, count in cube_to_active_count.items(): if space[n] == "#": if count in [2, 3]: space[n] = "#" else: space[n] = "." elif space[n] == "." and count == 3: space[n] = "#" return sum(state == "#" for state in space.values()) print("--- part 1 ---") print(full_cycle(initial, 3)) print("--- part 2 ---") print(full_cycle(initial, 4))
dbcf6b5acffdf9a54c1a18efc214dcaed6bae1c7
HanniSYC/Practice_code
/二维数组中的查找练习.py
1,405
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/3 下午9:38 # @Author : Hanni # @Fun : 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 # 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 print '欢迎来到二维数组中的查找v1.0 @星辰\n' class Solution: def Find(self, target, array): rowcount = len(array) colcount = len(array[0]) if colcount - 1 == 0: #二维数组为空 return False for i in range(rowcount -1 , -1, -1):#从左下角开始检索,到右上角结束,每次移动一个位置 if target > array[i][0]:#要查找的数字大于左下角的数字 for j in range(colcount):#右移比较 if target == array[i][j]:#找到,返回True return True elif target == array[i][0]:#要查找的数字等于左下角的数字,返回True return True #否则上移 return False array = [[1,3,5,7],[2,4,6,8],[3,6,9,12]] #循环显示二维数组 for i in range(0, 3): for j in range(0, 4): print array[i][j], print target = input('请输入待检测的数字:') s = Solution() print(s.Find(target, array))
98144aeef549d072b82e1ec8b6fe04b231c4016d
rollingonroad/Python005-01
/week06/assignment.py
1,777
3.984375
4
from abc import ABCMeta, abstractmethod # 动物 class Animal(metaclass=ABCMeta): def __init__(self, food_type, body_size, character): self.food_type = food_type self.body_size = body_size self.character = character @property def is_fierce(self): return self.body_size != '小' and self.food_type == '食肉' and self.character == '凶猛' @abstractmethod def is_pettable(self): pass # 猫 class Cat(Animal): sound = 'Meow' def __init__(self, name, food_type, body_size, character): super().__init__(food_type, body_size, character) self.name = name @property def is_pettable(self): return not self.is_fierce # 狗 class Dog(Animal): sound = 'Bark' def __init__(self, name, food_type, body_size, character): super().__init__(food_type, body_size, character) self.name = name @property def is_pettable(self): return not self.is_fierce # 动物园类 class Zoo(object): def __init__(self, name): self.name = name # 使用set防止单个动物实例增加多次 self.animals = set() def add_animal(self, animal): # 同一只动物只会记录一次 self.animals.add(animal) # 用类名作为属性名,支持hasattr self.__setattr__(type(animal).__name__, True) if __name__ == '__main__': # 实例化动物园 z = Zoo('时间动物园') # 实例化一只猫,属性包括名字、类型、体型、性格 cat1 = Cat('大花猫 1', '食肉', '小', '温顺') # 增加一只猫到动物园 z.add_animal(cat1) # 动物园是否有猫这种动物 have_cat = hasattr(z, 'Cat') # 测试abc # a = Animal('a', 'b', 'c')
fc9366b9c351ebcc8ee1408a82cbb2a051785b40
schardt8237/Codecademy
/Data Science Career Path/Unit 14: Learn Statistics With Python/life_expectancy_by_country.py
840
3.75
4
import codecademylib3_seaborn import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("country_data.csv") #print(data.head()) life_expectancy = data["Life Expectancy"] life_expectancy_quartiles = np.quantile(life_expectancy, [0.25, 0.5, 0.75]) print(life_expectancy_quartiles) #plt.hist(life_expectancy) #plt.show() gdp = data["GDP"] median_gdp = np.quantile(gdp, 0.5) low_gdp = data[data['GDP'] <= median_gdp] high_gdp = data[data['GDP'] > median_gdp] low_gdp_quartiles = np.quantile(low_gdp["Life Expectancy"], [0.25, 0.5, 0.75]) high_gdp_quartiles = np.quantile(high_gdp["Life Expectancy"], [0.25, 0.5, 0.75]) plt.hist(high_gdp["Life Expectancy"], alpha = 0.5, label = "High GDP") plt.hist(low_gdp["Life Expectancy"], alpha = 0.5, label = "Low GDP") plt.legend() plt.show()
e1ecce71b4e466e4028e2528e627a61486137ee5
IzMasters/timefuzz
/timefuzz.py
3,720
3.546875
4
class Namespace: def __init__(self, **names): for name in names.keys(): setattr(self, name, names[name]) # helper class for "speaking" units.. # singular and plural are the respective forms, plural defaults to a regular "s"-plural # vowel_onset determines whether or not to use "an" for the indefinite article class Word: def __init__( self, singular, plural = None, vowel_onset = False): self.singular = singular self.plural = plural or singular + "s" self.vowel_onset = vowel_onset class TimeUnit: def __init__( self, value, limit, precisions, word): self.value = value self.limit = limit self.precisions = precisions self.word = word duration = Namespace() setattr(duration, "second", 1) setattr(duration, "minute", duration.second * 60) setattr(duration, "hour", duration.minute * 60) setattr(duration, "day", duration.hour * 24) setattr(duration, "week", duration.day * 7) setattr(duration, "year", int(duration.day * 365.25)) setattr(duration, "month", duration.year // 12) setattr(duration, "decade", duration.year * 10) setattr(duration, "century", duration.year * 100) unit = Namespace( moment = TimeUnit(0, duration.second, [], Word("moment")), second = TimeUnit(duration.second, duration.minute, [(5,1),(30,5),(60,10),(120,30)], Word("second")), minute = TimeUnit(duration.minute, duration.hour, [(5,1),(30,5),(60,10),(120,30)], Word("minute")), hour = TimeUnit(duration.hour, duration.day, [(6,1),(24,3)], Word("hour", vowel_onset = True)), day = TimeUnit(duration.day, duration.week, [(6,1)], Word("day")), week = TimeUnit(duration.week, 2 * duration.month, [(4,1)], Word("week")), month = TimeUnit(duration.month, duration.year, [(12,1),(24,6)], Word("month")), year = TimeUnit(duration.year, 2 * duration.decade, [(10,1),(100,10),(1000,100)], Word("year")), decade = TimeUnit(duration.decade, duration.century, [(9,1)], Word("decade")), century = TimeUnit(duration.century, -1, [(1,1)], Word("century", plural = "centuries"))) # all limits in a central place limits = dict([(getattr(unit, u), getattr(unit, u).limit) for u in vars(unit)]) # the inverse dictionary to look up units by limits inv_limits = dict([(v,k) for (k,v) in limits.items()]) def get_unit(time): """ The appropriate time unit to use for a given duration in seconds, as defined via the limits dictionary above.""" thresholds = list(limits.values()) thresholds.sort() for t in thresholds: if time < t: return inv_limits[t] return unit.century def fuzz(time, granularity=1): """ A human-readable approximate representation of a time duration. The granularity parameter can be used to fine-tune granularity. values > 1 mean less precision; values < 1 mean more precision.""" # first determine appropriate time unit... t_unit = get_unit(time) # next, the magnitude given our time unit value = 0 if t_unit == unit.moment else int(time // t_unit.value) # lastly, figure out the custom precision stuff p = t_unit.precisions p.sort() try: thresh = value * granularity key = next(filter(lambda x: x > thresh, (x[0] for x in p))) precision = dict(p)[key] except StopIteration: # don't use a numeral at all if number too high precision = 0 # values of 0 are used to express "unspecified" as in: "months ago" value = 0 if (precision == 0) else ((value // precision) * precision) # natural lanugage stuff: spit out the correct word forms and such: # TODO make this more configurable if value == 0: return t_unit.word.plural # "months ago", not "0 months" or "0 month" if value == 1: return "an " if t_unit.word.vowel_onset else "a " + t_unit.word.singular return "{} {}".format( value, t_unit.word.plural)
7c7e46570e38bc54ba1c1fabd9c11de78f8f27b9
CharlieGodfrey1/Python-practice
/divisors practice.py
409
4
4
#user enters number num=int(input("Please enter a number: ")) #works out the intigers from 1 to the entered number listrange = list(range(1,num+1)) #list of divisors divisors = [] #for loop to work out divisors for i in listrange: #divides the entered number by the list range integers and if they have a modulas of 0 they are divisers if num % i == 0: divisors.append(i) print(divisors)
cb69532884a199d684d49739f1bc17e3076600a8
calcsam/toyprojects
/socialwire_example.py
3,142
3.65625
4
# in response to http://www.socialwire.com/exercise1.html; took me about 2 hours to code # python 2.7 def test(aString): stillNumber = True expectedExpressions = 0 allExp = [] currentExp = [] for char in aString: #print "iterate" + char if is_number(char) and stillNumber: expectedExpressions = expectedExpressions*10 + float(char) else: if stillNumber == True: # only should enter the else if loop once stillNumber = False if expectedExpressions == 0: expectedExpressions = 1 if notInSet(char): return "INVALID, " + char + " NOT VALID CHARACTER" currentExp = push(char, currentExp) #print currentExp if completeTree(currentExp): allExp.append(currentExp) currentExp = [] if len(allExp) == 0: return "INVALID, NO FULL EXPRESSIONS GIVEN" if not completeTree(allExp[len(allExp)-1]): return "INVALID, LAST EXPRESSION " + str(allExp[len(allExp)-1]) + "NOT COMPLETE" if len(allExp) != expectedExpressions: #print allExp return "EXPECTED "+ str(expectedExpressions) + " EXPRESSIONS. GOT " + str(len(allExp)) print "PARSE TREE: " + str(len(allExp)) + " EXPRESSION(S):", print allExp return "VALID" def push(element,currentTree): # put element into our Tree, using recursion to push it down where necessary if not currentTree: # if empty #print "hello" currentTree.append([element]) return currentTree if currentTree[0] == ["Z"]: if len(currentTree) == 1: currentTree.append([element]) return currentTree if len(currentTree) == 2: return [currentTree[0], push(element,currentTree[1])] if currentTree[0] in (["M"],["K"],["P"],["Q"]): if len(currentTree) == 1: currentTree.append([element]) return currentTree if len(currentTree) == 2 and not completeTree(currentTree[1]): return [currentTree[0], push(element,currentTree[1])] if len(currentTree) == 2 and completeTree(currentTree[1]): currentTree.append([element]) return currentTree if len(currentTree) == 3: return [currentTree[0], currentTree[1], push(element,currentTree[2])] if currentTree[0] in ("M","K","P","Q", "Z"): return [[currentTree[0]],[element]] def completeTree(currentTree): # determines if tree is complete using recursion if not currentTree: # if empty return False if currentTree[0] in (["M"],["K"],["P"],["Q"]) and len(currentTree) == 3 and completeTree(currentTree[1]) and completeTree(currentTree[2]): return True elif currentTree[0] == ["Z"] and len(currentTree) == 2 and completeTree(currentTree[1]): return True elif currentTree[0] in (["a"],["b"],["c"],["d"],["e"],["f"],["g"],["h"],["i"],["j"],"a","b","c","d","e","f","g","h","i","j") and len(currentTree) == 1: return True #print "savory" #print currentTree return False def notInSet(char): # determine if valid input if char in ("a","b","c","d","e","f","g","h","i","j","M","K","P","Q","Z"): return False return True def is_number(s): #okay, this should be self-explanatory try: float(s) return True except ValueError: return False inputString = raw_input() while inputString != "BREAK": print test(inputString) inputString = raw_input()
63825db8fd9cd5e9e6aaa551ef7bfec29713a925
Rohit439/pythonLab-file
/lab 9 .py
1,686
4.28125
4
#!/usr/bin/env python # coding: utf-8 # ### q1 # In[2]: class Triangle: def _init_(self): self.a=0 self.b=0 self.c=0 def create_triangle(self): self.a=int(input("enter the first side")) self.b=int(input("enter the second side")) self.c=int(input("enter the third side")) def print_sides(self): print("first side:",self.a,"second side:",self.b,"third side",self.c) x=Triangle() x.create_triangle() x.print_sides() # ### q2 # In[4]: class String(): def _init_(self): self.str1="" def inputstr(self): self.str1=input("enter the string") def printstr(self): print(self.str1) x=String() x.inputstr() x.printstr() # ### q3 # In[4]: class Rectangle: length=0.0 width=0.0 per=0.0 def rect_values(self,l,w): self.length=l self.width=w def perimeter(self): self.per=2*self.length+self.width return(self.per) r1=Rectangle() r1.rect_values(10,20) k=r1.perimeter() print("the perimeter of rectangle is",k) # ### q4 # In[6]: class Circle: radius=0.0 area=0.0 peri=0.0 def _init_(self,radius): self.radius=radius def area(self): self.area=3.14*self.radius*self.radius return(self.area) def perimeter(self): self.peri=2*3.14*self.radius return(self.peri) c1=Circle() c1._init_(4) a=c1.area() p=c1.perimeter() print("the area and perimeter of circle are:",a,p) # ### q5 # In[7]: class Class2: pass class Class3: def m(self): print("in class3") class Class4(Class2,Class3): pass obj=Class4() obj.m() # In[ ]:
100419d5cdb569188d4c1231a7e603bc6c16353b
racheltsitomeneas/python_homework
/Python Homework/PyBank/Analysis/PyBank.py
1,915
3.84375
4
#pybank homework import os import csv #variables months = [] profit_loss_changes = [] count_months = 0 net_profit_loss = 0 previous_month_profit_loss = 0 current_month_profit_loss = 0 profit_loss_change = 0 os.chdir(os.path.dirname(__file__)) budget_data_csv_path = os.path.join("budget_data.csv") #csv read with open(budget_data_csv_path, newline="") as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") csv_header = next(csvfile) for row in csv_reader: count_months += 1 current_month_profit_loss = int(row[1]) net_profit_loss += current_month_profit_loss if (count_months == 1): previous_month_profit_loss = current_month_profit_loss continue else: profit_loss_change = current_month_profit_loss - previous_month_profit_loss months.append(row[0]) profit_loss_changes.append(profit_loss_change) previous_month_profit_loss = current_month_profit_loss sum_profit_loss = sum(profit_loss_changes) average_profit_loss = round(sum_profit_loss/(count_months - 1), 2) highest_change = max(profit_loss_changes) lowest_change = min(profit_loss_changes) highest_month_index = profit_loss_changes.index(highest_change) lowest_month_index = profit_loss_changes.index(lowest_change) best_month = months[highest_month_index] worst_month = months[lowest_month_index] #final print print("Financial Analysis") print(f"Total Months: {count_months}") print(f"Total: ${net_profit_loss}") print(f"Average Change: ${average_profit_loss}") print(f"Greatest Increase in Profits: {best_month} (${highest_change})") print(f"Greatest Decrease in Losses: {worst_month} (${lowest_change})")
b3717109102391a9eed15d86869e05c0866d6c29
MusawerAli/python_practise
/nesteddict.py
512
3.84375
4
#nested dictionary parent_child = { "child1": { "name": "jorg", "age": 22 }, "child": { "name": "bush", "age": 30 } } parent_brother = { "brother1": { "name": "jonze", "age": 43 }, "brother2": { "name": "bus", "age": 65 } } print(parent_brother) print('create one dictionary from multiole dict') parent_family = { 'parents_child': parent_child, 'parents_brotehr': parent_brother } print(parent_family)
34c328e731795ee17c1e887a966c33a6bf2ca327
MusawerAli/python_practise
/regex/regex.py
125
3.890625
4
import re txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) print("Have a match") if (x) else print("no match")
644dd04680b280b1def7e3d5023e2dfa0a253161
MusawerAli/python_practise
/regex/endwithword.py
182
4.59375
5
import re str = "hello world" #Check if the string ends with 'world': x = re.findall("world$", str) if (x): print("Yes, the string ends with 'world'") else: print("No match")
ea81873f62f22fb784403d68c7c443a4b3749a40
MusawerAli/python_practise
/if_else.py
501
3.890625
4
a = 50 b =20 c = 54 d=50 if b > a: print("b is greater than b") elif c>a: print("c is grater than a") else: print("a is grater than b") #Short Hand if...Else print("A") if a > b else print("B") #print Multiple print("A") if a< d else print("=") if a == d else print("B") if a>b and d>b: print("Both are true") if a<b or c>a: print("one is true") if a > b: print("A grearter than b") if b > a: print("b is greater than b") elif a>b:
80656a2831924d203537b5788143bf03e149dd7d
lalitasharma04/Computer_Networks
/source codes/Bit_Stuffing_and_character_stuffing.py
4,154
3.984375
4
''' ============================================================================== Name :Lalita Sharma RNo :06 =============================================================================== Experiment :02 *************** Aim:Write a program for implementing Bit Stuffing and character stuffing ''' # to convert string into binary def toBinary(string): binary="" for char in string: ascii=ord(char) # print("ascii is {}".format(ascii)) sum=0 w=1 while ascii != 0: d=ascii % 2 sum=sum+d*w w=w*10 ascii=ascii//2 if len(str(sum))!=8: sum1='0'*(8-len(str(sum))) +str(sum) binary=binary+str(sum1) return binary # bit stuffing def DataAfterBitStuffing(b_str): stuffed="" count=0 indx=-1 for char in b_str: indx+=1 if int(char)==1: count=count+1 stuffed+=char elif int(char)!=1: count=0 stuffed+=char if count==5: print("index is {}".format(indx)) stuffed=stuffed[:indx+1] +'0' #adding a 0 indx+=1 count=0 return stuffed # returns a destuffed binary string def destuffing(stuffed_str): count=0 destuff='' highlight=1 #to skip a character after 5 1's for char in stuffed_str: if highlight==60: highlight=1 continue if int(char)==1: count+=1 destuff+=char elif int(char)!=1: count=0 destuff+=char if count==5: count=0 highlight=60 return destuff # to convert destuffed binary string to actual string def Back_to_str(binary_str): len1=8 ori='' ini=0 range1=len(binary_str)//8 for i in range(range1): sum=0 w=1 one_char=binary_str[ini:len1] one_char=int(one_char) while int(one_char)!=0: d=one_char%10 sum=sum+d*w w=w*2 one_char=one_char//10 ori+=chr(sum) ini=len1 len1+=8 return ori # returns a character stuffed string def stuffed_str_characterstuffing(string ,flag): ret='' for i in range(len(string)): if string[i]==flag : ret+=flag ret+=string[i] ret= flag+ret +flag return ret # returns the original string def destuffing_char(stuffed_str_char,flag): sliced_str=stuffed_str_char[1:len(stuffed_str_char)-1] #to remove first and last char ret='' for i in range(1,len(sliced_str)): if (sliced_str[i]==sliced_str[i-1]) and sliced_str[i-1]==flag: continue ret=ret+sliced_str[i-1] return ret+sliced_str[-1] # ********** driver function ******************** while(1): choice=int(input("Please enter your choice(1.bit stuffing \t 2.character stuffing\t 3.Quit)\n")) if choice ==1: string=input("Input data to sent?\n") binary_str=toBinary(string) print("binary string : {}".format(binary_str)) stuffed_str=DataAfterBitStuffing(binary_str) print("data after bit stuffing is ::{}".format(stuffed_str)) binary_str2=destuffing(stuffed_str) print("binary data after destuffing is :::{}".format(binary_str2)) originalstr=Back_to_str(binary_str2) print("string after destuffing is:: {}".format(originalstr)) elif choice==2: string=input("Input data to sent?\n") flag=input("Enter the flag character here..?") stuffed_str_char=stuffed_str_characterstuffing(string,flag) print("stuffed string::",stuffed_str_char) final_destuff_char=destuffing_char(stuffed_str_char,flag) print("Data after destuffing ::",final_destuff_char) else: print("********************** END **************************") break
63e1f1008273f5dcd65fd12e22b47886a6be3bec
lautaroGonzalez97/practica2
/ejercicio3.py
262
3.796875
4
texto="Tres tristes tigres, tragaban trigo en un trigal, en tres tristes trastos, tragaban trigo tres tristes tigres." letra = input("ingrese una letra") lista= texto.lower().replace(",","").split() for ele in lista: if ele[0] == letra: print(ele)
332b831f3602141a6dac113e04bf7caee197b9ce
bartkim0426/algorithm-study
/questions/leetcode_199.py
7,815
4.03125
4
# https://leetcode.com/problems/binary-tree-right-side-view/ # 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 ''' TreeNode{ val:1, left: TreeNode{ val: 2, left: None, right: TreeNode{ val: 5, left: None, right: None, } ... } } ''' # 1차. list라고 생각하고 풀어서 class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' # 초반에 root가 list로 잘못 알고 풀어서 실패 binary tree - nodes are incresing with 2**n: 1, 2, 4, 8 ... - Get tree length and "n": len(root) # solution 1: greedy searching - for loop for the root and add stack - add count for the power of 2 (2**n) - if the index is power of 2 -> add to index and make count to 0 - repeat till the end - time complex: O(n) becuase it search all root # solution 2: - return indexs are 0, 2, 6, 14, ... -> 2**n / += 2**(n+1) += 2**(n+2) - find all indexes of them - and return all from root - time complex: O(logn) because it search for power of 2 # solution ''' # solution 2: # find largest 2**n number: n = 0 result = [] q = [root] print(q) index = 0 while True: power = 2 ** n index =+ 2 ** n if index + 1 == len(root): break result.append(q[index]) return result # 2차. root로 풀었는데 실패 -> 이런건 면접관에게 물어볼 수 있으면 물어보면 좋을듯? class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' # 초반에 root가 list로 잘못 알고 풀어서 실패 # root -> TreeNode object # solution 1: finding right only find right treenode till the end -> 이 방식으로는 오른쪽게 아닌데 왼쪽에만 있는 경우를 잡지 못함 ex. [1, 2] -> 2가 왼쪽이 아니고 right side로 취급됨 ''' # If no root, return empty list if not root: return [] result = [] while True: # add first value if not result: result.append(root.val) if not root.right: break result.append(root.right.val) root = root.right return result # 3차. solution 3으로 풀었는데 마지막 rightest value를 찾지 못해서 실패 class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' # 초반에 root가 list로 잘못 알고 풀어서 실패 # root -> TreeNode object # solution 1: finding right only find right treenode till the end -> 이 방식으로는 오른쪽게 아닌데 왼쪽에만 있는 경우를 잡지 못함 ex. [1, 2] -> 2가 왼쪽이 아니고 right side로 취급됨 # solution 2: greddy 전체 tree를 모두 읽어서 리스트 형태로 만들고 푸는 방식 O(n**2) -> 비효율적임 tree를 한 번 읽어서 바로 처리해야 O(n) 형태가 나옴 # solution 3: read tree and find power of 2 - read tree sequentially (left -> right -> left-left -> left-right ...) - memorize the order (index) - if the index is 1, 3, 7, 15 ... (2**n += 2**(n+1) ...) - add it to result - if end before complete 2**n -> add last tree value - O(n) because it read all the nodes # solution 4: find right tree + if not exist, return left - if right tree exits, the whole tree till now must be comopleted - if right tree not exits, the tree is ended: add the most rightest value - find rightest value: is it impossible without read whole tree?? # solution 5: find rightest value from all floor - add node for specific floor - add rightest value to result per floor (last input) ''' # solution 3: result = [] # indexes list indexes = [] index = 0 # number of nodes in the tree is range [0..100] -> max index will be 2**100 for i in range(100): index += 2**i indexes.append(index) prev = None next_node = None left = True index = 1 while True: # First node if index == 1: prev = current current = root left = False # find next root if left: current = root.left next_node = root.right # if right else: current = root.right next_node = nex if index in indexes: result.append(current.val) prev = current index += 1 # 5번째 풀이 from collections import deque class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' # 초반에 root가 list로 잘못 알고 풀어서 실패 # root -> TreeNode object # solution 1: finding right only find right treenode till the end -> 이 방식으로는 오른쪽게 아닌데 왼쪽에만 있는 경우를 잡지 못함 ex. [1, 2] -> 2가 왼쪽이 아니고 right side로 취급됨 # solution 2: greddy 전체 tree를 모두 읽어서 리스트 형태로 만들고 푸는 방식 O(n**2) -> 비효율적임 tree를 한 번 읽어서 바로 처리해야 O(n) 형태가 나옴 # solution 3: read tree and find power of 2 - read tree sequentially (left -> right -> left-left -> left-right ...) - memorize the order (index) - if the index is 1, 3, 7, 15 ... (2**n += 2**(n+1) ...) - add it to result - if end before complete 2**n -> add last tree value - O(n) because it read all the nodes # solution 4: find right tree + if not exist, return left - if right tree exits, the whole tree till now must be comopleted - if right tree not exits, the tree is ended: add the most rightest value - find rightest value: is it impossible without read whole tree?? # solution 5: find rightest value from all floor - add node for specific floor - add rightest value to result per floor (last input) ''' # solution 5: # if no root, return [] if not root: return [] result = [] # create floor with root node floor = deque([[root]]) # loop till the end while floor: current_floor = floor.popleft() print(current_floor) # append rightest value from the floor -> last value from queue result.append(current_floor[-1].val) next_floor = [] for node in current_floor: # append left -> right to next floor if node.left: next_floor.append(node.left) if node.right: next_floor.append(node.right) # add next_floor to floor if next_floor: floor.append(next_floor) return result
6cca9c50b24c23b7b0f45721b84cb06646185442
brpasiliao/Girls_Who_Code_Projects
/commute.py
1,814
3.953125
4
qhome = "walk or drive: " qwalk = "bus or lirr: " qlirr = "subway or speedwalk: " qdrive1 = "lirr or drive: " qdrive2 = "bridge or tunnel: " # def plurality() # if plural == True: # word += "s" # else: # None def end(time, money): hours = time // 60 minutes = time - hours * 60 if time >= 60: print(f"boa, time = {hours} hour & {minutes} minutes, money = ${money}") else: print(f"boa, time = {minutes} minutes, money = ${money}") def back(option): option() def lirr(time, money): time += 40 money += 13.50 user_input = input(qlirr).lower() if user_input == "subway": time += 7 money += 2.75 end(time, money) elif user_input == "speedwalk": time += 15 end(time, money) else: back(lirr) def drive2(time, money): time += 60 user_input = input(qdrive2).lower() if user_input == "bridge": end(time, money) elif user_input == "tunnel": time += 15 end(time, money) else: back(drive2) def drive1(time, money): time += 10 user_input = input(qdrive1).lower() if user_input == "lirr": lirr(time, money) elif user_input == "drive": money += 20 drive2(time, money) else: back(drive1) def walk(time, money): user_input = input(qwalk).lower() if user_input == "bus": time += 30 money += 15 drive2(time, money) elif user_input == "lirr": time += 45 lirr(time, money) else: back(walk) def home(): time = 0 money = 0 user_input = input(qhome).lower() if user_input == "walk": walk(time, money) elif user_input == "drive": drive1(time, money) else: back(home) home()
6558d052e684878a271533df745aa0aaf398d710
apollo-chiu/password-retry
/pssw-try3.py
267
3.84375
4
key = 'a123456' x = 3 while x > 0: x = x - 1 psw = input('請輸入密碼: ') if psw == key: print('登入成功!') break else: print('密碼錯誤!') if x > 0: print('還有', x, '次機會') else: print('沒機會嘗試了! 要鎖帳號了啦!')
a9540bff47bfe8f9939f81c00fefa3348e91675c
tianshuaifei/kaggle
/feature.py
1,222
3.890625
4
import numpy as np #类别变量处理 treat categorical features as numerical ones #1 labelencode #2 frequency encoding #3 mean-target encoding #https://www.kaggle.com/c/petfinder-adoption-prediction/discussion/79981 # Mean-target encoding is a popular technique to treat categorical features as numerical ones. # The mean-target encoded value of one category is equal to the mean target of all samples of # the corresponding category (plus some optional noise for regularization). from sklearn.preprocessing import LabelEncoder for name in f_feature: lab = LabelEncoder() data["le_" + name] = lab.fit_transform(data[name].astype("str")) data["%s_count_num"%fea]=data[fea].map(data[fea].value_counts(dropna=False)) def frequency_encoding(variable): t = df_train[variable].value_counts().reset_index() t = t.reset_index() t.loc[t[variable] == 1, 'level_0'] = np.nan t.set_index('index', inplace=True) max_label = t['level_0'].max() + 1 t.fillna(max_label, inplace=True) return t.to_dict()['level_0'] for variable in ['age', 'network_age']: freq_enc_dict = frequency_encoding(variable) data[variable+"_freq"] = data[variable].map(lambda x: freq_enc_dict.get(x, np.nan))
69b848ed2eeae8f3090a9c35b2cdf12bc4dd29e5
Rita626/HK
/Leetcode/237_刪除鏈表中的節點_05170229.py
1,671
4.21875
4
#題目:请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = None #直觀的認為可以直接刪除 #結果:答案錯誤,只是將要刪除的值變為None而已 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = None #改為以下一節點取代要刪除的值,並將(想像中)重複的下一個節點刪除 #結果:答案錯誤,題目要求的值卻時刪除了,但也將後面的值刪掉了 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next #同樣以下一節點取代要刪除的值,並將後面節點整個前移 #結果:通過,用時28ms,內存消耗13MB
4e485050a23b744142df8dc609002818dd9044c9
Eduardo-Chavez/Unidad2Evaluacio-n
/Iniciales_login.py
194
3.9375
4
usuario = input ("Ingresa tu usuario: ") contra = input ("Ingesa tu contraseña: ") if usuario == "utng" and contra == "mexico": print ("Bienvenido") else: print ("Datos incorrectos")
2991c345efe646cedda8aeaeeebe06b2a4cc6842
drmason13/euler-dream-team
/euler1.py
778
4.34375
4
def main(): """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ test() print(do_the_thing(1000)) def do_the_thing(target): numbers = range(1, target) answer = [] for i in numbers: #print(i) if is_multiple_of(i, 3) or is_multiple_of(i, 5): answer.append(i) #ends here => i won't be a thing after this return(sum(answer)) def test(): result = do_the_thing(10) if result == 23: print("success") print(result) else: print("check again pinhead") print(result) def is_multiple_of(num, multiple): #print("is_multiple_of") return num % multiple == 0 main()
0c9c7fbf5ea0ed3591fd4aee2c9ac9de4b2392a6
paulbradshaw/scrapers
/festivaltweetsjson.py
1,713
3.65625
4
#!/usr/bin/env python import json import csv import requests import urllib import scraperwiki jsonurlgh = 'https://raw.githubusercontent.com/paulbradshaw/scraping-for-everyone/gh-pages/webpages/cheltenhamjazz-export.json' jsonurl = 'https://paulbradshaw.github.io/scraping-for-everyone/webpages/cheltenhamjazz-export.json' trumpjson = 'https://petition.parliament.uk/petitions/178844.json' #fetch the json from the URL response = urllib.urlopen(jsonurl) #load it into variable called x x = json.loads(response.read()) #let's see what we have print x print len(x) #drill down a bit into the 'posts' branch which contains everything print x['posts'] #store that in a new variable posts = x['posts'] #how many items? print len(x['posts']) #this only grabs the ID number of each #create an empty list to store the ID numbers, which we can then loop through to grab each tweet postids = [] for post in posts: print post postids.append(post) #create empty dict to store the data record = {} #loop through the codes for code in postids: print x['posts'][code] #test that we can grab the text print x['posts'][code]['text'] #start storing each field in the dict record['text'] = x['posts'][code]['text'] record['authorid'] = x['posts'][code]['author'] try: record['imageurl'] = x['posts'][code]['image'] except KeyError: record['imageurl'] = 'NULL' record['lon'] = x['posts'][code]['lon'] record['lat'] = x['posts'][code]['lat'] record['timestamp'] = x['posts'][code]['timestamp'] #this is the tweet code that we are using record['tweetid'] = code record['fulljson'] = str(x['posts'][code]) scraperwiki.sql.save(['tweetid'], record)
1ce80703b6e762b4913a7c906fc23143363e2bae
paulbradshaw/scrapers
/westminstercouncilevents.py
1,660
3.578125
4
#!/usr/bin/env python import scraperwiki import urlparse import lxml.html import urllib2 import datetime #more on datetime here: https://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/ now = datetime.datetime.now() currentmonth = now.month currentyear = now.year currentday = now.day print str(now) print "Current month: %d" % currentmonth print "Current year: %d" % currentyear print "Current day: %d" % currentday baseurl = "http://committees.westminster.gov.uk/" #Note the M=6 part of the URL and DD=2018 - these will need to be updated with the current month/year - also D=26 with day juneurl = "http://committees.westminster.gov.uk/mgCalendarAgendaView.aspx?MR=0&M=6&DD=2018&CID=0&OT=&C=-1&D=26" latesturl = "http://committees.westminster.gov.uk/mgCalendarAgendaView.aspx?MR=0&M="+str(currentmonth)+"&DD="+str(currentyear)+"&CID=0&OT=&C=-1&D="+str(currentday) print latesturl record = {} headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} timeout=0.25 req = urllib2.Request(latesturl, None, headers) #adapting some of the code from https://stackoverflow.com/questions/3569152/parsing-html-with-lxml doc = lxml.html.parse(urllib2.urlopen(req)) print doc listlinks = doc.xpath('//ul[@class="mgCalendarWeekEventList"]/li/a') print len(listlinks) for link in listlinks: print link.text_content() print link.attrib['href'] record['event'] = link.text_content() record['url'] = baseurl+link.attrib['href'] record['searchurl'] = latesturl scraperwiki.sqlite.save(['url'], record, table_name="westminsterevents")
01c12a1ab03ab87a404dbd42b9a755be0ed03173
maymashd/BFDjango
/week 1/Informatics mcc/Cycle While/D.py
151
3.5625
4
import math n=int(input()) i=1 ok=False while i<=n: if i==n: ok=True i=i*2 if (ok==True): print("YES") else: print ("NO")
e2e7128884e11dbc5dba935b8986c987663633db
maymashd/BFDjango
/week 1/Informatics mcc/Array/B.py
140
3.609375
4
import array n=int(input()) a=input() arr=a.split(" ") for i in range(0,len(arr)): if (int(arr[i])%2==0): print(arr[i],end=' ')
5ff1f253950b663e79b8d4450e458aa43937d802
maymashd/BFDjango
/week 1/Informatics mcc/Cycle For/K.py
105
3.5
4
import math cnt=0 n=int(input()) for i in range(1,n+1): a=int(input()) cnt=cnt+a print(cnt)
27662057212e19516566758c0cdde3eb883a90a2
valeriuursache/scratchpad
/module 3/cat_strings.py
637
3.71875
4
if __name__ == "__main__": #Concatenation #You can concatenate two strings together using + leia = "I love you." han = "I know." print(leia + ' ' + han) ship = "Millinium Falcon" # Python starts at 0, slices TO the end index (not included) print("'" + ship[10:] + "'") bold_statement = ship + "is the fastest in the galaxy" print (bold_statement) print(ship) ship = 'S' + ship[1:] print(ship) jedi_masters = "Obi-Wan Kenobi, Qui-Gon Gin" print('Anakin' in jedi_masters) council_mermbers = ("Anakin, Obi-Wan Kenobi, Yoda, Qui-Gon Gin") print('Anakin' in council_mermbers)
6f1aa43d0614cd211b0c92a48b182cf662e230fa
nmaswood/Random-Walk-Through-Computer-Science
/lessons/day4/exercises.py
720
4.25
4
def fib_recursion(n): """ return the nth element in the fibonacci sequence using recursion """ return 0 def fib_not_recursion(n): """ return the nth element in the fibonacci sequence using not recursion """ return 0 def sequence_1(n): """ return the nth element in the sequence S_n = S_{n-1} * 2 + 1 """ return 0 def factorial_recursive(n): """ Calculate the factorial of n using recursion """ return 0 class LinkedList(): def __init__(self, val): self.val = val self.next = None """ Use the LinkedList Data Type Create a linked list with the elements "fee" -> "fi" -> "foo" -> "fum" and print it backwards """
5f31e4cdf81801c19d737535ca94fb49ceab59fb
dangriffin13/Project_Euler
/euler21_amicable_numbers.py
662
3.578125
4
import math t = int(input()) def sum_of_divisors(number): s = 0 stop = int(math.floor(math.sqrt(number))) for i in range(2,stop): if number%i == 0: s += i + number/i return int(s+1) amicable_numbers = [] for i in range(100001): y = sum_of_divisors(i) if sum_of_divisors(y) == i and i != y and i not in amicable_numbers: if y < 100001: amicable_numbers.extend([i, y]) #print(amicable_numbers) else: amicable_numbers.append(i) #print(amicable_numbers) for _ in range(t): n = int(input()) print(sum([i for i in amicable_numbers if i < n]))
cd4d8070eeaa1eff50473cb6d89f3cedbf973b66
LawlessJ/Object_Oriented_Programming_Project
/Script.py
2,987
3.703125
4
from datetime import datetime class Menu: def __init__(self, name, items, start_time, end_time): self.name = name self.items = items self.start_time = datetime.strptime(start_time, "%I %p") self.end_time = datetime.strptime(end_time, "%I %p") self.times = [self.start_time, self.end_time] def __repr__(self): return "We are currently serving {name} menu items from {start} until {end}.".format(name = self.name, start=self.start_time, end=self.end_time) def calculate_bill(self, purchased_items): #2 arg is a list total_bill = 0 for item in purchased_items: total_bill += self.items.get(item, 0) return total_bill class Franchise: def __init__(self, address, menus): self.address = address self.menus = menus def __repr__(self): return "This location of Basta Fazzoolin can be found at {address}.".format(address = self.address) def available_menus(self, time): the_time = datetime.strptime(time, "%I %p") for menu_items in range(len(self.menus)): if the_time >= self.menus[menu_items].start_time and the_time <= self.menus[menu_items].end_time: print(self.menus[menu_items]) class Business: def __init__(self, name, franchises): self.name = name self.franchises = franchises brunch = Menu("Brunch", {'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50, 'espresso': 3.00, 'tea': 1.00, 'mimosa': 10.50, 'orange juice': 3.50}, "11 AM", "4 PM") #print(brunch.items) #print(brunch.start_time) early_bird = Menu("Early-bird", {'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza with quattro formaggi': 9.00, 'duck ragu': 17.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 1.50, 'espresso': 3.00,},"3 PM", "6 PM") #print(early_bird.start_time) dinner = Menu("Dinner", {'crostini with eggplant caponata': 13.00, 'ceaser salad': 16.00, 'pizza with quattro formaggi': 11.00, 'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00,},"5 PM","11 PM") kids = Menu("Kids Menu", {'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00}, "11 AM","9 PM") #print(brunch) #print(brunch.items) #print(brunch.calculate_bill(["pancakes", "home fries", "coffee"])) #print(early_bird.calculate_bill(["salumeria plate", "mushroom ravioli (vegan)"])) flagship_store = Franchise("1232 West End Road", [brunch, early_bird, dinner, kids]) new_installment = Franchise("12 East Mulberry Street", [brunch, early_bird, dinner, kids]) #print(new_installment.available_menus("12 PM")) #print(new_installment.available_menus("5 PM")) bus_1 = Business("Basta Fazoolin' with my Heart", [flagship_store, new_installment]) arepas_menu = Menu("Take a' Arepa", {'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa': 7.50}, "10 AM", "8 PM") arepas_place = Franchise("189 Fitzgerald Avenue", [arepas_menu]) bus_2 = Business("Take a' Arepa", [arepas_place])
51ed6228cc6ff33b400a250782b2b0d9b16daf09
RohilH/Convolutional-Neural-Network-using-TensorFlow
/cnnTensorFlow.py
2,468
3.515625
4
from keras.models import Sequential from keras.layers import Dense, Conv2D, Flatten import matplotlib.pyplot as plt from keras.datasets import mnist from keras.utils import to_categorical import numpy as np # (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = np.load("data/x_train.npy") X_train = (X_train - np.mean(X_train, axis=0)) / np.std(X_train, axis=0) y_train = np.load("data/y_train.npy") X_test = np.load("data/x_test.npy") X_test = (X_test - np.mean(X_test, axis=0))/np.std(X_test, axis=0) y_test = np.load("data/y_test.npy") #--------------------------------------------- X_train = X_train.reshape(50000,28,28,1) X_test = X_test.reshape(10000,28,28,1) y_train = to_categorical(y_train) y_test = to_categorical(y_test) ''' The code above simply loads the data and one-hot encode it. We load the MNIST data from the files given to us. ''' #--------------------------------------------- #create model model = Sequential() # allows us to create model step by step #add model layers ''' Kernel size is typically 3 or 5. Experimenting with a value of 4 didn't decrease the accuracy significantly, i.e. only by like 1% or so. ''' model.add(Conv2D(64, kernel_size=5, activation='tanh', input_shape=(28,28,1))) # Adds a convolution layer ''' Each model.add(Conv2D...) essentially adds another layer to the neural network. Instead of using an affine forward to do so, we depend on a convolution instead, taking a square cluster of kernel_size, and looping through the image. At each iteration of the for loop, we take the convolution of the feature (the square cluster) and the part of the image that we're on. Once we do this, we can get a 2D array using the answers from each convolution, based on where in the image each patch is located. ''' model.add(Conv2D(32, kernel_size=3, activation='tanh')) model.add(Flatten()) # Turns 2d array into 1d array model.add(Dense(10, activation='softmax')) # condenses layers down into final 10 classes # compile model using accuracy as a measure of model performance model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ''' Optimizer: 'Adam' an optimizer that adjusts the learning rate while training loss: categorical_crossentropy most commonly used in classification metrics: prints accuracy of CNN ''' #train model model.fit(X_train, y_train,validation_data=(X_test, y_test), epochs=3) # Runs the model
bed140408d860cdaa01ba616ac984a3beb4029ae
benoitantelme/python_ds_ml_bootcamp
/05-Data-Visualization-with-Matplotlib/02-Matplotlib Exercises.py
3,412
3.75
4
#!/usr/bin/env python # coding: utf-8 # ___ # # <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> # ___ # # Matplotlib Exercises # # Welcome to the exercises for reviewing matplotlib! Take your time with these, Matplotlib can be tricky to understand at first. These are relatively simple plots, but they can be hard if this is your first time with matplotlib, feel free to reference the solutions as you go along. # # Also don't worry if you find the matplotlib syntax frustrating, we actually won't be using it that often throughout the course, we will switch to using seaborn and pandas built-in visualization capabilities. But, those are built-off of matplotlib, which is why it is still important to get exposure to it! # # ** * NOTE: ALL THE COMMANDS FOR PLOTTING A FIGURE SHOULD ALL GO IN THE SAME CELL. SEPARATING THEM OUT INTO MULTIPLE CELLS MAY CAUSE NOTHING TO SHOW UP. * ** # # # Exercises # # Follow the instructions to recreate the plots using this data: # # ## Data # In[1]: import numpy as np x = np.arange(0, 100) y = x * 2 z = x ** 2 # ** Import matplotlib.pyplot as plt and set %matplotlib inline if you are using the jupyter notebook. What command # do you use if you aren't using the jupyter notebook?** # In[3]: import matplotlib.pyplot as plt # ## Exercise 1 # # ** Follow along with these steps: ** # * ** Create a figure object called fig using plt.figure() ** # * ** Use add_axes to add an axis to the figure canvas at [0,0,1,1]. Call this new axis ax. ** # * ** Plot (x,y) on that axes and set the labels and titles to match the plot below:** # In[4]: fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) ax.plot(x, y) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('title') # ## Exercise 2 # ** Create a figure object and put two axes on it, ax1 and ax2. Located at [0,0,1,1] and [0.2,0.5,.2,.2] # respectively.** # In[39]: fig2 = plt.figure() ax21 = fig2.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) ax22 = fig2.add_axes([0.2, 0.5, .2, .2]) # ** Now plot (x,y) on both axes. And call your figure object to show it.** # In[42]: ax21.plot(x, y) ax22.plot(x, y) # ## Exercise 3 # # ** Create the plot below by adding two axes to a figure object at [0,0,1,1] and [0.2,0.5,.4,.4]** # In[6]: fig3 = plt.figure() ax31 = fig3.add_axes([0.1, 0.1, 0.9, 0.9]) # left, bottom, width, height (range 0 to 1) ax32 = fig3.add_axes([0.17, 0.5, .4, .4]) # ** Now use x,y, and z arrays to recreate the plot below. Notice the xlimits and y limits on the inserted plot:** # In[5]: ax31.plot(x, z) ax31.set_xlabel('x') ax31.set_ylabel('z') ax32.plot(x, y) ax32.set_xlabel('x') ax32.set_ylabel('y') ax32.set_title('zoom') # ## Exercise 4 # # ** Use plt.subplots(nrows=1, ncols=2) to create the plot below.** # In[48]: fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,2)) # ** Now plot (x,y) and (x,z) on the axes. Play around with the linewidth and style** # In[51]: axes[0].plot(x, y, 'g') axes[0].set_xlabel('x') axes[0].set_ylabel('y') axes[0].set_title('plot 1') axes[1].plot(x, z, 'r') axes[1].set_xlabel('x') axes[1].set_ylabel('z') axes[1].set_title('plot 2') plt.show() # ** See if you can resize the plot by adding the figsize() argument in plt.subplots() are copying and pasting your # previous code.** # In[32]: # # Great Job!
d460b9928fa6276cd94ab510d3c24b7aa8932a34
shanefay/MachineLearning
/assignment2/estimate_scorer.py
2,528
3.515625
4
from sklearn.metrics import make_scorer from sklearn.model_selection import train_test_split, cross_validate def split_estimate(estimator, X, y, metrics, test_size=0.3): """Score an estimated model using a simple data split. A 70/30 split of training to testing data is used by default. Args: estimator: Scikit-learn model estimator. X: Feature data matrix. y: Target data array. metrics: Metrics to be used for scoring the estimated model. A Dictionary of metric names to metric evaluation functions. e.g. {'accuracy': scklearn.metrics.accuracy_score, etc.} test_size (optional): The proportion of the data to be used for testing. Returns: A dictionary of metric names to scores. The scores are the metrics on the test targets verses predicted targets. """ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, shuffle=False) estimator.fit(X_train, y_train) y_pred = estimator.predict(X_test) # print(y_test,y_pred) # print(y_test.min) return {name: metric(y_test, y_pred) for name, metric in metrics.items()} def cross_val_estimate(estimator, X, y, metrics, k_fold=20): """Score an estimated model using k-fold cross validation. 20-fold cross validation is used by default. Args: estimator: Scikit-learn model estimator. X: Feature data matrix. y: Target data array. metrics: Metrics to be used for scoring the estimated model. A Dictionary of metric names to metric evaluation functions. e.g. {'accuracy': scklearn.metrics.accuracy_score, etc.} test_size (optional): The proportion of the data to be used for testing. Returns: A dictionary of metric names to scores. The scores are the metrics on the k-fold test targets verses predicted targets. As there are k-fold test sets, the mean of each metric is taken as the scores with a confidence interval (20-fold gives 90% CI). """ scoring = {name: make_scorer(metric) for name, metric in metrics.items()} scores = cross_validate(estimator, X, y, cv=k_fold, scoring=scoring) return {name: confidence_interval_score(scores['test_' + name]) for name in scoring} def confidence_interval_score(score_list): mean = score_list.mean() score_list.sort() low = score_list[1] high = score_list[-2] return '{:.3f} [{:+.3f}, {:+.3f}]'.format(mean, low-mean, high-mean)
4d0f3b2e8eb544407de5ed9cd04ef2347628ff19
Inlinesoft/POC.ECS.Python.App
/utilities/email.py
2,975
3.59375
4
import smtplib import definitions class Email: """ Send out emails (with or without attachments) using this class. Usage: With attachment email = Email(server_name) email.send_mail(send_from, send_to, subject, text, files) Without attachment email = Email() email.send_mail(send_from, send_to, subject, text) """ # variable _user_name = None _server = None # methods def __init__(self): """ This method initialises the local variable :return: none """ # Initialize the User name self._server = smtplib.SMTP(definitions.EMAIL_PRIMARY_SMTP_ADDRESS, 587) self._user_name = definitions.EMAIL_ACCOUNT_USERNAME self._password = definitions.EMAIL_ACCOUNT_PASSWORD self._server = smtplib.SMTP('smtp.gmail.com') self._server.ehlo() self._server.starttls() self._server.login(self._user_name, self._password) def __str__(self): """ This is to return the calss name, which will can be used to pass to the logging methods :return: A string with class details """ ret_data = f"<<{self.__class__.__name__}>> :: " return ret_data def set_user_name(self, user_name): """ setter method for user_name :param user_name: :return: """ self._user_name = user_name def get_user_name(self): """ getter method for username :param user_name: :return: """ return self._user_name def set_password(self, password): """ setter method for password :param password: :return: """ self._password = password def get_password(self): """ getter method for password :param password: :return: """ return self._password def set_smtp_server(self, value): """ setter method for server :param value: :return: """ self._server = value def get_smtp_server(self): """ getter method for smtp server :return: """ return self._server def send_mail_using_smtp(self, send_from, send_to, subject, text, files=None, text_type='text'): """ Send mail sends out email to list of email participants :param send_from: :param send_to: :param subject: :param text: :param files: :param server: :return: """ is_email_sent = True try: body = '\r\n'.join(['To: %s' % send_to, 'From: %s' % send_from, 'Subject: %s' % subject, '', text]) self._server.sendmail(send_from, send_to, body) except Exception as exp: raise (exp) return is_email_sent
2512b1f39ae0d570fae3dda36f2950254a085549
jfernand196/Ejercicios-Python
/funcion_all.py
146
3.71875
4
# verificarf que todos los items iteravles cumplan una condicion lista = [2, 4, 6, 7] print(all(x > 4 for x in lista)) h = "juan" print(type(h))
60dab56c8c06bc13f3c182ec1dbb11832298c6d2
jfernand196/Ejercicios-Python
/farmeteos de string y float.py
190
3.734375
4
palabra = "!aprendiendo python!" print("%.6s" % palabra) print("%.12s" % palabra) real = 2.6578 print("valor es: %f" % real) print("valor es: %.2f" % real) print("valor es: %.13f" % real)