blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
bd3d80133d7780eaacc843d4f7f9a144a6a56802
testmywork77/WorkspaceAbhi
/Year 8/Concatenation_Practice.py
1,042
4.34375
4
name = "Abhinav" age = "11" fav_sport = "Cricket" fav_colour = "red" fav_animal = "lion" # Create the following sentences by using concatenation # Example: A sentence that says who he is and how old he is print("My name is " + name + " and I am " + age + " ,I like to play " + fav_sport) # NOTE: Don't forget about spaces. # 1. Write a sentence below that includes the variables name and fav_sport. # 2. Write a sentence below that includes the variables fav_colour and fav_animal. # 3. Write a sentence below that includes the variables age and fav_sport. # 4. Write a sentence below that includes all the variables. print("My name is " + name + " and my favorate sport is " + fav_sport) print("My favorate colour is " + fav_colour + " and my favorate animal is a " + fav_animal) print("I am " + age + " years old. My favorate sport is " + fav_sport) print ("My name is " + name + " I am " + age + " years old. My favorate sport is " + fav_sport + " My favorate colour is " + fav_colour + " and my favorate animal is a " + fav_animal)
true
d1c7cadba59a9c79cf30df4167483821263c15e5
krishnaja625/CSPP-1-assignments
/m6/p3/digit_product.py
416
4.125
4
''' Given a number int_input, find the product of all the digits example: input: 123 output: 6 ''' def main(): ''' Read any number from the input, store it in variable int_input. ''' N3 = int(input()) N2 = N3 N = abs(N3) S = 0 K = 0 if N > 0: S = 1 while N > 0: N2 = N%10 S = S*N2 N = N//10 if N3 >= 0: print(S) else: K = -1*S print(K) if __name__ == "__main__": main()
true
065d5fda40b2c6f28f7736e946076f3b3d709f27
Santoshi321/PythonPractice
/ListExcercise.txt
1,866
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 8 15:06:30 2019 @author: sgandham """ abcd = ['nintendo','Spain', 1, 2, 3] print(abcd) # Ex1 - Select the third element of the list and print it abcd[2] # Ex2 - Type a nested list with the follwing list elements inside list abcd mentioned above and print it newlist = [54,76] abcd.append(newlist) print (abcd) # Ex3 - Print the 1 and the 4 position element in the following list nestedlist = ["shail", [11,8, 4, 6], ['toronto'],abcd, "abcd"] print(nestedlist[1]) print(nestedlist[4]) # Ex4 - add the following 2 lists and create list3 and print - remove string items too list1= [10, 20, 'company', 40, 50, 100] list2 = [100, 200, 300, 'orange', 400, 500,1000] del list1[2] print(list1) del list2[3] list3=list1+list2 print(list3) # Ex 5 - print the lenght of the list3 print(len(list3)) # Ex 6 Add 320 to list 1 and print list1.append(320) print(list1) #list1+320 #Ex 7 - Add parts of list1 & 2 by tking first 4 elements from list1 and last 2 elements from list2 newlist=list1[:5] + list2[5:] print(newlist) #ex 8 check if 99 is in list 1 99 in list1 #ex 9 check if 99 is not in list 1 99 not in list1 # concatenation (+) and replication (*) operators #ex 10 - CONCATENANTE list 1 and ['cool', 1990] list1+['cool',1990] # Ex 11 - triplicate the list 1 list1*3 # ex 12 - find min & max of list2 max(list2) min(list2) # append & del # Ex 13 append 'training' to list 1 list1.append('training') list1.pop() # Ex 14 delete 2nd position element from list 2 del list2[1] # Ex 15 - iterate over list1 and print all elements by adding 10 to each element # for x in list1: list1= [10, 65,20, 30,93, 40, 50, 100] for x in list1: print(x+10) #Ex 16 sorting #sort list1 by ascending order list1.sort() #sort list1 by reverse order list1.sort(reverse=True)
true
3630cc5aeda264cc010df9809a3ef48d809b9cb3
myNameArnav/dsa-visualizer
/public/codes/que/que.py
1,771
4.25
4
# Python3 program for array implementation of queue INT_MIN = -32768 # Class Queue to represent a queue class Queue: # __init__ function def __init__(self, capacity): self.front = self.size = 0 self.rear = capacity - 1 self.array = [None]*capacity self.capacity = capacity # Queue is full when size becomes # equal to the capacity def isFull(self): return self.size == self.capacity # Queue is empty when size is 0 def isEmpty(self): return self.size == 0 # Function to add an item to the queue. # It changes rear and size def enqueue(self, item): if self.isFull(): return self.rear = (self.rear + 1) % (self.capacity) self.array[self.rear] = item self.size += 1 print(item, "enqueued to queue") # Function to remove an item from queue. # It changes front and size def dequeue(self): if self.isEmpty(): return INT_MIN print(self.array[self.front], "dequeued from queue") self.front = (self.front + 1) % (self.capacity) self.size -= 1 # Function to get front of queue def qfront(self): if self.isEmpty(): return INT_MIN return self.array[self.front] # Function to get rear of queue def qrear(self): if self.isEmpty(): return INT_MIN return self.array[self.rear] # Driver Code queue = Queue(1000) queue.enqueue(10) queue.enqueue(100) queue.enqueue(-1) queue.dequeue() print("Front item is", queue.qfront()) print("Rear item is", queue.qrear()) # Output: # 10 enqueued to queue # 100 enqueued to queue # -1 enqueued to queue # 10 dequeued from queue # Front item is 100 # Rear item is -1
true
ed57a1ae2c3abd176cf440c00857b411899dd32e
myNameArnav/dsa-visualizer
/public/codes/dfs/dfs.py
1,868
4.28125
4
# Python3 program to implement DFS # This function adds an edge to the graph. # It is an undirected graph. So edges # are added for both the nodes. def addEdge(g, u, v): g[u].append(v) g[v].append(u) # This function does the Depth First Search def DFS_Visit(g, s): # Colour is gray as it is visited partially now colour[s] = "gray" global time time += 1 d[s] = time print(s, end=" ") # This loop traverses all the child nodes of u i = 0 while i < len(g[s]): # If the colour is white then # the said node is not traversed. if (colour[g[s][i]] == "white"): p[g[s][i]] = s # Exploring deeper DFS_Visit(g, g[s][i]) i += 1 time += 1 f[s] = time # Now the node u is completely traversed # and colour is changed to black. colour[s] = "black" def DFS(g, n): # Initially all nodes are not traversed. # Therefore, the colour is white. # global because the variables in the parent scope needs to be used here global colour, p, d, f, time colour = ["white"] * n p = [-1] * n d = [0] * n f = [0] * n time = 0 # Calling DFS_Visit() for all # white vertices print("DFS Order is : ", end="") for i in range(n): if (colour[i] == "white"): DFS_Visit(g, i) # Driver Code # Graph with 11 nodes and 11 edges. n = 11 # Declaring the vectors to store color,predecessor, # and time stamps d and f colour = [None] * n p = [None] * n d = [None] * n f = [None] * n time = 0 # The Graph vector g = [[] for i in range(n)] addEdge(g, 0, 1) addEdge(g, 1, 2) addEdge(g, 2, 3) addEdge(g, 1, 4) addEdge(g, 4, 5) addEdge(g, 4, 6) addEdge(g, 4, 7) addEdge(g, 6, 9) addEdge(g, 7, 8) addEdge(g, 7, 9) addEdge(g, 8, 10) DFS(g, n) # Output: # DFS Order is : 0 1 2 3 4 5 6 9 7 8 10
true
d78d4b827bc6013444e4db630cd1261773a0bea8
Bcdirito/django_udemy_notes
/back_end_notes/python/level_two/object_oriented_notes/oop_part_two.py
791
4.53125
5
# Example class Dog(): # Class Object Attributes # Always go up top species = "Mammal" # initializing with attributes def __init__(self, breed, name): self.breed = breed self.name = name # can be done without mass assignment my_dog = Dog("German Shepherd", "Louis") # can be done with mass assignment other_dog = Dog(breed = "Huskie", name="Hughie") print(my_dog.breed, my_dog.species) print(other_dog.name) # Example 2 class Circle(): pi = 3.14 def __init__(self, radius=1): self.radius = radius def area(self): return Circle.pi * self.radius**2 def set_radius(self, new_r): self.radius = new_r default_circle = Circle() print(default_circle.radius) my_circle = Circle(3) print(my_circle.area())
true
f4ddf222cd4c3d87ffee555eb23937de49298016
AshurMotlagh/CECS-174
/Lab 3.13.py
223
4.375
4
## # Print the first 3 letters of a string, followed by ..., followed by the last 3 letters of a string. ## word = input("Enter a word with longer than 8 letters: ") print("The new word is", word[0:3], "...", word[-3:])
true
5b52810c905e0213d4e30a36931640fe503e8f09
ivelinakaraivanova/SoftUniPythonFundamentals
/src/Lists_Advanced_Exercise/01_Which_Are_In.py
265
4.15625
4
first_list = input().split(", ") second_list = input().split(", ") result_list =[] for item in first_list: for item2 in second_list: if item in item2: if item not in result_list: result_list.append(item) print(result_list)
true
0b246053cbffe4fa6a52f10f5a0982052cdebf4f
azdrachak/CS212
/212/Unit2/HW2-2.py
1,564
4.125
4
#------------------ # User Instructions # # Hopper, Kay, Liskov, Perlis, and Ritchie live on # different floors of a five-floor apartment building. # # Hopper does not live on the top floor. # Kay does not live on the bottom floor. # Liskov does not live on either the top or the bottom floor. # Perlis lives on a higher floor than does Kay. # Ritchie does not live on a floor adjacent to Liskov's. # Liskov does not live on a floor adjacent to Kay's. # # Where does everyone live? # # Write a function floor_puzzle() that returns a list of # five floor numbers denoting the floor of Hopper, Kay, # Liskov, Perlis, and Ritchie. import itertools def higher(f1, f2): """ Returns True if floor f1 is higher than floor f2 """ return True if f1 - f2 > 0 else False def adjacent(f1, f2): """ Returns True if floors f1 and f2 are adjacent to each other """ return True if abs(f1 - f2) == 1 else False def floor_puzzle(): """ Solves Floor puzzle. Returns a list of five floor numbers denoting the floor of Hopper, Kay, Liskov, Perlis, and Ritchie. """ floors = [1,2,3,4,5] c_floors = itertools.permutations(floors) order = next([Hopper, Kay, Liskov, Perlis, Ritchie] for Hopper, Kay, Liskov, Perlis, Ritchie in c_floors if (Hopper != 5) and (Kay != 1) and (Liskov != 1 and Liskov != 5) and (higher(Perlis, Kay)) and (not adjacent(Ritchie, Liskov)) and (not adjacent(Liskov, Kay))) return order print floor_puzzle()
true
75fa0274e9cfd4193bb5d1730caf90b2b0c5b194
edagotti689/PYTHON-7-REGULAR-EXPRESSIONS
/1_match.py
508
4.15625
4
''' 1. Match is used to find a pattern from starting position ''' import re name = 'sriram' mo = re.match('sri', name) print(mo.group()) # matching through \w pattern name = 'sriram' mo = re.match('\w\w\w', name) print(mo.group()) # matching numbers through \d pattern name = 'sriram123' mo = re.match('\d\d\d', name) print(mo.group()) ''' Error:1 File "1_match.py", line 18, in <module> print(mo.group()) AttributeError: 'NoneType' object has no attribute 'group' '''
true
a59503d23f606bad8fc8ff6c68001e6ea1783431
Rd-Feng/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
257
4.125
4
#!/usr/bin/python3 """Define MyList that extends list""" class MyList(list): """add print_sorted instance method that prints the list in sorted order""" def print_sorted(self): """print list in sorted order""" print(sorted(self))
true
705cc760876474bc595a7244895ea27ecb875d76
shrirangmhalgi/Python-Bootcamp
/25. Iterators Generators/iterators.py
495
4.34375
4
# iterator is object which can be iterated upon An object which returns data, one at a time when next() is called on it name = "Shrirang" iterator = iter(name) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) # StopIteration error is thrown at the end of iterator # iterable is object which returns a iterator when iter() method is called on it
true
2302ed436657bca98feffd12477b4294ba12313b
shrirangmhalgi/Python-Bootcamp
/8. Boolean Statements/conditional_statements.py
789
4.125
4
name = input("Enter a name:\n") if name == "shrirang": print("Hello Shrirang") elif name == "suvarna": print("Hello Suvarna") elif name == "rajendra": print("Hello Rajendra") else: print("Hello User") # truthiness and falsiness # (is) is used to evaluate truthiness and falsiness # falsiness includes # None, Empty strings, Empty objecs and zero # and or not a = 1 b = 0 if a and b: print(f"{a} and {b} is true") else: print(f"{a} and {b} is false") if a or b: print(f"{a} or {b} is true") else: print(f"{a} or {b} is false") if not b: print(f"not {a} is {not a}") # is vs == # is checks that whether they are stored in same memory address # == checks the values inside them # a = [1, 2, 3] # b = [1, 2, 3] # a == b gives true # a is b gives false
true
d81cadb1c01234f822fab833bc67f06b8c0cfa10
shrirangmhalgi/Python-Bootcamp
/20. Lambdas and Builtin Functions/builtin_functions.py
1,851
4.125
4
import sys # 1. all() returns true if ALL elements of iteratable are truthy print(all(list(range(10)))) print(all(list(range(1, 10)))) # 2. any() returns true if ANY of the element is truthy print(any(list(range(10)))) print(any(list(range(1, 10)))) # 3. sys.getsizeof print(sys.getsizeof([x % 2 == 0 for x in range(1000)])) print(sys.getsizeof((x % 2 == 0 for x in range(1000)))) # (x % 2 == 0 for x in range(1000)) is a generator # 4. sorted() sorts things list1 = list(range(10, 0, -1)) dict1 = [dict(name = "shrri"), dict(name = "hrri", last = "rang")] print(sorted(list1)) print(sorted(list1, reverse = True)) print(sorted(dict1, key = lambda user : user['name'], reverse = True)) # 5. min() finds the minimum element print(min(list1)) print(min(list1, key = lambda n : n > 5)) # 6. max() finds the maximum element print(max(list1)) print(max(list1, key = lambda n : n < 2)) # 7. reversed returns a reverse iterator for i in reversed(list1): print(i) print(''.join(list(reversed("hello world")))) # 8. len print("hello".__len__()) # 9. abs returns the absolute value of a number print(abs(-1.2)) print(abs(-1)) print(abs(1.2)) print(abs(1)) # 10. sum returns the sum of the collection print(sum(list1, 100)) # 11. round rounds off the given number print(round(1.212121, 2)) print(round(1.5)) # 12. zip is used to bind 2 or more collections together it stops as soon as the shortest iterable is exhausted list1 = list(range(10, 20)) list2 = list(range(20, 30)) print(dict(zip(list1, list2))) midterms = [80,91,78] finals = [98,89,53] students = ['dan', 'ang', 'kate'] print({pair[0] : max(pair[1], pair[2]) for pair in zip(students, midterms, finals)}) print(dict(zip(students, map(lambda pair: max(pair), zip(midterms, finals))))) print(dict(zip(students, map(lambda pair: ((pair[0] + pair[1]) / 2), zip(midterms, finals)))))
true
713b3b42119f727b8e3bc59a09a6f0f27e748339
shrirangmhalgi/Python-Bootcamp
/12. Lists/lists.py
1,903
4.53125
5
# len() function can be used to find length of anything.. # lists start with [ and end with ] and are csv task = ["task 1", "task 2", "task 3"] print(len(task)) # prints the length of the list... list1 = list(range(1, 10)) # another way to define a list # accessing data in the lists # lists are accessed like arrays.. 0, 1, 2 ... and to count it backwards, start with negative -1, -2, -3 ... print(task[0]) print(task[1]) print(task[2]) # to check if value exists in a list or not use the in operator print("task 1" in task) # iterate through lists for i in task : print(i) i = 0 while i != len(task) : print(f"task {i} : " + str (task[i])) i += 1 # some list methods # 1. append(123) -> appends the data in the list a = [] a.append(1) print(a) # 2. extend([list]) -> attaches multiple items to the list a.extend([2, 3, 4]) print(a) # 3. insert(position, data) a.insert(2, "shrirang") print(a) # 4. clear() removes all the elements from the list a.clear() print(a) # 5. pop(index number) a.extend([2, 3, 4]) a.pop() # -> removes last element from the list a.pop(0) # -> removes the element specified by index number print(a) # 6. remove(x) x is a value but remove does not return a value a.remove(3) print(a) # 7. index(value) returns the first index of the value present in the list a.extend([2, 3, 4]) print(a.index(2)) print(a.index(2, 1)) # -> finds the first index of 2 starting from 1 print(a.index(2, 1, 2)) # -> finds the first index of 2 starting from 1 and ending index of 2 # 8. count() -> returns the count of the number present in the list print(a.count(2)) # 9. reverse() -> reverses the current list a.reverse() print(a) # 10. sort() a.sort() print(a) # 11. join " ".join(a) # tasks = ["task " + str(i) for i in range(1, 4)] # print(tasks) # a=[0]*10 # b=[0 for i in range(10)] # print(a) # print(b) # a[2]=9 # b[2]=9 # print(a) # print(b)
true
4a9158546b978eb121262bb114def980bfbc2ca9
shrirangmhalgi/Python-Bootcamp
/30. File Handling/reading_file.py
528
4.1875
4
file = open("story.txt") print(file.read()) # After a file is read, the cursor is at the end... print(file.read()) # seek is used to manipulate the position of the cursor file.seek(0) # Move the cursor at the specific position print(file.readline()) # reads the first line of the file file.seek(0) print(file.readlines()) # Reads all the contents of the file and stores it in a list # Make sure you close the files when you are done... file.close() # returns a value to check whether the file is closed or not... file.closed
true
d7df6511316ed65740cca6f8570f152fad2637fe
chivitc1/python-turtle-learning
/turtle15.py
552
4.15625
4
""" animate1.py Animates the turtle using the ontimer function. """ from turtle import * def act(): """Move forward and turn a bit, forever.""" left(2) forward(2) ontimer(act, 1) def main(): """Start the timer with the move function. The user’s click exits the program.""" reset() shape("turtle") speed(0) up() exitonclick() # Quit the program when the user clicks the mouse listen() ontimer(act, 1) return "Done!" if __name__ == '__main__': msg = main() print(msg) mainloop()
true
1731be54e0a9905f6f751a97808931ce54e0bec0
chivitc1/python-turtle-learning
/menuitem_test.py
1,121
4.28125
4
""" menuitem_test.py A simple tester program for menu items. """ from turtle import * from menuitem import MenuItem from flag import Flag INDENT = 30 START_Y = 100 ITEM_SPACE = 30 menuClick = Flag() def changePenColor(c): """Changes the system turtle’s color to c.""" menuClick.value(True) color(c) def createMenu(callback): """Displays 6 menu items to respond to the given callback function.""" x = -(window_width() / 2) + INDENT y = START_Y colors = ("red", "green", "blue", "yellow", "purple", "black") shape = "circle" for color in colors: MenuItem(x, y, shape, color, callback) y -= ITEM_SPACE def skip(x, y): "Moves the pen to the given location without drawing." if not menuClick.value(): up() goto(x, y) down() else: menuClick.value(False) # Reset when menu item selected def main(): """Creates a menu for selecting colors.""" reset() shape("triangle") createMenu(changePenColor) onscreenclick(skip) listen() return "Done" if __name__ == '__main__': main() mainloop()
true
4dfa7c1f1f9f51b838fcfb7e7d6c9f5f4fad2d42
chivitc1/python-turtle-learning
/turtle17.py
1,508
4.46875
4
""" testpoly.py Illustrates the use of begin_poly, end_poly, and get_poly to create custom turtle shapes. """ from turtle import * def regularPolygon(length, numSides): """Draws a regular polygon. Arguments: the length and number of sides.""" iterationAngle = 360 / numSides for count in range(numSides): forward(length) left(iterationAngle) def makeShape(length, numSides, shapeName): """Creates and registers a new turtle shape with the given name. The shape is a regular polygon with the given length and number of sides. Arguments: the length, number of sides, and shape name.""" up() goto(0,0) setheading(0) begin_poly() regularPolygon(length, numSides) end_poly() shape = get_poly() addshape(shapeName, shape) def main(): """Creates two turtles with custom shapes and allows you to drag them around the window.""" hideturtle() speed(0) makeShape(length=40, numSides=5, shapeName="pentagon") makeShape(length=20, numSides=8, shapeName="octagon") turtle1 = Turtle(shape="pentagon") turtle1.color("brown", "green") turtle1.up() turtle1.goto(100, 50) turtle1.tilt(angle=90) turtle2 = Turtle(shape="octagon") turtle2.color("blue", "pink") turtle2.up() turtle1.ondrag(lambda x, y: turtle1.goto(x, y)) turtle2.ondrag(lambda x, y: turtle2.goto(x, y)) listen() return "Done!" if __name__ == '__main__': msg = main() print(msg) mainloop()
true
dab151fa8d3e2045bd5fab97d96c7ed1e1e9fe7f
MichaelTennyson/OOP
/lab3(practice).py
516
4.5
4
# The following program scrambles a string, leaving the first and last letter be # the user first inputs their string # the string is then turned into a list and is split apart # the list of characters are scrambled and concatenated import random print("this program wil take a word and will scramble it \n") word = input("enter the word\n") word_list = list(word) for i in range(len(word_list)): random.shuffle(word_list[1:-1]) scrambled_word = "".join(word_list) print(scrambled_word)
true
4e44b69e698e6f9435bc9e147b473398e8c794e1
DanielShin2/CP1404_practicals
/prac05/emails.py
624
4.1875
4
def name_from_email(email): username = email.split("@")[0] parts = username.split(".") name = " ".join(parts).title() return name def main(): email_name = {} email = input("Enter your email: ") while email != "": name = name_from_email(email) correct = input("Is your name {}? (Y/N): ".format(name)).upper() if correct.upper() == "N" or correct != "": name = input("Enter your name: ") email = input("Enter your email: ") email_name[email] = name for email, name in email_name.items(): print("{} ({})".format(name, email)) main()
true
7b7ae24c2bf54988394165e6c63c165a84472f0e
mrudulamucherla/Python-Class
/2nd assign/dec to binary,.py
510
4.25
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 9 16:19:30 2020 @author: mrudula """ #write prgm to convert decimal to binary number sysytem using bitwise operator binary_num=list() decimal_num=int(input("enter number")) for i in range(0,8): shift=decimal_num>>i #code to check value of last bit and append 1 or 0 to list make binary number if shift&1: binary_num.append(1) else: binary_num.append(0) for j in range(-1,-9,-1): print(binary_num[j],end="")
true
d99c43ed6e3f8ff9cbd3ee31063216578a3702f5
mrudulamucherla/Python-Class
/While Loop,134.py
236
4.21875
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 7 14:13:32 2020 @author: mrudula """ #Print all 3 multiples from 1 to 100 using for while loop. while True: for i in range (1,101): print(i*3,end=" ") break
true
4cf6cf7d66050a5a9a4f2ef8f7ad48b5f20d9dc3
lilbond/bitis
/day1/exploring.py
2,508
4.53125
5
""" Samples below are intended to get us started with Python. Did you notice this is a multi-line comment :-) and yes being the first one and before code, it qualifies to be documentation as well. How Cool!!! In order to be a docstring it had to be multi-line """ # print hello world :-), Hey this is a single line comment print("Hello, World") ''' We can define strings using ' (single quotes) or using " (double quotes) Same goes for comments, did you notice this one. Assignment ---------- print messages below: 1. You won't be disappointed with Python 2. One day you will say "I love Python" 3. You won't be disappointed with Python. One day you will say "I love Python" ''' # Getting rid of new line print("Hello", end='') print(", World!!!") # Working with variables is damn easy an_int = 1 a_string = "We won't work with other types today. Yes, there are many more." ''' There is no verbosity like - int anInt = 1; or String aString = "Something"; ''' # Programming is all about decision making, is not it? if an_int == 1: print(a_string) # A decision without a negative case is not so useful if an_int == 2: print(a_string) else: print("Damn it was not true!!!") # Ah! that was nice but how can I take more than one decisions if an_int == 2: print("It is 2 indeed") elif an_int == 1: print("It is 1 indeed") else: print("I seriously have not idea, what it is") ''' Do we just keep scripting in Python or can we package snippets and reuse Did not you realize, what print is? Yes, it is a function. A callable, reusable and self contained unit of code. Provides a logical grouping and helps in organizing snippets to perform unit of work. Disclaimer: I am NOT good at definitions and this one is purely self cooked :-) ''' def greet_awesome_people(): print("Hello Awesome People. I am a dumb function but teaches a very powerful thing. \nGuess what?") # Guess what? greet_awesome_people() # Same goes for me, guess guess :-) def i_am_bit_smarter(message): print(message) # And same goes for me def i_am_bit_more_smarter(a, b): return a + b i_am_bit_smarter("Custom Message>> Sum of 10 and 2 is : " + str(i_am_bit_more_smarter(10, 2))) ''' Assignment ---------- Write the smartest calculator which: - Works only with integer - Handles add, subtract, mul and divide client should be able to use your calculator like: add(10,2), subtract(11, 3) etc. ''' # Time to evaluate our guess and together try to get a bit of programming Moksha :-).
true
ab4ad6fb7096a9276d614b2d0b4a97276f1c2512
cpucortexm/python_IT
/python_interacting _with_os/logfile/parse_log.py
1,985
4.3125
4
#!/usr/bin/env python3 import sys import os import re ''' The script parses the input log file and generates an output containing only relevant logs which the user can enter on command prompt ''' def error_search(log_file): error = input("What is the error? ") # input the error string which you want to see in the output returned_errors = [] with open(log_file, mode='r',encoding='UTF-8') as file: for log in file.readlines(): error_patterns = ["error"] # default pattern is "error" for i in range(len(error.split(' '))): # split the input string into a list error_patterns.append(r"{}".format(error.split(' ')[i].lower())) # keep appending every word of the input string split by space to list of patterns if all(re.search(error_pattern, log.lower()) for error_pattern in error_patterns): # use regex to compare the list of patterns with each log line returned_errors.append(log) # append every line which matches to all the patterns in the list file.close() return returned_errors def file_output(returned_errors): with open(os.path.expanduser('~') + '/Desktop/python-coursera/logfile/errors_found.log', 'w') as file: for error in returned_errors: file.write(error) file.close() ''' If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name. Every Python module has it’s __name__ defined and if this is ‘__main__’, it implies that the module is being run as a standalone by the user and we can do corresponding appropriate actions. If you import this script as a module in another script, the __name__ is set to the name of the script/module. ''' if __name__ == "__main__": log_file = sys.argv[1] returned_errors = error_search(log_file) file_output(returned_errors) sys.exit(0)
true
3802612e9ba51aaa8d3307e8ab39d413dc8b6d20
nguyntony/class
/large_exercises/large_fundamentals/guess2.py
1,553
4.21875
4
import random on = True attempts = 5 guess = None print("Let's play a guessing game!\nGuess a number 1 and 10.") while on: # correct = random.randint(1, 10) while True: try: guess = int(input()) break except ValueError: print("Please give a number!") correct = random.randint(1, 10) print(correct) if guess < 1 or guess > 10: print(f"{guess} is not a number between 1 and 10.") print("Try again.") elif guess == correct: print( f"YES! I was thinking of the number: {correct}\nYou win!") # I need this to ask if we want to play again decision = input("Play again? ( Y / N ) ").lower() if decision == "no" or decision == "n": print("Goodbye!") on = False else: print("Guess another number!") else: if guess < correct: print("Your guess is too low.") else: print("Your guess is too high.") print("NOPE! Try again.") attempts -= 1 if attempts != 0: print(f"You have {attempts} remaining guesses.") else: print("You ran out of guesses!") print("You lose!") # I need to ask to see if they wanna play again. decision = input("Play again? ( Y / N ) ").lower() if decision == "no" or decision == "n": print("Goodbye!") on = False else: print("Guess another number!")
true
9148ba1063ba78923a760707e24d3f3e78a2fab1
nguyntony/class
/python101/strings.py
303
4.1875
4
# interpolation syntax first_name = "tony" last_name = "nguyen" print("hello %s %s, this is interpolation syntax" % (first_name, last_name)) # f string print(f"Hi my name is {first_name} {last_name}") # escape string, you use the back slash \ # \n, \t # concatenating is joining two things together
true
518a262e0db8dc3b9a9645f41f331ee79794dc54
nguyntony/class
/python102/dict/ex1_dict.py
458
4.21875
4
siblings = {} # for a list you can not create a new index but in a dictionary you can create a new key with the value at any time. siblings["name"] = "Misty" siblings["age"] = 15 siblings["fav_colors"] = ["pink", "yellow"] siblings["fav_colors"].append("blue") print(siblings) # loop # key for key in siblings: print(key) # values for key in siblings: print(siblings[key]) # key and values for key in siblings: print(key, siblings[key])
true
aa4105b0f27729de85e91b4a106d25509b6a991d
nguyntony/class
/python102/list/ex3_list.py
1,185
4.375
4
# Using the code from exercise 2, prompt the user for which item the user thinks is the most interesting. Tell the user to use numbers to pick. (IE 0-3). # When the user has entered the value print out the selection that the user chose with some sort of pithy message associated with the choice. things = ["water bottle", "chapstick", "phone", "headphones"] index = 0 while index < len(things): thing = things[index] print(f"{index}: {thing}") index += 1 print("What is the most interesting item?") while True: try: choice = int(input("Pick a number between 0 - 3\n")) break except ValueError: print("Please enter an integer!") try: if things[choice] == things[0]: print(f"You chose {things[0]}, you must be thirsty!") elif things[choice] == things[1]: print(f"You chose {things[1]}, your lips must be dry!") elif things[choice] == things[2]: print( f"You chose {things[2]}, get off your phone and pay attention in class!") elif things[choice] == things[3]: print(f"You chose {things[3]}, great!") except IndexError: print("You did not choose a number between 0 - 3!")
true
280dde835bdd22c44a461955634526aa9bd57faa
cute3954/Solving-Foundations-of-Programming
/problem-solving-with-python/makeBricks.py
1,302
4.3125
4
# https://codingbat.com/prob/p183562 # # We want to make a row of bricks that is goal inches long. # We have a number of small bricks (1 inch each) and big bricks (5 inches each). # Return true if it is possible to make the goal by choosing from the given bricks. # This is a little harder than it looks and can be done without any loops. See also: Introduction to MakeBricks # # makeBricks(3, 1, 8) → true # makeBricks(3, 1, 9) → false # makeBricks(3, 2, 10) → true class BricksMaker: def __init__(self): self.bricks = [ {'small': 3, 'big': 1, 'goal': 8}, {'small': 6, 'big': 0, 'goal': 11}, {'small': 1, 'big': 4, 'goal': 12}, {'small': 43, 'big': 1, 'goal': 46}, {'small': 1000000, 'big': 1000, 'goal': 1000100}, {'small': 2, 'big': 1000000, 'goal': 100003}, {'small': 20, 'big': 4, 'goal': 39} ] for i in range(len(self.bricks)): result = self.makeBricks(self.bricks[i]) print(result) def makeBricks(self, bricks): small = bricks['small'] big = bricks['big'] goal = bricks['goal'] re = goal - big * 5 if goal >= big * 5 else goal % 5 result = False if re > small else True return result BricksMaker()
true
1226a6de159e071159a9aca6f00a4dd2483265ab
daveboat/interview_prep
/coding_practice/binary_tree/populating_next_right_pointers_in_each_node.py
2,486
4.125
4
""" LC116 - Populating Next Right Pointers in Each Node You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Follow up: You may only use constant extra space. Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem. Example 1: Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#] Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. Constraints: The number of nodes in the given tree is less than 4096. -1000 <= node.val <= 1000 """ """ # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next """ class Solution(object): def connect(self, root): """ :type root: Node :rtype: Node """ # trivial case if not root: return None # since the binary tree is perfect, we can do a breadth-first search with a known number of # nodes at each level (i.e. 2^i where i is the level, starting from 0). This necessarily # O(N) time (need to visit every node) and O(N) space (need to store on average N/2 nodes in # the queue) curr_level = 0 queue = [root] level_node_counter = 0 while queue: # pop node and add children node = queue.pop(0) if node.left: queue.append(node.left) if node.right: queue.append(node.right) # increment counter and do assignment of node.next level_node_counter += 1 if level_node_counter == 2 ** curr_level: # end of level node.next = None curr_level += 1 level_node_counter = 0 else: # otherwise node.next = queue[0] return root
true
49dfa92d60ff280719607b50f9e5a6aa40f76e1e
daveboat/interview_prep
/coding_practice/general/robot_bounded_in_circle.py
2,663
4.15625
4
""" LC1041 - Robot bounded in circle On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. Example 1: Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin. Example 2: Input: "GG" Output: false Explanation: The robot moves north indefinitely. Example 3: Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... Note: 1 <= instructions.length <= 100 instructions[i] is in {'G', 'L', 'R'} """ class Solution(object): def get_next_orientation(self, current_orientation, instruction): if instruction == 'R': return 0 if current_orientation == 3 else current_orientation + 1 elif instruction == 'L': return 3 if current_orientation == 0 else current_orientation - 1 def isRobotBounded(self, instructions): """ :type instructions: str :rtype: bool """ # the robot stays bounded if it returns to its original position OR if its final direction before looping # is no longer north. In the first case, the robot will return to its original position, and so it's bounded. # in the second case, the robot will make a multi-cycle loop # so we follow the instructions to the end, and find the final position and direction current_position = [0, 0] current_orientation = 0 # 0 - North, 1 - West, 2 - South, 3 - East for i in instructions: if i == 'L' or i == 'R': current_orientation = self.get_next_orientation(current_orientation, i) elif i == 'G': if current_orientation == 0: current_position[1] += 1 elif current_orientation == 1: current_position[0] -= 1 elif current_orientation == 2: current_position[1] -= 1 elif current_orientation == 3: current_position[0] += 1 if current_position == [0, 0]: return True elif current_orientation != 0: return True else: return False
true
c38cc560308edabac42c87bec8252bc9f446e39c
momentum-cohort-2019-05/w2d2-palindrome-bhagh
/palindrome.py
577
4.25
4
import re #grab user input submission = input("Enter a word or sentence(s): ") #function to clean up text by user def cleantext (submission): submission = (re.sub("[^a-zA-Z0-9]+", '', submission).replace(" ","")) return submission print(cleantext(submission)) #create a string that's the reverse of the text by the user backwards_string = (cleantext(submission)[::-1]) #check if both strings match if str(cleantext(submission).lower()) == str(backwards_string.lower()): print(submission, "is a palindrome") else: print(submission, "is not a palindrome")
true
e74a0ce8b1b2301019f58e51ad1befacaf983a4c
sidmusale97/SE-Project
/Pricing Algorithm/linearRegression.py
1,113
4.28125
4
''' ------------------------------------------------------------------------------------ This function is used to compute the mean squared error of a given data set and also to find the gradient descent of the theta values and minimize the costfunction. ------------------------------------------------------------------------------------ X="input parameters" y="required output" theta="parameters to minimize costfunction" alpha = "Learning rate" num_iters="Number of iterations to run" ''' import numpy as np def computecost(X, y, theta): m = y.size x = np.transpose(X) hypothesis = x.dot(theta) sub = np.subtract(hypothesis, y) cost = (0.5 / m) * np.sum(sub ** 2) return cost def gradient(X, y, theta, alpha, num_iters): m = y.size x = np.transpose(X) cost_iter = np.zeros((num_iters, 1)) for i in range(1, num_iters): hypothesis = x.dot(theta) theta = theta - ((alpha / m) * (np.dot(X, np.subtract(hypothesis, y)))) cost = computecost(X, y, theta) cost_iter[i - 1] = cost return theta, cost_iter
true
93226ba29c06e18e86531e1c7326ab89082d473c
SAbarber/python-exercises
/ex12.py
611
4.34375
4
#Write a Python class named Circle. Use the radius as a constructor. Create two methods which will compute the AREA and the PERIMETER of a circle. A = π r^2 (pi * r squared) Perimeter = 2πr class Circle: def area(self): return self.pi * self.radius ** 2 def __init__(self, pi, radius): self.pi = pi self.radius = radius x = Circle(3.14,5) print('The area is' ,x.area()) class Perimeter(): def perm(self): return 2 * self.pi * self.radius def __init__(self, pi, radius): self.pi = pi self.radius = radius i = Perimeter(3.14,5) print('Ther perimeter is', i.perm())
true
1cca34bd53ba9d73f844dccf011526deb399cd18
darkbodhi/Some-python-homeworks
/divN.py
713
4.25
4
minimum = int(input("Please insert the minimal number: ")) maximum = int(input("Please insert the maximal number: ")) divisor = int(input("Please insert the number on which the first one will be divided: ")) x = minimum % divisor if divisor <= 0: raise Exception("An error has occurred. The divisor is not a natural positive number.") elif not maximum > minimum: raise Exception("Error: the relation between numbers is not minimum-maximum.") elif x == 0: while minimum <= maximum: print(minimum) minimum += divisor elif x > 0: minimum += divisor - x while minimum <= maximum: print(minimum) minimum += divisor else: raise Exception("An error has occurred.")
true
aa0c6a66944e2cef568c401bd7f55e55bca1cec6
anilkumar-satta-au7/attainu-anilkumar-satta-au7
/create_a_dictionary_from_a_string.py
430
4.21875
4
#3) Write a Python program to create a dictionary from a string. # Note: Track the count of the letters from the string. # Sample string : 'w3resource' # Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1} test_str = "w3resource" all_freq = {} for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 print (str(all_freq))
true
01b0cf471c7e1a3d5ea42bd4e8ce2b44eaaba293
pyaephyokyaw15/credit-card-validation
/credit-card.py
1,811
4.28125
4
''' Credit-card Validation - This script is used to determine whether a certain credit-card is valid or not. - It is based on Luhn’s algorithm. - It also determines the type of Card(eg.MASTER, VISA, AMEX) ''' def main(): # getting number from user until it is numeric value while True: card = input("Number: ") if card.isnumeric(): break if (is_valid(card)): # if card is valid, determine what card it is. if len(card) == 15 and (card[0:2] == '34' or card[0:2] == '37'): print('AMEX') elif len(card) == 16 and card[0:2] in ['51','52','53','54','55']: print('MASTERCARD') elif 13 <= len(card) <= 16 and card[0] == '4': print('VISA') else: print("INVALID") else: print("INVALID") def is_valid(card): odd_pos_digit_sum = 0 even_pos_digit_sum = 0 # In algorithm, digit in card starting LSB # to get digits from the last digit by 2 for position in range(len(card)-1, -1, -2): # sum each digit directly odd_pos_digit_sum += int(card[position]) # to get digits even position started from last digit for position in range(len(card)-2, -1, -2 ): # peprocessing before sum due to algorithm digit = int(card[position]) digit *= 2 # if the result digit contains two digit separate them and sum if digit > 9: digit = (digit // 10) + (digit % 10) # sum each digit even_pos_digit_sum += digit check_sum = odd_pos_digit_sum + even_pos_digit_sum # if check_sum is end in 0 , valid if (check_sum % 10): return False return True if __name__ =="__main__": main()
true
a36d51210c4062391cca3a8218f990388fc20cca
jenihuang/hb_challenges
/EASY/lazy-lemmings/lemmings.py
942
4.21875
4
"""Lazy lemmings. Find the farthest any single lemming needs to travel for food. >>> furthest(3, [0, 1, 2]) 0 >>> furthest(3, [2]) 2 >>> furthest(3, [0]) 2 >>> furthest(6, [2, 4]) 2 >>> furthest(7, [0, 6]) 3 >>> furthest(7, [0, 6]) 3 >>> furthest(3, [0, 1, 2]) 0 >>> furthest(3, [2]) 2 >>> furthest(3, [0]) 2 >>> furthest(6, [2, 4]) 2 """ def furthest(num_holes, cafes): """Find longest distance between a hole and a cafe.""" # find max distance between all cafes and integer divide by 2 distances = set() distances.add(cafes[0]) distances.add(num_holes - cafes[-1] - 1) for i in range(1, len(cafes)): distances.add((cafes[i] - cafes[i - 1]) // 2) return max(distances) if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED; GREAT JOB!\n")
true
de62ef9fb09f2d10b0813bf727442cb6c282b546
jenihuang/hb_challenges
/EASY/replace-vowels/replacevowels.py
946
4.34375
4
"""Given list of chars, return a new copy, but with vowels replaced by '*'. For example:: >>> replace_vowels(['h', 'i']) ['h', '*'] >>> replace_vowels([]) [] >>> replace_vowels(['o', 'o', 'o']) ['*', '*', '*'] >>> replace_vowels(['z', 'z', 'z']) ['z', 'z', 'z'] Make sure to handle uppercase:: >>> replace_vowels(["A", "b"]) ['*', 'b'] Do not consider `y` a vowel:: >>> replace_vowels(["y", "a", "y"]) ['y', '*', 'y'] """ def replace_vowels(chars): """Given list of chars, return a new copy, but with vowels replaced by '*'.""" replaced = [] vowels = {'a', 'e', 'i', 'o', 'u'} for char in chars: if char.lower() in vowels: replaced.append('*') else: replaced.append(char) return replaced if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. YAY!\n")
true
6ce8b6c28e28ea4207d7bfbc95fb9ccc0d558602
jenihuang/hb_challenges
/MEDIUM/balanced-brackets/balancedbrackets.py
1,935
4.15625
4
"""Does a given string have balanced pairs of brackets? Given a string, return True or False depending on whether the string contains balanced (), {}, [], and/or <>. Many of the same test cases from Balance Parens apply to the expanded problem, with the caveat that they must check all types of brackets. These are fine:: >>> has_balanced_brackets("<ok>") True >>> has_balanced_brackets("<{ok}>") True >>> has_balanced_brackets("<[{(yay)}]>") True These are invalid, since they have too many open brackets:: >>> has_balanced_brackets("(Oops!){") False >>> has_balanced_brackets("{[[This has too many open square brackets.]}") False These are invalid, as they close brackets that weren't open:: >>> has_balanced_brackets(">") False >>> has_balanced_brackets("(This has {too many} ) closers. )") False Here's a case where the number of brackets opened matches the number closed, but in the wrong order:: >>> has_balanced_brackets("<{Not Ok>}") False If you receive a string with no brackets, consider it balanced:: >>> has_balanced_brackets("No brackets here!") True """ def has_balanced_brackets(phrase): """Does a given string have balanced pairs of brackets? Given a string as input, return True or False depending on whether the string contains balanced (), {}, [], and/or <>. """ stack = [] opens = {'(', '{', '[', '<'} matches = {')': '(', '}': '{', ']': '[', '>': '<'} for char in phrase: if char in opens: stack.append(char) elif char in matches: if not stack: return False else: out = stack.pop() opening = matches[char] if out != opening: return False if not stack: return True else: return False if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. YOU CAUGHT ALL THE STRAY BRACKETS!\n")
true
29c4f36d8bfa47db7391311153a590deeb43216b
jenihuang/hb_challenges
/MEDIUM/maxpath/maxpath.py
2,844
4.125
4
"""Given a triangle of values, find highest-scoring path. For example:: 2 5 4 3 4 7 1 6 9 6 = [2,4,7,9] = 22 This works: >>> triangle = make_triangle([[2], [5, 4], [3, 4, 7], [1, 6, 9, 6]]) >>> triangle [2, 5, 4, 3, 4, 7, 1, 6, 9, 6] >>> maxpath(triangle) 22 """ class Node(object): """Basic node class that keeps track fo parents and children. This allows for multiple parents---so this isn't for trees, where nodes can only have one children. It is for "directed graphs". """ def __init__(self, value): self.value = value self.children = [] self.parents = [] def __repr__(self): return str(self.value) def make_triangle(levels): """Make a triangle given a list of levels. For example, imagining this triangle:: 1 2 3 4 5 6 7 8 9 10 We could create it like this:: >>> triangle = make_triangle([[1], [2,3], [4,5,6], [7,8,9,10]]) >>> triangle [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Let's check to make sure this works:: >>> n1, n2, n3, n4, n5, n6, n7, n8, n9, n10 = triangle >>> n1.parents [] >>> n1.children [2, 3] >>> n2.parents [1] >>> n2.children [4, 5] >>> n3.parents [1] >>> n3.children [5, 6] >>> n4.parents [2] >>> n4.children [7, 8] >>> n5.parents [2, 3] >>> n5.children [8, 9] >>> n6.parents [3] >>> n6.children [9, 10] """ nodes = [] for y, row in enumerate(levels): for x, value in enumerate(row): node = row[x] = Node(value) nodes.append(node) if y == 0: continue if x == 0: parents = [levels[y - 1][0]] elif x == y: # last in row parents = [levels[y - 1][x - 1]] else: parents = [levels[y - 1][x - 1], levels[y - 1][x]] node.parents = parents for p in parents: p.children.append(node) return nodes def maxpath(nodes): """Given list of nodes in triangle, return high-scoring path.""" return maxpath_helper(nodes[0]) def maxpath_helper(node): if not node.children: return node.value else: highest = 0 for child in node.children: c_value = maxpath_helper(child) if c_value > highest: highest = c_value highest += node.value return highest if __name__ == '__main__': import doctest print() if doctest.testmod().failed == 0: print("\t*** ALL TESTS PASSED; GOOD WORK!") print()
true
9015d36d969ed1e22d46113064e94a3c26dc0043
jenihuang/hb_challenges
/EASY/rev-string/revstring.py
519
4.15625
4
"""Reverse a string. For example:: >>> rev_string("") '' >>> rev_string("a") 'a' >>> rev_string("porcupine") 'enipucrop' """ def rev_string(astring): """Return reverse of string. You may NOT use the reversed() function! """ rev_str = '' for i in range(len(astring)-1, -1, -1): rev_str += astring[i] return rev_str if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. !KROW DOOG\n")
true
6fdb741e9ccd497a7f6a7ae00604072bbf178262
jenihuang/hb_challenges
/EASY/missing-number/missing.py
831
4.15625
4
"""Given a list of numbers 1...max_num, find which one is missing in a list.""" def missing_number(nums, max_num): """Given a list of numbers 1...max_num, find which one is missing. *nums*: list of numbers 1..[max_num]; exactly one digit will be missing. *max_num*: Largest potential number in list >>> missing_number([7, 3, 2, 4, 5, 6, 1, 9, 10], 10) 8 """ # all_nums = set() # for i in range(1, max_num + 1): # all_nums.add(i) # for num in nums: # if num not in all_nums: # return num sum_n = (max_num * (max_num + 1)) / 2 total = 0 for item in nums: total += item return int(sum_n - total) if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASS. NICELY DONE!\n")
true
de346421fd9bf36a0113d702ccf6de03620b8198
Johan-p/learnpythonShizzle
/exercise_36_birthdayplots.py
1,639
4.28125
4
""" In this exercise, use the bokeh Python library to plot a histogram of which months the scientists have birthdays in! """ print(__doc__) from bokeh.plotting import figure, show, output_file from collections import Counter import json def read_jsonfile(): #global birthday_dictionary global x global y with open("birthday.json", "r") as read_file: birthday_dictionary = json.load(read_file) #counting number of times months occur in each entry numberic_list = [] alphabettic_list = [] for values in birthday_dictionary.values(): nummeric_month = values[3] + values[4] numberic_list.append(str(nummeric_month)) for num in numberic_list: alphabettic_list.append(month_dict[num]) c = dict(Counter(alphabettic_list)) x = list(c.keys()) y = list(c.values()) # create a figure # To make sure bokeh draws the axis correctly, # you need to specify a special call to figure() to pass an x_range p = figure(x_range=x_categories) # create a histogram p.vbar(x=x, top=y, width=0.5) # render (show) the plot, this opens the browser show(p) # we specify an HTML file where the output will go output_file("plot.html") x_categories = ["January","Febuary","March","April", "May","June","July","August","September","October","November","December"] x = [] y = [] month_dict = {"01":"January", "02":"Febuary", "03":"March", "04":"April", "05":"May", "06":"June", "07":"July", "08":"August", "09":"September", "10":"October", "11":"November", "12":"December"} if __name__=='__main__': read_jsonfile()
true
713ed8035bf707c380e127bab4f0c6b36f6641ce
Johan-p/learnpythonShizzle
/Madlibs.py
1,517
4.46875
4
""" In this project, we'll use Python to write a Mad Libs word game! Mad Libs have short stories with blank spaces that a player can fill in. The result is usually funny (or strange). Mad Libs require: A short story with blank spaces (asking for different types of words). Words from the player to fill in those blanks. """ # The template for the story print "starting Mad Libs" Name = raw_input("Enter a name: ") Adjective_1 = raw_input("Adjective One: ") Adjective_2 = raw_input("Adjective Two: ") Adjective_3 = raw_input("Adjective Three: ") Verb = raw_input("verb: ") Nouns_1 = raw_input("nouns One: ") Nouns_2 = raw_input("nouns Two: ") Animal = raw_input("input an animal: ") Food = raw_input("input a food: ") Fruit = raw_input("input a fruit: ") Superhero = raw_input("input a superhero: ") Country = raw_input("input a country: ") Dessert = raw_input("input a dessert: ") Year = raw_input("input a Year: ") STORY = "This morning %s woke up feeling %s. 'It is going to be a %s day!' Outside, a bunch of %ss were protesting to keep %s in stores. They began to %s to the rhythm of the %s, which made all the %ss very %s. Concerned, %s texted %s, who flew %s to %s and dropped %s in a puddle of frozen %s. %s woke up in the year %s, in a world where %ss ruled the world." % (Name, Adjective_1, Adjective_2, Animal, Food, Verb, Nouns_1, Fruit, Adjective_3, Name, Superhero, Name, Country, Name, Dessert, Name, Year, Nouns_2) print STORY
true
8a8d89f72edd35ccb2928af5b147ad882899c6fe
Johan-p/learnpythonShizzle
/exercise_33_birthdaydictionaries.py
884
4.59375
5
""" or this exercise, we will keep track of when our friends birthdays are, and be able to find that information based on their name. Create a dictionary (in your file) of names and birthdays. When you run your program it should ask the user to enter a name, and return the birthday of that person back to them. """ print(__doc__) #imports def var(): pass birthday_dictionary = {"Albert Einstein":"14/03/1879", "Benjamin Franklin":"17/01/1706", "Winston Churchill":"24/01/1965",} if __name__=='__main__': print "Welcome to the birthday dictionary. We know the birthdays of:" for key in birthday_dictionary.keys(): print key user_input = str(raw_input("Who's birthday do you want to look up? ")) if user_input in birthday_dictionary: print "%s birthday is %s" % (user_input, birthday_dictionary[user_input]) else: exit()
true
c816a4224eeff0e5610176feb5df8eacfe3efcfb
HarrisonWelch/MyHackerRankSolutions
/python/Nested Lists.py
496
4.25
4
# Nested Lists.py # Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. marksheet = [] for _ in range(0,int(input())): marksheet.append([raw_input(), float(raw_input())]) second_highest = sorted(list(set([marks for name, marks in marksheet])))[1] print "second_highest = ", second_highest print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))
true
fc9d7761b45597c8d3efb6fd81f76f0c96d547b7
Lenux56/FromZeroToHero
/text_vowelfound.py
519
4.4375
4
''' Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found. ''' import re def multi_re_find(): ''' search and count vowels ''' phrase = input('Please, enter a phrase to find vowels and count it: ') while not phrase: print('Phrase is empty, please try again') phrase = input('Enter a phrase to find vowels and count it: ') print([{pattern:len(re.findall(pattern, phrase))} for pattern in 'aeyuio'])
true
20e59d6494ba4c87140ccf88af9e846164ce0596
vikas-ukani/Hacktoberfest_2021
/Rock_Paper_Scissors.py
1,368
4.28125
4
import random print("Welcome to rock paper scissors game .....") print("You have three chances greater the wins in individual game will increase your chance to win") print("Press 0-->paper , 1-->rock , 2-->scissors") comp = 0 player = 0 for i in range(3): player_choice = input("Your turn") comp_choice=random.randint(0,2) print(f"you chose\t{player_choice} and computer chose\t{comp_choice}") if int( player_choice) >2: print("Enter number between 0,1,2") break if comp_choice == player_choice: print("Its a tie.") comp = comp + 1 player = player+ 1 if comp_choice == 0: if player_choice == 1: print("Computer wins.") comp = comp + 1 else: print("You win.") player = player+ 1 elif comp_choice == 1: if player_choice == 2: print("Computer wins.") comp = comp + 1 else: print("You win.") player = player+ 1 elif comp_choice == 2: if player_choice == 0: print("Computer wins.") comp = comp + 1 else: print("You win.") player = player+ 1 if int(player) > int(comp): print("Hurray!!You win!!!") else: print("Computer wins!! Better luck next time !!")
true
3f7c545c8765583c918074b6c73f4114522a1d2b
emmanuelnaveen/decision-science
/date_format.py
292
4.3125
4
from datetime import date # Read the current date current_date = date.today() # Print the formatted date print("Today is :%d-%d-%d" % (current_date.day,current_date.month,current_date.year)) # Set the custom date custom_date = date(2021, 05, 20) print("The date is:",custom_date)
true
49c046a92870d3f128849c8ad0452ca7c71c75f1
SruthiM-10/5th-grade
/Programs/reverseName.py
275
4.21875
4
s=input("What is your first name?") f=input("What is your middle name if you have one? If you don't have a middle name, just type no") r=input("What is your last name?") if f=="no": print("Your name in reverse is",r,s) else: print("Your name in reverse is",r,f,s,)
true
513a9d0167adda155e9f267aab31db2b75f4e441
dulalsaurab/Graph-algorithm
/plot.py
418
4.1875
4
''' This file will plot 2-d and 3-d points''' import numpy as np import matplotlib.pyplot as plt # drawing lines between given points iteratively def draw_line(array): data = array # array should be of format [(),(),(),()] # 2D ploting using matplotlib def plot_2D(array, size): # array should be of format [(),(),(),()] data = array x, y = zip(*data) plt.scatter(x, y, size) plt.show()
true
950fb0e048a560043577605d9642d69808f974da
Rohitha92/Python
/Sorting/BubbleSort.py
774
4.1875
4
#Bubble sort implementation #multiple passes throught the list. ##Ascending order def bubble_sort(arr): swapped = True while(swapped): swapped = False for i in range(len(arr)-1): if arr[i] > arr[i+1]: temp = arr[i] arr[i] = arr[i+1] arr[i+1]= temp swapped = True return arr #Optimized solution: #faster since we do not move comparing throughout the array every iteration. def bubble_sort2(arr): n= len(arr) for i in range(n): swapped = False for j in range(0, n-i-1): if arr[j]> arr[j+1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1]= temp swapped = True if swapped == False: break return arr x = [1,5,10,2,5,23,11] print(bubble_sort2(x))
true
7216c73c1532bb08e436447f01903f98e7be6660
Rohitha92/Python
/StacksQueuesDeques/Queue.py
578
4.21875
4
#Implement Queue #First in First out #insert items at the First (zero index) #delete from first (zero index) class Queue(object): def __init__(self): self.items=[] def enqueue(self,val): #add to the rear self.items.insert(0,val) def size(self): return len(self.items) def isempty(self): return self.items == [] def dequeue(self): #removes from the front if self.isempty(): return "queue empty" return self.items.pop() a = Queue() a.enqueue(3) a.enqueue(4) print(a.dequeue()) print(a.dequeue()) print(a.dequeue())
true
7aeba56b0611f7db71a27daf3cb8f007273cdbc2
Shubhamditya36/python-pattern-programs
/a13.py
391
4.1875
4
# PROGRAM TO PRINT PATTERN GIVEN BELOW. # 1 # 2 1 2 # 3 2 1 2 3 # 4 3 2 1 2 3 4 # 5 4 3 2 1 2 3 4 5 num=int(input ("enter a number of rows:")) for row in range(1,num+1): for col in range(0,num-row+1): print(end=" ") for col in range(row,0,-1): print(col,end=" ") for col in range(2,row+1): print(col,end=" ") print()
true
6539173b858b23d1e0ce6daa4431edc7c0c8761b
svigstol/100-days-of-python
/days-in-a-month.py
1,522
4.21875
4
# 100 Days of Python # Day 10.2 - Days In A Month # Enter year and month as inputs. Then, display number of days in that month # for that year. # Sarah Vigstol # 5/31/21 def isLeap(year): """Determine whether or not a given year is a leap year.""" if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False def daysInMonth(year, month): """Check if the given year is a leap year, then returns the number of days in the given month.""" monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if isLeap(year) == True and month == 2: return 29 return monthLength[month - 1] while True: year = int(input("Enter a year: ")) month = int(input("Enter a month (1-12): ")) monthNames = { 1:"January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "Novemeber", 12: "December" } if month <= 12 and month >= 1: for key in monthNames: if key == month: monthName = monthNames.get(key) days = daysInMonth(year, month) print(f"\nThere were {days} days in {monthName} of {year}.") break elif month > 12 or month < 1: print("Invalid month. Try again.\n")
true
02350014103279d5c3d072b18cae6a3e0798de75
teddyk251/alx-higher_level_programming-1
/0x07-python-test_driven_development/2-matrix_divided.py
1,289
4.28125
4
#!/usr/bin/python3 """ divides all elements of a matrix """ def matrix_divided(matrix, div): """ divides all elements of a matrix Args: matrix: matrix to be divided div: number used to divide Return: matrix with divided elements """ if not all(isinstance(matrix, list)): raise TypeError( 'matrix must be a matrix (list of lists)of integers/floats' ) """ if all lists are of the same length """ it = iter(matrix) length = len(next(it)) if not all(len(l) == length for l in it): raise TypeError('Each row of the matrix must have the same size') """ checking for list values """ for lst in matrix: for num in lst: if type(num) not in [int, float] or num is None: raise TypeError( 'matrix must be a matrix (list of lists)' ' of integers/floats' ) """ checking for div """ if type(div) not in [int, float] or div is None: raise TypeError('div must be a number') if div == 0: raise ZeroDivisionError('division by zero') """ else, divide the matrix """ return([list(map(lambda x: round(x / div, 2), num))for num in matrix])
true
758b8709a3d0133fa00beb506b662cb00bd51129
rkgitvinay/python-basic-tutorials
/3-control_flow.py
714
4.21875
4
""" Control Flow Statements """ """ uses an expression to evaluate whether a statement is True or False. If it is True, it executes what is inside the “if” statement. """ """ If Statement """ if True: print("Hello This is if statement!") """ Output: Hello This is if statement! """ if 5 > 2: print("5 is greater than 2.") """ Output: 5 is greater than 2. """ """ If Else Statement """ if 5 < 2: print("5 is lss than 2.") else: print("5 is greater than 2.") """ Outpur: 5 is greater than 2.""" """ If Else If Statement """ if 1 > 2: print("1 is greater than 2") elif 2 > 1: print("1 is not greater than 2") else: print("1 is equal to 2") """ Output: 1 is not greater than 2 """
true
06e0b06b985e0ac48cfe3ecd6c1ca1de69334424
ybettan/ElectricalLabs
/electrical_lab_3/aws_experiment/part2/preliminary/q4.py
279
4.3125
4
grades = {"python": 99, "java": 90, "c": 90} grades_list = [x for _, x in grades.items()] max_grade = max(grades_list) min_grade = min(grades_list) print "My lowest grade this semester was {}".format(min_grade) print "My highest grade this semester was {}".format(max_grade)
true
2d11b7b1d939f6be364dc2394728fe2a21b99e95
Nduwal3/python-Basics
/function-Assignments/soln16.py
377
4.125
4
""" Write a Python program to square and cube every number in a given list of integers using Lambda. """ def calc_square_and_cube(input_list): square_list = map(lambda num: num * num, input_list) cube_list = map(lambda num: num ** 3, input_list) print(list(square_list)) print(list(cube_list)) sample_list = [1, 3, 5, 7, 9] calc_square_and_cube(sample_list)
true
f4fd513b8f8706e0339d7da3284b5f22364b5d04
Nduwal3/python-Basics
/soln43.py
374
4.25
4
""" Write a Python program to remove an item from a tuple. """ # since python tuples are immutable we cannot append or remove item from a tuple. # but we can achive it by converting the tuple into a list and again converting the list back to a tuple my_tuple = ('ram', 37, "ram@r.com") my_list = list(my_tuple) my_list.remove(37) my_tuple = tuple(my_list) print(my_tuple)
true
10047fa0561ecf373381ce8abed48587402952b3
Nduwal3/python-Basics
/function-Assignments/soln7.py
825
4.21875
4
""" Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. Sample String : 'The quick Brow Fox' Expected Output : No. of Upper case characters : 3 No. of Lower case Characters : 12 """ def count_string_lower_and_upper_case(input_string): count_upper_case = 0 count_lower_case = 0 for char in input_string: if char.isupper(): count_upper_case += 1 elif char.islower(): count_lower_case += 1 else: continue return count_upper_case , count_lower_case upper_case_count, lower_case_count = count_string_lower_and_upper_case('The quick Brow Fox') print("No. of Upper case characters : {}".format(upper_case_count)) print("No. of Lower case characters : {}".format(lower_case_count))
true
4af30bc0c5fa913415ad507c23232f86a20fad8a
Nduwal3/python-Basics
/function-Assignments/soln9.py
591
4.15625
4
""" Write a Python function that takes a number as a parameter and check the number is prime or not. Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself. """ def check_prime(num): is_prime = False if num > 1: for i in range(2, num): if num % i == 0: is_prime = False break else: is_prime = True return is_prime num = 16 if(check_prime(num)): print("the number is prime") else: print("the number is not prime")
true
515a4847f1592a5d8329f075cf40506c63350f82
Nduwal3/python-Basics
/soln25.py
548
4.1875
4
""" Write a Python program to check whether all dictionaries in a list are empty or not. Sample list : [{},{},{}] Return value : True Sample list : [{1,2},{},{}] Return value : False """ def check_empty_dictionaries(sample_list): is_empty = False for item in sample_list: if item: is_empty = False break else: is_empty = True print(is_empty) sample_list1 = [{},{},{}] sample_list2 = [{},{1,2},{}] check_empty_dictionaries(sample_list1) check_empty_dictionaries(sample_list2)
true
fc5d4c5006f3c9217d58848447a4fd76382a4a72
GravityJack/keyed-merge
/keyed_merge/merge.py
880
4.1875
4
import functools import heapq def merge(*iterables, key=None): """ Merge multiple sorted iterables into a single sorted iterable. Requires each sequence in iterables be already sorted with key, or by value if key not present. :param iterables: Iterable objects to merge :param key: optional, callable Key function, identical to that used by builtin sorted(). If not present, items will be compared by value. :return: iterator to the sorted sequence """ if key is None: for x in heapq.merge(*iterables): yield x else: bound_key = functools.partial(_add_key, key) with_key = map(bound_key, iterables) merged = heapq.merge(*with_key) for key, value in merged: yield value def _add_key(key, iterable): for x in iterable: yield key(x), x
true
7c918ccd80ec7fd3c45d8233a12a62bd423c7937
msflyee/Learn_python
/code/Chapter4_operations on a list.py
1,062
4.28125
4
# Chapter4-operations on a list magicians = ['Alice','David','Liuqian']; for magician in magicians: #define 'magician' print(magician + '\t'); for value in range(1,5): #define value print(value); numbers = list(range(1,6)); print(numbers); even_numbers = list(range(2,11,2)); #打印偶数,函数range()的第三个参数为 步数 print(even_numbers); squares = []; for value in range(1,6): squares.append(value ** 2); print(squares); list = [4,3,2,1]; for value in list: squares.pop(value); print(squares); squares = [value ** 2 for value in range(1,11)]; print(squares); list = []; for value in range(1,1000001): list.append(value); print(min(list)); print(max(list)); print(sum(list)); players = ['Charles','Martina','Florence','Eli']; print(players[0:3]); print(players[:3]); print(players[2:]); print(players[-3:]); for player in players[-3:]: print(player); _players = players[:]; print(_players); print(players); players.append('Karry'); print(_players); print(players); #copyright by Karry Yee in WuHan,China.
true
30808f5fb665d31421e878ace60502afebf33836
ShaneRandell/Midterm_001
/midterm Part 4.py
867
4.1875
4
## Midterm Exam Part 4 import csv # imports the csv library file = open("book.csv", "a") # Opening a file called book.csv for appending title = input("enter a title: ") # asking the user to enter a title author = input("Enter author: ") # asking the user to enter a author year = input("Enter the year it was released: ") # askign the user to enter year book was published newrecord = title + "," + author + "," + year + "\n" # creating a string to combine all the entered information file.write(str(newrecord)) # writing to the file all the information the user inputted file.close() # closing the file file = open("Book.csv", "r") # opening the file for reading for row in file: # for loop with the condition to print all the rows in the file print(row) # printing the contents of rows in the file file.close() # closing the file
true
065aff05e0876ed0cedeea555109f6147a9d3219
Venkatesh147/60-Python-projects
/60 Python projects/BMI Calculator.py
572
4.28125
4
Height=float(input("Enter your height in centimeters: ")) Weight=float(input("Enter your weight in kg: ")) Height=Height/100 BMI=Weight/(Height*Height) print("your Body Mass Index is: ", BMI) if(BMI>0): if (BMI<=16): print("you are severly underweight") elif (BMI<=18.5): print("you are underweight") elif (BMI<=25): print("you are healthy") elif (BMI<=30): print("you are overweight") else: print("you are severely overweight") else:("enter valid detalis")
true
2b654bfaf67cefdbdff9a1b4b61d4d80af3da5ff
CodecoolBP20172/pbwp-3rd-si-code-comprehension-frnczdvd
/comprehension.py
1,948
4.34375
4
# This program picks a random number between 1-20 and the user has to guess it under 6 times import random # Import Python's built-in random function guessesTaken = 0 # Assign a variable to 0 print('Hello! What is your name?') # Display a given output message myName = input() # Ask for user input number = random.randint(1, 20) # Assign a variable to a random number between 1 and 20 print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') # Display a given output message, including a variable that contains the user's name while guessesTaken < 6: # A loop that runs until user has given input 6 times or less print('Take a guess.') # Display a given output message guess = input() # Ask for user input guess = int(guess) # Convert user input to integer guessesTaken += 1 # A variable that count user inputs if guess < number: # If users input is lower than the variable number print('Your guess is too low.') # Display a given output message if guess > number: # If users input is higher than the variable number print('Your guess is too high.') # Display a given output message if guess == number: # If users input equals the variable number break # Stop the loop if guess == number: # If users input equals the variable number guessesTaken = str(guessesTaken) # Convert the variable that counts the number of user inputs from integer to string print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') # Display a given output message, including a variable that contains the user's name and the number of guesses. if guess != number: # If user's input doesn't equals the variable number number = str(number) # Convert the variable that had to be guessed from integer to string print('Nope. The number I was thinking of was ' + number) # Display a given output message containing the number that had to be guessed
true
f97c7326e6be4786e1fda3a5c4a55c61aa6c6f3c
KLKln/Module11
/employee1.py
2,382
4.53125
5
""" Program: employee.py Author: Kelly Klein Last date modified: 7/4/2020 This program will create a class called employee allowing the user to access information about an employee """ import datetime class Employee: def __init__(self, lname, fname, address, phone, start_date, salary): """ use reST style. :param last_name: employee's last name :param first_name: employee's first name :param address: employees address :param phone_number: employee's phone number :param start_date: date employee started :param salary: double to indicate salary :return: """ self.last_name = lname #last_name: string self.first_name = fname #first_name: string self.address = address #address: string self.phone = phone #phone_number: string self.start_date = start_date #start_date: datetime self.salary = salary #salary: double def display(self): """ use reST style. :param last_name: employee's last name :param first_name: employee's first name :param address: employees address :param phone_number: employee's phone number :param start_date: date employee started working :param salary: employee's yearly salary or hourly wage :return: """ print(self.first_name + ' ' + self.last_name) print(self.address) print(self.phone) if self.salaried is False: print('Hourly Employee:', self.salary) else: print('Salaried Employee:', self.salary) def __str__(self): str(self.first_name + self.last_name + self.address + self.phone + self.start_date, self.salary) def __repr__(self): repr(self.first_name + self.last_name + self.address + self.phone + self.start_date + self.salary) if __name__ == '__main__': s_date = datetime.datetime(2019, 5, 17) employee1 = Employee('Klein', 'Kelly', '42 Fake st\nCoralville, IA', '319-377-2760', True, s_date, '$65000.00') print(employee1.display()) s_date = datetime.datetime(2020, 1, 20) employee2 = Employee('Lauper', 'Cyndi', '45 Elm St\nIowa City, IA', '319-345-8998', False, s_date,'$35.00 an hour') print(employee2.display())
true
6ba6176c13121443a781646914751b1430766e51
RaHuL342319/Integration-of-sqlite-with-python3
/query.py
813
4.375
4
import sqlite3 # to connect to an existing database. # If the database does not exist, # then it will be created and finally a database object will be returned. conn = sqlite3.connect('test.db') print("Opened database successfully") # SELECTING WHOLE TABLE cursor = conn.execute( "SELECT * from Movies") for row in cursor: print("Name:", row[0]) print("Actor:", row[1]) print("Actress:", row[2]) print("Director:", row[3]) print("Year_Of_Release:", row[4]) print() # querying based on actor name cursor = conn.execute( "SELECT * FROM Movies WHERE Actor='Shiddarth Malhotra'") for row in cursor: print("Name:", row[0]) print("Actor:", row[1]) print("Actress:", row[2]) print("Director:", row[3]) print("Year_Of_Release:", row[4]) print()
true
ae3dfe81639e3c295061a8b173dde8303632fd41
holbertra/Python-fundamentals
/dictionary.py
1,201
4.3125
4
# Dictionaries # dict my_dictionary = { "key" : "value", "key2" : 78 } product = { "id" : 2345872425, "description": "A yellow submarone", "price" : 9.99, "weight" : 9001, "depart" : "grocery", "aisle" : 3, "shelf" : "B" } #print(product["price"]) location = (product["aisle"], product["shelf"]) #print(location) #print(product.get("quanity")) # use .get when unknown or unsure it exists product["aisle"] = 4 product["department"] = "guy's grocery games" # for key in product: # print(product[key]) # A list of the values # print(product.values()) # print(product.keys()) # product["whatever"] = "the value" product.update({"whatever": "the value"}) # Challenge you = {} data = [ ("name", "Rich") , ("age", 55), ("class", "Python") ] for x in data: you.update({ x[0]: x[1] }) # .update() to add to dictionary, note the syntax print(you) # Question: Does update.insert() also work? Probably not a dict is UNORDERED # Question: How do you retrieve some value given a key? for k, v, in data: you[k] = v you.update(data) # 1 line solution print(you) print(f'Your age is { you["age"]}')
true
27c43829d72a2e43b5ca4f1d6d54031bfdd10138
axayjha/algorithms
/diagonal_traverse.py
886
4.21875
4
""" https://leetcode.com/problems/diagonal-traverse/ Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] Explanation: Note: The total number of elements of the given matrix will not exceed 10,000. """ class Solution: def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: from collections import defaultdict ans = [] d = defaultdict(list) for i in range(len(matrix)): for j in range(len(matrix[0])): d[i+j].append((i, j, matrix[i][j])) flip = True for i in sorted(d.keys()): for j in sorted(d[i], reverse=flip): ans.append(j[2]) flip = not flip return ans
true
edff4979701065d3a63aa5b1c7312a8389989d0b
shaduk/MOOCs
/UdacityCS101/app/days.py
1,144
4.34375
4
def nextDay(year, month, day): """Simple version: assume every month has 30 days""" if day < 30: return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1 def daysBetweenDates(year1, month1, day1, year2, month2, day2): """Returns the number of days between year1/month1/day1 and year2/month2/day2. Assumes inputs are valid dates in Gregorian calendar, and the first date is not after the second.""" c=0 while(year1,month1,day1 != year2,month2,day2): print year1,month1,day1 year1,month1,day1=nextDay(year1,month1,day1) c = c+1 # YOUR CODE HERE! return c def test(): test_cases = [((2012,9,30,2012,10,30),30), ((2012,1,1,2013,1,1),360), ((2012,9,1,2012,9,4),3)] for (args, answer) in test_cases: result = daysBetweenDates(*args) if result != answer: print "Test with data:", args, "failed" else: print "Test case passed!" test()
true
2aa27e73539e9ef7766fcf5ee480679d7b4fe2e2
shaduk/MOOCs
/edx-CS101/myLog.py
1,063
4.375
4
'''Write a simple procedure, myLog(x, b), that computes the logarithm of a number x relative to a base b. For example, if x = 16 and b = 2, then the result is 4 - because 24=16. If x = 15 and b = 3, then the result is 2 - because 32 is the largest power of 3 less than 15. In other words, myLog should return the largest power of b such that b to that power is still less than or equal to x. x and b are both positive integers; b is an integer greater than or equal to 2. Your function should return an integer answer. Do not use Python's log functions; instead, please use an iterative or recursive solution to this problem that uses simple arithmatic operators and conditional testing. Note: You will only get ten checks. Use these judiciously. ''' def myLog(x, b): ''' x: a positive integer b: a positive integer; b >= 2 returns: log_b(x), or, the logarithm of x relative to a base b. ''' # Your Code Here ans = 0 while(ans<x): if b**(ans+1)>x and b**(ans)<=x: return ans ans = ans + 1
true
41411ad71ab27f75e0771dbadac75de58b9bb3dc
sol83/python-simple_programs_7
/Lists/get_first.py
467
4.34375
4
""" Get first element Fill out the function get_first_element(lst) which takes in a list lst as a parameter and prints the first element in the list. The list is guaranteed to be non-empty. You can change the items in the SAMPLE_LIST list to test your code! """ SAMPLE_LIST = [1, 2, 3, 'a', 'b', 'c'] def get_first_element(lst): # write your code below! print(lst[0]) def main(): get_first_element(SAMPLE_LIST) if __name__ == "__main__": main()
true
5298e43d2497174ebf8477e9adede2f9c008fc67
TSG405/SOLO_LEARN
/PYTHON-3 (CORE)/Fibonacci.py
659
4.21875
4
''' @Coded by TSG, 2021 Problem: The Fibonacci sequence is one of the most famous formulas in mathematics. Each number in the sequence is the sum of the two numbers that precede it. For example, here is the Fibonacci sequence for 10 numbers, starting from 0: 0,1,1,2,3,5,8,13,21,34. Write a program to take N (variable num in code template) positive numbers as input, and recursively calculate and output the first N numbers of the Fibonacci sequence (starting from 0). Sample Input 6 Sample Output 0 1 1 2 3 5 ''' #your code goes here def fibonacci(n): a,b=0,1 for i in range(n): print(a) a,b=b,(a+b) fibonacci(int(input()))
true
6dd541d14a70d5d0654da10db9074c0999507725
kumarritik87/Python-Codes
/factorial.py
217
4.21875
4
#program to find factorial of given number using while loop:- n = int(input("Enter the no to find factorial\n")) temp = n f = 1 while(temp>0): f = f*temp temp = temp-1 print('factorial of ',n,'is', f)
true
de6c458f37b0512d53d4f87baa84115af4cc235c
infinitumodu/CPU-temps
/tableMaker.py
1,787
4.21875
4
#! /usr/bin/env python3 def makeXtable(data): """ Notes: This function takes the data set and returns a list of times Args: data: a list with each element containing a time and a list of the core tempatures at that time Yields: a list of times """ xTable = [] for temp in data: xTable.append(temp[0]) return xTable def makeYtable(data, core): """ Notes: This function takes the data set and a core number and returns a list of tempetures for the given core Args: data: a list with each element containing a time and a list of the core tempatures at that time core: 0-indexed core number Yields: a list of tempetures """ y = [] for temp in data: y.append(temp[1][core]) return y def makeXmatrix(data): """ Notes: This functions takes the data set and returns a list in which each element contains a list [1, temp]. Args: data: a list with each element containing a time and a list of the core tempatures at that time Yields: a matrix in nested list form """ xMatrix = [] for temp in data: xMatrix.append([1, temp[0]]) return xMatrix def makeYmatrix(data, core): """ Notes: Nearly identical to the makeYtable function but returns a list or lists to allow for use in matrix maniplations Args: data: a list with each element containing a time and a list of the core tempatures at that time core: 0-indexed core number Yields: a list of tempetures, where each element is a list """ y = [] for temp in data: y.append([temp[1][core]]) return y
true
d8275b0bbc9be8dbf86bd2657ab2a7c4e3768c02
jack-alexander-ie/data-structures-algos
/Topics/3. Basic Algorithms/1. Basic Algorithms/binary_search_first_last_indexes.py
2,635
4.125
4
def recursive_binary_search(target, source, left=0): if len(source) == 0: return None center = (len(source)-1) // 2 if source[center] == target: return center + left elif source[center] < target: return recursive_binary_search(target, source[center+1:], left+center+1) else: return recursive_binary_search(target, source[:center], left) def first_and_last_index(arr, number): """ Given a sorted array that may have duplicate values, use binary search to find the first and last indexes of a given value. Args: arr(list): Sorted array (or Python list) that may have duplicate values number(int): Value to search for in the array Returns: a list containing the first and last indexes of the given value """ if len(arr) == 1: # Check to see if array has more than 1 element if arr[0] == number: return [0, 0] else: return [-1, -1] rec_index = recursive_binary_search(number, arr) # Recursive call to find if element is in a list if not rec_index: return [-1, -1] start_index, end_index = rec_index, rec_index + 1 if end_index == len(arr): end_index -= 1 indexes = [start_index, end_index] # Find start index while arr[start_index] == number: if start_index == 0: break if arr[start_index - 1] == number: start_index -= 1 else: break # Find end index while arr[end_index] == number: if end_index == len(arr): break if end_index + 1 == len(arr): break if arr[end_index + 1] == number: end_index += 1 else: break return [start_index, end_index] def test_function(test_case): input_list = test_case[0] number = test_case[1] solution = test_case[2] output = first_and_last_index(input_list, number) if output == solution: print("Pass") else: print("Fail") input_list = [1] number = 1 solution = [0, 0] test_case_1 = [input_list, number, solution] test_function(test_case_1) input_list = [0, 1, 2, 3, 3, 3, 3, 4, 5, 6] number = 3 solution = [3, 6] test_case_2 = [input_list, number, solution] test_function(test_case_2) input_list = [0, 1, 2, 3, 4, 5] number = 5 solution = [5, 5] test_case_3 = [input_list, number, solution] test_function(test_case_3) input_list = [0, 1, 2, 3, 4, 5] number = 6 solution = [-1, -1] test_case_4 = [input_list, number, solution] test_function(test_case_4)
true
d2fdddb9967037869d65f92edf0a93c4a1717c6f
jack-alexander-ie/data-structures-algos
/Topics/2. Data Structures/Recursion/recursion.py
2,728
4.6875
5
def sum_integers(n): """ Each function waits on the function it called to complete. e.g. sum_integers(5) The function sum_integers(1) will return 1, then feedback: sum_integers(2) returns 2 + 1 sum_integers(3) returns 3 + 3 sum_integers(4) returns 4 + 6 sum_integers(5) returns 5 + 10 """ # Base Case if n == 1: return 1 return n + sum_integers(n - 1) # Works # print(sum_integers(5)) # Doesn't work # print(sum_integers(1000)) """ Python has a limit on the depth of recursion to prevent a stack overflow. However, some compilers will turn tail-recursive functions into an iterative loop to prevent recursion from using up the stack. Since Python's compiler doesn't do this, watch out for this limit. Tail-recursive functions are functions in which all recursive calls are tail calls and hence do not build up any deferred operations. Each call to factorial generates a new stack frame. The creation and destruction of these stack frames is what makes the recursive factorial slower than its iterative counterpart. """ def power(n): """ Each function waits on the function it called to complete. e.g. 2^5 The function power_of_2(0) will return 1: 1 returned from power_of_2(0), power_of_2(1) returns 2∗1 2 returned from power_of_2(1), power_of_2(2) returns 2∗2 4 returned from power_of_2(1), power_of_2(2) returns 2∗4 8 returned from power_of_2(1), power_of_2(2) returns 2∗8 16 returned from power_of_2(4), power_of_2(5) returns 2∗16 """ if n == 0: return 1 return 2 * power(n - 1) # Works # print(power(5)) # Causes max recursion depth error # print(power(1000)) def factorial(n): if n == 0 or n == 1: return 1 previous = factorial(n-1) return n * previous # print(factorial(5)) """ Slicing Arrays """ # Not particularly time or space efficient def sum_array(array): # Base Case - when down to it's last element if len(array) == 1: return array[0] # Recursive case - keep burrowing return array[0] + sum_array(array[1:]) # print(sum_array([1, 2, 3, 4, 5, 6])) def sum_array_index(array, index): """ Instead of slicing, pass the index for the element needed for addition. """ # Base Case - when the end of the array is reached if len(array) - 1 == index: return array[index] # Recursive Case - Same array passed in each time but index is incremented to grab values return array[index] + sum_array_index(array, index + 1) print(sum_array_index([1, 2, 3, 4, 5, 6], 0))
true
92d1e98c5ee646d5d8e9811c609af686208cb983
abhijitmk/Rock-paper-scissors-spock-lizard-game
/rock paper scissors spock lizard game.py
2,191
4.1875
4
# Rock-paper-scissors-lizard-Spock template # The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors import random # helper functions def name_to_number(name): if(name=="rock"): return 0 elif(name=="Spock"): return 1 elif(name=="paper"): return 2 elif(name=="lizard"): return 3 elif(name=="scissors"): return 4 # convert name to number using if/elif/else def number_to_name(number): if(number==0): return "rock" elif(number==1): return "Spock" elif(number==2): return "paper" elif(number==3): return "lizard" elif(number==4): return "scissors" # convert number to a name using if/elif/else def rpsls(player_choice): # print a blank line to separate consecutive games print "" # print out the message for the player's choice print "Player chooses",player_choice # convert the player's choice to player_number using the function name_to_number() player_value = name_to_number(player_choice) # compute random guess for comp_number using random.randrange() computer_value = random.randrange(0,5) # convert comp_number to comp_choice using the function number_to_name() computer_name = number_to_name(computer_value) # print out the message for computer's choice print "Computer chooses",computer_name # compute difference of comp_number and player_number modulo five difference = (player_value-computer_value)%5 if(difference==1) or (difference==2): return "Player wins!" elif(difference==3) or (difference==4): return "Computer wins!" else: return "Player and computer tie!" # use if/elif/else to determine winner, print winner message # test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE print rpsls("rock") print rpsls("Spock") print rpsls("paper") print rpsls("lizard") print rpsls("scissors")
true
0a3caa0649b0442ab39a9d4baebce376191a4767
jeevan-221710/AIML2020
/1-06-2020assignment.py
994
4.15625
4
#password picker import string from random import * print("Welcome password Picker!!!!") adj = ["Excellet","Very Good","Good","Bad","Poor"] noun = ["jeevan","sai","narra","anaconda","jupyter"] digits = string.digits spl_char = string.punctuation Welcome password Picker!!!! while True: password = choice(adj) + choice(noun) + choice(digits) + choice(spl_char) print("Your Password is : ",password) print("Do you want to generate New password? ") response = input("Enter yes for New password and No for Not generating the password: ") if response in ["NO","no","No","nO"]: break elif response in ["Yes","yes"]: continue else: print("Enter Either Yes or No") Your Password is : Excelletjeevan5^ Do you want to generate New password? Enter yes for New password and No for Not generating the password: yes Your Password is : Poorsai4! Do you want to generate New password? Enter yes for New password and No for Not generating the password: no
true
f820b900bce0f1a3de25fca50a91cf8a8a23eab9
MLameg/computeCones
/computeCones.py
811
4.375
4
import math print("This program calculates the surface area and volume of a cone.") r = float(input("Enter the radius of the cone (in feet): ")) h = float(input("Enter the height of the cone (in feet): ")) print("The numbers you entered have been rounded to 2 decimal digits.\nRadius = " +str(round(r,2))+ " feet & Height = " +str(round(h,2))+ " feet.") def cone_surface_area(r, h): sa1 = math.pi * (pow(r,2)) sa2 = (pow(r,2) + pow(h,2) ) sa3 = (math.pi * r) * math.sqrt(sa2) final = sa1 + sa3 print("The surface area of the cone is " +str(round(final,2))+ " feet.") def cone_volume(r,h): v1 = ( math.pi * (pow(r,2)) * h) final = v1 / 3 print("The volume of the cone is " +str(round(final,2))+ " feet.") cone_surface_area(r,h) cone_volume(r,h)
true
4b69f0783a133a08f34e2dc0a1190df3340dc0f1
Tha-Ohis/demo_virtual
/Functions/Using Funcs to guess highest number.py
400
4.15625
4
def highest_number(first, second, third): if first > second and first > third: print(f"{first}is the highest number") elif second > first and second > third: print(f"{second} is the highest number") elif third > first and third > second: print(f"{third} is the highest number") else: print("Two or more numbers are equal" ) highest_number(4,55,7)
true
81634c60ec9ab4a5d9c75c7de1eada0e8ec45865
Tha-Ohis/demo_virtual
/Program that checks the hrs worked in a day and displays the wage.py
631
4.25
4
# #Write a program that accepts the name, hours worked a day, and displays the wage of the person name=input("Enter your Name: ") hrs=float(input("Enter the No of Hours Worked in a day: ")) rate=20*hrs wage=(f"You've earned {rate}$") print(wage) # #Write a program that takes in the sides of a rectangle and displays its area and perimeter name=input("Enter your name: ") length=int(input("Enter the Length of a rectangle: ")) width=int(input("Enter the width of a rectangle: ")) area=length*width print(f"The area of the rectangle is:{area}") perimeter=(2*length + 2*width) print(f"The perimeter of the rectangle is:{perimeter}")
true
a0b3d022d89f844f0c0c0e577a64b17b64518869
xvrlad/Python-Stuff
/Lab01A - Q10.py
294
4.125
4
prompt = "Enter a word: " string = input(prompt) letter_list = list(string) letter_list.sort() new_dict = {} for letters in letter_list: if letters not in new_dict: new_dict[letters] = ord(letters) for letters, asciis in new_dict.items(): print("{}:{}".format(letters,asciis))
true
72f6ecdabe68de3f216b47c50f029dbb20d634cb
KrisNguyen135/PythonSecurityEC
/PythonRefresher/01-control-flow/loops.py
829
4.5625
5
#%% While loops check for the conditions at each step. x = 1 while x < 10: print(x) x += 1 print('Loop finished.') #%% For loops are used to iterate through a sequence of elements. a = [1, 2, 3] for item in a: print(item) print() #%% range(n) returns an iterator from 0 to (n - 1). for index in range(len(a)): print(index, a[index]) #%% One can loop through the keys in a dictionary in a for loop. dict = {'a': 1, 'b': 2, 'c': 3} for key in dict: print(key, dict[key]) print() #%% enumerate() returns the individual elements and their corresponding index # in pairs in a list. for index, value in enumerate(a): print(index, value) print() #%% zip() returns the individual elements of two given lists in pairs. b = [2, 3, 4] print(a) print(b) print() for a_i, b_i in zip(a, b): print(a_i, b_i)
true
d36fe85647e5b761c392d510b0227c48a40b6d38
faryar48/practice_bradfield
/python-practice/learn_python_the_hard_way/ex08.py
2,230
4.5
4
def break_words(stuff): """THis function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word def print_last_word(words): """Prints the last words after popping it off.""" word = words.pop(-1) print word def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) # In this exercise we're going to interact with your ex25.py file inside the python interpreter you used periodically to do calculations. You run python from the terminal like this: # $ python # Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) # [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin # Type "help", "copyright", "credits" or "license" for more information. # >>> # import ex25 # sentence = "All good things come to those who wait." # words = ex25.break_words(sentence) # words # sorted_words = ex25.sort_words(words) # sorted_words # ex25.print_first_word(words) # ex25.print_last_word(words) # words # ex25.print_first_word(sorted_words) # ex25.print_last_word(sorted_words) # sorted_words # sorted_words = ex25.sort_sentence(sentence) # sorted_words # ex25.print_first_and_last(sentence) # ex25.print_first_and_last_sorted(sentence) # When should I print instead of return in a function? # The return from a function gives the line of code that called the function a result. You can think of a function as taking input through its arguments, and returning output through return. The print is completely unrelated to this, and only deals with printing output to the terminal.
true
c119cf284f9e9afe49e906b8f4b1ff771eee66c9
ddh/codewars
/python/range_extraction.py
1,817
4.625
5
""" A format for expressing an ordered list of integers is to use a comma separated list of either individual integers or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17") Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. Example: solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-6,-3-1,3-5,7-11,14,15,17-20" """ # idea: # save current_index # if in range mode # is next number consecutive # # No? then exit range mode and append to string current number and append running string into array # If not in range mode # # Check if possible range exist (three numbers) # # If possible range exists, turn on range mode and store 'currentnumber + -' # Else append current number def solution(args): extracted_nums = [] range_mode = False range_string = None for i, num in enumerate(args): if range_mode: # Break out of range mode if on last index or if next number is not contiguous if i == len(args) - 1 or args[i + 1] != num + 1: range_mode = False extracted_nums.append(f'{range_string}{str(num)}') else: # Toggle range mode if there's two numbers ahead and they are contiguous if i < len(args) - 2 and args[i + 2] - num == 2: range_mode = True range_string = str(f'{num}-') else: extracted_nums.append(str(num)) return ','.join(extracted_nums) # Driver print(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]))
true
14390a2ae3b6ad53a988c321de9df62ad7110e00
ddh/codewars
/python/basic_mathematical_operations.py
1,478
4.34375
4
""" Your task is to create a function that does four basic mathematical operations. The function should take three arguments - operation(string/char), value1(number), value2(number). The function should return result of numbers after applying the chosen operation. Examples basic_op('+', 4, 7) # Output: 11 basic_op('-', 15, 18) # Output: -3 basic_op('*', 5, 5) # Output: 25 basic_op('/', 49, 7) # Output: 7 """ def basic_op(operator, value1, value2): # code here if operator == '+': return value1 + value2 if operator == '-': return value1 - value2 if operator == '*': return value1 * value2 if operator == '/': return value1 / value2 # driver print(basic_op('+', 4, 7)) # Output: 11 print(basic_op('-', 15, 18)) # Output: -3 print(basic_op('*', 5, 5)) # Output: 25 print(basic_op('/', 49, 7)) # Output: 7 # Try doing this with only using addition: sum or + def basic_op2(operator, value1, value2): if operator == '+': return value1 + value2 if operator == '-': return value1 + -value2 if operator == '*': return sum([value1 for n in range(value2)]) if operator == '/': count = 0 while value1 != 0: value1 += -value2 count += 1 return count # driver print(basic_op2('+', 4, 7)) # Output: 11 print(basic_op2('-', 15, 18)) # Output: -3 print(basic_op2('*', 5, 5)) # Output: 25 print(basic_op2('/', 49, 7)) # Output: 7
true
160c7cb9ab9719c4d0573ce90bb4c9e70ba1ca9b
junyechen/PAT-Advanced-Level-Practice
/1108 Finding Average.py
2,573
4.34375
4
""" The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in. Input Specification: Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N numbers are given in the next line, separated by one space. Output Specification: For each illegal input number, print in a line ERROR: X is not a legal number where X is the input. Then finally print in a line the result: The average of K numbers is Y where K is the number of legal inputs and Y is their average, accurate to 2 decimal places. In case the average cannot be calculated, output Undefined instead of Y. In case K is only 1, output The average of 1 number is Y instead. Sample Input 1: 7 5 -3.2 aaa 9999 2.3.4 7.123 2.35 Sample Output 1: ERROR: aaa is not a legal number ERROR: 9999 is not a legal number ERROR: 2.3.4 is not a legal number ERROR: 7.123 is not a legal number The average of 3 numbers is 1.38 Sample Input 2: 2 aaa -9999 Sample Output 2: ERROR: aaa is not a legal number ERROR: -9999 is not a legal number The average of 0 numbers is Undefined """ ######################################### """ 非常简单,利用异常机制 """ ######################################### N = int(input()) number = input().split() total, amount = 0, 0 for i in range(N): try: number_int = int(number[i]) if -1000 <= number_int <= 1000: total += number_int amount += 1 else: print("ERROR: %s is not a legal number" % number[i]) except: try: number_float = float(number[i]) number_split = number[i].split('.') if len(number_split[1]) > 2: print("ERROR: %s is not a legal number" % number[i]) else: if -1000 <= number_float <= 1000: total += number_float amount += 1 else: print("ERROR: %s is not a legal number" % number[i]) except: print("ERROR: %s is not a legal number" % number[i]) if amount == 0: print("The average of 0 numbers is Undefined") elif amount == 1: print("The average of 1 number is %.2f" % total) else: print("The average of %d numbers is %.2f" % (amount, total/amount))
true
7ac060f0eaedadd5c18d3dce33afa776639f45f2
TranD2020/Backup
/lists.py
1,315
4.34375
4
# Make a list myClasses = ["Algebra", "English", "World History"] print(myClasses) # add an item to the list # append or insert # append will add to the back of the list myClasses.append("Coding") print(myClasses) favClass = input("What is your favorite class? ") myClasses.append(favClass) print(myClasses) # insert myClasses.insert(3, "Art") print(myClasses) # overwrite myClasses[4] = "Science" print(myClasses) # remove list items # remove, pop # remove will remove a specific item myClasses.remove("Science") print(myClasses) # myClasses.remove("Lunch") # pop will remove the item at a specific index myClasses.pop() # erases the last item print(myClasses) myClasses.pop(1) print(myClasses) # len - it returns the length of a list print("myClasses is " + str(len(myClasses)) + " items long") print(myClasses[len(myClasses) - 1]) # loop through a list count = 1 for aClass in myClasses: print("Item " + str(count) + " is " + aClass) count = count + 1 numbers = [1, 23, 47, 65, 89, 32, 54, 76] # challenge: loop through the list add the numbers and print the sum total = 0 for aNum in numbers: total += aNum print(total) myClasses.append("cooking") #.append("cooking") if "cooking" in myClasses: print("Have fun cooking") else: print("Ok then")
true
aa5d7c78bc0e77b5ad660b713b65b918ae20707d
TranD2020/Backup
/practice3.py
393
4.375
4
print("Hello, this is the Custom Calendar.") day = input("What is today(monday/tuesday/wednesday/thursday/friday/saturday/sunday): ") if day == "monday": print("It's Monday, the weekend is over") elif day == "friday": print("It's Friday, the weekend is close") elif day == "saturday" or "sunday": print("It's the weekend, time to relax") else: print("Its not the weekend yet")
true
a795152079fe503c87516ab5b753c0c33c504c73
gouri21/c97
/c97.py
491
4.25
4
import random print("number guessing game") number = random.randint(1,9) chances = 0 print("guess a number between 1 and 9") while chances<5: guess = int(input("enter your guess")) if guess == number: print("congratulations you won!") break elif guess<number: print("guess a number higher than that",guess) else: print("guess a number lower than that",guess) chances +=1 if not chances<5: print("you lose and the number is",number)
true
e0883ed37e79623f17ea2eaae85cc49b05e012ea
BigPPython/Name
/name.py
1,110
4.125
4
# Code: 1 # Create a program that takes a string name input, # and prints the name right after. # Make sure to include a salutation. import sys a = '''********************************** *WHAT IS YOUR SEXUAL ORIENTATION?* *TYPE * *M FOR MALE * *F FOR FEMALE * **********************************''' print(a) # prints string a sex = str(input()) # user input s ='' if sex in ['M', 'm']: # Conditional statement for question above s = 'Mr.' elif sex in ['F', 'f']: b = ''' ****************** *ARE YOU MARRIED?* *TYPE * *YES OR NO * ******************''' print(b) m = str(input()) if m in ['y', 'Y', 'yes', 'Yes', 'YES']: # accepts all yes like answer s = 'Mrs ' elif m in ['n', 'N', 'no', 'No', 'NO']: # accepts all no like answers s = 'Ms ' else: print("PLEASE TRY AGAIN") sys.exit() else: print("PLEASE TRY AGAIN") sys.exit() print('Insert name here:') name = str(input()) print('Hello, '+ s + name) # prints final result sys.exit()
true
5cf92bdd9fbd1820297c63dcb370a5d7b3bb1129
SKosztolanyi/Python-exercises
/11_For loop simple universal form.py
345
4.25
4
greeting = 'Hello!' count = 0 # This is universal python for loop function form # The "letter" is <identifier> and "greeting" is <sequence> # the "in" is crucial. "letter" can be changed for any word and the function still works for letter in greeting: count += 1 if count % 2 == 0: print letter print letter print 'done'
true
11cea43282d93c8ff11abe1bd833275be18744c6
SKosztolanyi/Python-exercises
/88_Tuples_basics.py
1,136
4.6875
5
# Tuples are non-changable lists, we can iterate through them # Tuples are immutable, but lists are mutable. # String is also immutable - once created, it's content cannot be changed # We cannot sort, append or reverse a tuple # We can only count or index a tuple # The main advantage of a tuple is, they are more efficient # We can use tuples when we make temporary variables # The items() method in a dictionary returns a list of (key, value) tuples # We can sort dictionaries by sorting tuples in dictionary # Method dict.sort() sorts by keys - the values don't even get looked at. d = { "b":2, "a":10, "c":18} t = d.items() print t t.sort() print t t2 = sorted(d.items()) # this is more direct method print t2 # It is possible to sort a dictionary by values when I iterate through a list of values c = { "b":2, "a":10, "c":18, "d":-16, "e": 21} print c tmp = list() for k, v in c.items(): tmp.append( (v, k) ) # reversing keys and values print tmp tmp.sort(reverse = True) print tmp #short verion: d = { "b":2, "a":10, "c":18, "d":-16, "e": 21} print sorted( [ (v, k) for k, v in d.items() ] ) # sorted by value in one line
true
d0fc126abdd1251d5c7555870ec36b49798c8936
SKosztolanyi/Python-exercises
/33_Defining factorials functions iterativela and recursively.py
374
4.15625
4
# Recursive and iterative versions of factorial function def factI(n): ''' Iterative way assume that n is an int>0, returns n! ''' res = 1 while n >1: res = res*n n-=1 return res def factR(n): ''' Recursive way assume that n is an int>0, returns n! ''' if n == 1: return n return n*factR(n-1)
true