blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
983b106ab6e4e093ee330866707bd6e35b7df3da
barvaliyavishal/DataStructure
/Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/removeDuplicates.py
766
4.25
4
from LinkedList import LinkedList class RemoveDuplicates: # Remove duplicates Using O(n^2) def removeDuplicates(self, head): if head.data is None: return temp = head while temp.next: start = temp while start.next: if start.next.data == temp.data: start.next = start.next.next else: start = start.next temp = temp.next obj = LinkedList() obj.add(1) obj.add(2) obj.add(3) obj.add(3) obj.add(4) obj.add(5) obj.add(7) obj.add(9) obj.add(2) obj.add(2) print("Before Removing Duplicates") obj.show() obj1 = RemoveDuplicates() obj1.removeDuplicates(obj.head) print() print("After Removing Duplicates") obj.show()
true
923aafcb9147d70e62d8512fabb477b5a8365a5e
garciaha/DE_daily_challenges
/2020-08-13/eadibitan.py
1,788
4.15625
4
"""Eadibitan You're creating a conlang called Eadibitan. But you're too lazy to come up with your own phonology, grammar and orthography. So you've decided to automatize the proccess. Write a function that translates an English word into Eadibitan. English syllables should be analysed according to the following rules: - Syllables will follow the pattern (C)(C)V(V(V))(C), where C is a consonant and V is a vowel. Parentheses indicate that an element is optional. - The pattern CVCV will be analyzed as CV-CV. - The pattern CVCCV will be analyzed as CVC-CV - The pattern CVCCCV will be analyzed as CVC-CCV - Two or three consecutive vowels will always form a diphthong and a triphthong respectively. Meaning they will be grouped in the same syllable. - A y should be analyzed as a consonant if followed by a vowel, and as a vowel otherwise. The order of the letters of each syllable should be altered according to the following table: English Eadibitan c1 v1 v1 c1 c1 v1 v2 v1 c1 v2 c1 v1 v2 v3 v1 c1 v2 v3 c1 v1 c2 v1 c1 c2 c1 v1 v2 c2 v1 c1 v2 c2 c1 v1 v2 v3 c2 v1 c1 v2 v3 c2 c1 c2 v1 c2 v1 c1 c1 c2 v1 v2 c2 v1 c1 v2 c1 c2 v1 v2 v3 c2 v1 c1 v2 v3 c1 c2 v1 c3 c2 v1 c1 c3 c1 c2 v1 v2 c3 c2 v1 c1 v2 c3 c1 c2 v1 v2 v3 c3 c2 v1 c1 v2 v3 c3 Any other pattern should be left untouched. Notes: - You can expect only lower case single words as arguments. - Bonus: Try to solve it using RegEx. """ def eadibitan(word): pass if __name__ == "__main__": assert eadibitan("edabitian") == "eadibitan" assert eadibitan("star") == "tasr" assert eadibitan("beautiful") == "ebauitufl" assert eadibitan("statistically") == "tasittisaclyl" print("All cases passed!")
true
85051a8cef826a0fb73dfc66172c8f588dc3433f
garciaha/DE_daily_challenges
/2020-07-09/maximize.py
1,015
4.1875
4
""" Maximize Write a function that makes the first number as large as possible by swapping out its digits for digits in the second number. To illustrate: max_possible(9328, 456) -> 9658 # 9658 is the largest possible number built from swaps from 456. # 3 replaced with 6 and 2 replaced with 5. Each digit in the second number can only be used once. Zero to all digits in the second number may be used. """ def max_possible(num_1, num_2): num1_list = [int(x) for x in str(num_1)] num2_sort = sorted([int(x) for x in str(num_2)], reverse = True) index = 0 for x in range(len(num1_list)): if num2_sort[index] > num1_list[x]: num1_list[x] = num2_sort[index] index += 1 if index >= len(num2_sort): break return int("".join([str(x) for x in num1_list])) if __name__ == '__main__': assert max_possible(523, 76) == 763 assert max_possible(9132, 5564) == 9655 assert max_possible(8732, 91255) == 9755 print("All cases passed!")
true
081fa71ed4ff5ac6c1e5402c48cbb46429f5e46f
garciaha/DE_daily_challenges
/2020-08-20/summer_olympics.py
1,058
4.21875
4
"""Summer Olympics Analyse statistics of Olympic Games in the summer CSV file. Create a function that returns 1. Find out the (male and female) athlete who won most medals in all the Summer Olympic Games (1896-2014). 2. Return the first 10 countries that won most medals: Bonus: Use pandas to create a dataframe you can work on SELECT Name FROM summer.csv WHERE Gender = gender (input) GROUP BY Name ORDER BY COUNT(Medal) LIMIT RESULTS TO 1 SELECT Country FROM summer.csv WHERE Gender = gender GROUP BY Name ORDER BY COUNT(Medal) LIMIT RESULTS TO 10 """ def summer_olympic_medals(gender, countries=False): pass if __name__ == "__main__": assert summer_olympic_medals('Men') == "Michael Phelps" assert summer_olympic_medals('Women') == "Larisa Latynina" assert summer_olympic_medals("Men", True) == [ 'USA', 'URS', 'GBR', 'FRA', 'ITA', 'SWE', 'GER', 'HUN', 'AUS', 'JPN'] assert summer_olympic_medals("Women", True) == [ 'USA', 'URS', 'CHN', 'AUS', 'GER', 'GDR', 'RUS', 'NED', 'ROU', 'GBR'] print("All cases passed!")
false
736a16c6c9f13efd689a4449c5bdaef22d1d96fc
garciaha/DE_daily_challenges
/2020-08-03/unravel.py
641
4.4375
4
"""Unravel all the Possibilities Write a function that takes in a string and returns all possible combinations. Return the final result in alphabetical order. Examples unravel("a[b|c]") -> ["ab", "ac"] Notes Think of each element in every block (e.g. [a|b|c]) as a fork in the road. """ def unravel(string): pass if __name__ == "__main__": assert unravel("a[b|c]de[f|g]") == ["abdef", "acdef", "abdeg", "acdeg"] assert unravel("a[b]c[d]") == ["abcd"] assert unravel("a[b|c|d|e]f") == ["abf", "acf", "adf", "aef"] assert unravel("apple [pear|grape]") == ["apple pear", "apple grape"] print("All cases passed!")
true
8cd9783dc602893f32c52a2c4c2e21952662def3
garciaha/DE_daily_challenges
/2020-07-22/connect.py
1,742
4.28125
4
"""Connecting Words Write a function that connects each previous word to the next word by the shared letters. Return the resulting string (removing duplicate characters in the overlap) and the minimum number of shared letters across all pairs of strings. Examples connect(["oven", "envier", "erase", "serious"]) -> ["ovenvieraserious", 2] connect(["move", "over", "very"]) -> ["movery", 3] connect(["to", "ops", "psy", "syllable"]) -> ["topsyllable", 1] # "to" and "ops" share "o" (1) # "ops" and "psy" share "ps" (2) # "psy" and "syllable" share "sy" (2) # the minimum overlap is 1 connect(["aaa", "bbb", "ccc", "ddd"]) -> ["aaabbbcccddd", 0] Notes More specifically, look at the overlap between the previous words ending letters and the next word's beginning letters. """ def connect(words): shared = [] connected = words[0] for x in range(1, len(words)): start = words[x][0] end = words[x-1][-1] last = words[x-1][::-1] spos = last.find(start) epos = words[x].find(end) if start in words[x-1] and end in words[x] and last[:spos+1][::-1] == words[x][:epos+1]: shared.append(epos+1) connected += words[x][epos+1:] else: shared.append(0) connected += words[x] return [connected, min(shared)] if __name__ == '__main__': assert connect(["oven", "envier", "erase", "serious"]) == [ "ovenvieraserious", 2] assert connect(["move", "over", "very"]) == ["movery", 3] assert connect(["to", "ops", "psy", "syllable"]) == ["topsyllable", 1] assert connect(["silver", "version", "onerous", "usa", "apple", "please"]) == [ "silversionerousapplease", 1] print("All cases passed!")
true
79b243b7c8dc4a887e111dac8b620adb5db55420
garciaha/DE_daily_challenges
/2020-09-09/all_explode.py
1,679
4.21875
4
"""Chain Reaction (Part 1) In this challenge you will be given a rectangular list representing a "map" with three types of spaces: - "+" bombs: When activated, their explosion activates any bombs directly above, below, left, or right of the "+" bomb. - "x" bombs: When activated, their explosion activates any bombs placed in any of the four diagonal directions next to the "x" bomb. - Empty spaces "0". Consider the grid: [ ["+", "+", "0", "x", "x", "+", "0"], ["0", "+", "+", "x", "0", "+", "x"] ] If the top left "+" bomb explodes, the resulting chain reaction will blow up bombs in the order given by the numbers below: [ ["1", "2", "0", "x", "6", "8", "0"], ["0", "3", "4", "5", "0", "7", "8"] ] Note that there are two 8's since two of the bombs explode at the same time. Also, note that one of the "x" bombs in the top row does not explode. Write a function that determines if the chain reaction started when the top left bomb explodes destroys all bombs or not. Notes Both "+" and "x" bombs have an "explosion range" of 1. """ def all_explode(bombs): pass if __name__ == "__main__": assert all_explode([ ["+", "+", "+", "+", "+", "+", "x"] ]) == True assert all_explode([ ["+", "+", "+", "+", "+", "0", "x"] ]) == False assert all_explode([ ["+", "+", "0", "x", "x", "+", "0"], ["0", "+", "+", "x", "0", "+", "x"] ]) == False assert all_explode([ ["x", "0", "0"], ["0", "0", "0"], ["0", "0", "x"] ]) == False assert all_explode([ ["x", "0", "x"], ["0", "x", "0"], ["x", "0", "x"] ]) == True print("All cases passed!")
true
56ae86a640e1ffef13d7f04792943bfd696a6b9d
Yossarian0916/AlogrithmsSpecialization
/insertion_sort.py
380
4.15625
4
# insertion sort def insertion_sort(array): for i in range(1, len(array)): # insert key into sorted subarray card = array[i] j = i-1 while j >= 0 and array[j] > card: array[j+1] = array[j] j = j-1 array[j+1] = card if __name__ == '__main__': lst = [8, 7, 3, 6, 3, 2] insertion_sort(lst) print(lst)
false
a0042c5e43f8b7608b580d7e0fa70876a50a9da4
tahe-ba/Programmation-Python
/serie/serie 3 liste/code/exemple.py
225
4.21875
4
# creating an empty list lst = [] # number of elemetns as input n = int(input("Enter number of elements : ")) for i in range(n): ele = int(input("element n° "+str(i+1)+": ")) lst.append(ele) print (lst)
false
891b21382cc0cd84bb66d14ef296e4f70a230ccc
tahe-ba/Programmation-Python
/serie/serie 3 liste/code/ex9.py
369
4.21875
4
''' program to find the list of words that are longer than n from a givenlist of words. ''' li = [] li = [item for item in input("Enter the words seperated by space: ").split()] msg=input("text= ") txt=msg.split(" ") print (txt) print (li) n=int(input("longueur de mot ")) lw = [] for i in range(len(li)): if len(li[i]) > n : lw.append(li[i]) print (lw)
false
31de87045288069ce8dc80acd46cda2ff4d86dd8
tahe-ba/Programmation-Python
/serie/serie 1 I-O/code/second.py
629
4.15625
4
# Find how many numbers are even and how many are odd in a sequenece of inputs without arrays while True : try : n=int(input("combien d'entier vous aller entrer: ")) break except ValueError: print("Wrong input") j=z=0 for i in range(n): while True : try : x=int(input("saisir le "+str(i+1)+"° nombre: ")) if (x%2==0) : j=j+1 else : z=z+1 break except ValueError: print("Wrong input") print("Il y a "+str(j)+" nombre pair") print("Il y a "+str(z)+" nombre impair")
false
381007913bcd073e5a1aa745b00ea030fe371b84
sandeepvura/Mathematical-Operators
/main.py
538
4.25
4
print(int(3 * 3 + 3 / 3 - 3)) # b = print(int(a)) **Mathematical Operators** ``` ###Adding two numbers 2 + 2 ### Multiplication 3 * 2 ### Subtraction 4 - 2 ### Division 6 / 3 ### Exponential When you want to raise a number 2 ** 2 = 4 2 ** 3 = 8 ``` ***Note:*** Order of Mathematical operators to execute is like "PEMDAS" P - Parentheses - () E - Exponents - ** M - Multiplication - * D - Division - / A - Addition - + S - Subtraction - *Example* : Rule of PEMDAS ``` print( 3 * 3 + 3 / 3 - 3) #Find the output. ```
true
44c3662bac6085bd63fcb52a666c2e81e5a683ff
farhadkpx/Python_Codes_Short
/list.py
1,689
4.15625
4
#list # mutable, multiple data type, un-ordered lis = [1,2,3,4,5,6,7,8,9] #nos lis2 = ['atul','manju','rochan'] #strings lis3 = [1,'This',2,'me','there'] #both #create empty list lis4 = [] #empty lis5 = list() #empty #traversl for item in lis: print (item), #slicing print (lis[:],lis[2:3],lis[3:]) #Mutable lis[5] ='Singh' print (lis) print (lis2) #addition using + operator only for single element lis2 = lis2 + ['manju'] #to concatenate using append only single element lis2.append('newval') print (lis2) #for more values addition to the list lis2.extend(['one','two']) print (lis2) #addition of elements in a specified place in the list lis2.insert(5,'fifth') print (lis2) #list inside an other list #lis2.insert(0,['start','element']) print (lis2) #accessing list inside the list print(lis2[0][0]) #prints 'start' print(lis2[0][1]) #prints 'element' #removing the elements from the list #pop lis2.pop() #removes the last element always print (lis2) lis2.pop() print (lis2) rval1=lis2.pop() rval2=lis2.pop() print (lis2) print (rval1,rval2) print (len(lis2)) #0,13 # index or indicies deletion - del(not returned deleted elements) del lis2[1] print (lis2) #range to delete del lis2[1:3] print (lis2) #delete the element by values lis2.append('three') print(lis2) lis2.remove('three') print (lis2) lis2.append('one') lis2.append('two') lis2.append('three') #sort the list lis2.sort() print (lis2) #lis.sort(reverse=True) print (lis2) Name = 'manjunath manikumar' name_list = list(Name) print (name_list) #split word_list = Name.split() print (word_list) #alias print (lis3) alias3 = lis3 print (alias3) alias3[2] = 'changed' print (lis3) print (alias3) #alias
true
28ec5060a74ff5c0e0f62742317d22266a5f41a2
sadieBoBadie/feb-python-2021
/Week1/Day2/OOP/intro_OOP.py
2,111
4.46875
4
#1. # OOP: # Object Oriented Programming # Style of programming uses a blueprint for modeling data # Blueprint defined by the programmer -- DIY datatypes # -- customize it for your situation # Modularizing # 2: # What is CLASS: # User/Programmer defined data-type # Like a function is a recipe --- class is blueprint for the datatype # 3. What are... # Attributes/properties # Characteristics -- variables that belong to the class # What a class of objects HAS --> data #ex: car # -- model -- string (corolla) # -- make -- string (toyota) # JS: my_arr = [3, 4, 5] # console.log( my_arr.length ) # Methods # Functions that often affect the properties of the class # Functions that belong to the class -- # What a class of objects can DO --> actions/functions my_list = [3, 4, 5] my_list.append(8) # --> [3, 4, 5, 8] # Quiz Challenge: # self.store = store # self.items.append(item) # def add_item(self, item, price): # self.items = [] # def __init__(self, store): # class ShoppingCart: # return self # self.total = 0 # self.total += price class ShoppingCart: def __init__(self, specific_store): self.total = 0 self.store = specific_store self.items = [] def add_item(self, thing, price): self.total += price self.items.append(thing) return self def show_cart(self): print(f"Store: {self.store}, total: {self.total}") print(f"Items: {self.items}") sadie_shopping_cart = ShoppingCart("Safeway") print(sadie_shopping_cart) print(sadie_shopping_cart.store) nate_cart = ShoppingCart("Target") print(nate_cart) print(nate_cart.store) nate_cart.store = "Amazon" nate_cart.items.append("apples") nate_cart.total += 3.00 nate_cart.add_item("apples", 3.00) nate_cart.add_item("pears", 3.00) nate_cart.add_item("broccoli", 5.00) # nate_cart.items.append("mango") # nate_cart.total += 5.0 # nate_cart.show_cart() # sadie_shopping_cart.show_cart() # nate_cart.add_item("Star Wars Figurine", 50.00) # nate_cart.add_item("apple", 0.99)
true
36c9bac791ef0ee4aba78e32851a4fcb6756fafb
Lawlietgit/Python_reviews
/review.py
2,202
4.15625
4
# 4 basic python data types: # string, boolean, int, float # str(), bool(), int(), float() # bool("False") --> True # bool("") --> False # bool(10.2351236) --> True # bool(0.0) --> False # bool(object/[1,2,3]) --> True # bool([]) --> False # bool(None) --> False # FIFO --> queue data structure # LIFO --> stack a = [1,2,3] # queue: for _ in range(len(a)): print(a.pop(0)) print(a) a = [1,2,3] # while len(a) > 0: while a: print(a.pop(0)) print(a) # stack: a = [1,2,3] while a: print(a.pop()) print(a) # class/objects (scalable/extensible) # e.g. build a system for a library # people can register as a user/member # members can check-out and return books # books should be classified by generics class Books: attrs: cost/n_stocks/popularity/theme methods: #class MusicBooks(Books): # attrs: class Users: attrs: member_id(KEY)/account balance/age/email/dob/name methods: check_out(book)/return_book(book) # time complexity (big O notation) # space complexity (big O notation) # 2 types of problems: # P - Polynomial (O(N), O(N^2), O(N^p)) # NP - not possible for Poly time # NP - problem itself cannot be solved in P, but verifying the problem takes P # NP hard - verifying it takes more than P (postman) # A # B # C # A B C #A 0 21 #B 21 0 40 #C 40 0 # A - B --> 21 km # B - C --> 40 km ... # A --> A search for the best route (shortest total distance) to connect all the towns, # and return to A. # loop (keep visiting a town many times) # N --> infinity # O(a*N^c + b) a, b, c are constants --> O(N^c) # dictionary/sets # visit element time O(1) # a = [1,2,3, 3,3,3,3,3], a[0] # check if 3 is in a: # a_set = {1,2,3} # check if 3 is in a set: # in a set, the elements have to be unique # a set can be used as the key set for a dictionary # a_dic = {0:2, 1:2} k:v a_dic[0] -->2 """ print(3 in a) --> True O(N) print(3 in a_set) --> True O(1) a_lis.append(), .remove(), .pop(), .insert() a_set.add(), .remove() a_dic[new_key] = new_value, a_dic.remove(key) """
true
4fd15d3e74cb6ea719d26bf9f30704f5f7c7de7b
mfcust/sorting
/sorting.py
2,274
4.53125
5
# 1) Run the code in the markdown and write a comment about what happens. # 2) Try to print(sorted(my_list2)) and print(my_list2.sort()). Is there a difference? What do you observe? my_list2 = [1,4,10,9,8,300,20,21,21,46,52] # 3) Let's say you wanted to sort your list but in reverse order. To do this, you can put reverse=True inside the parentheses (for either sort() or sorted(). # Try it below, and then print your reverse sorted list! my_list3 = [1,4,10,9,8,300,20,21,21,46,52] # 4) But Mr. Custance, to this point all I've been sorting are lists with integer values inside. How does .sort() and sorted() organize string values? # Sort the following list, print it and comment on how it was sorted: word_list = ["pizza", "frog", "lemon", "lemon", "computer", "water bottle", "lamp", "table", "radio", "speaker"] # 5) Do the same for the following list: word_list2 = ["lamb", "lap", "lalalala", "laaaa", "larynx", "laguardia", "laproscopy", "lad"] # 6) How does the .sort() method and sorted function deal with lists that have multiple data types? Create a list that has integers, strings and floats. Sort and print, and then comment on the results. # 7) Let's say you wanted to sort a list based purely on length of characters. You can define a function that returns the length of an item, and then use # that as the key for your sort. For example: ''' def len_func(a): return(len(a)) length_list = ["aaaaaaa", "aaaaa", "aaa", "a", "aaaaaaaaaaaaaaa", "aa", "aaaaaaaaaa", "", "aaaaaaaaaaaaaaaaaaa", "aaaaa", "aaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaa", " ", "bcbcbdhbb", "dibvibfv", "a"] ''' #Uncomment the code above, and sort it using either sort() or sorted(). When you do, in the parentheses include key = len_func. This makes the key based on the function you've defined #Print your new list below # 8) Print the list from the previous question, but in reverse length order. # 9) Can .sort() and sorted() be used to sort the chracters in a string? Try it below and comment. ###Bonus### # 1) Write a program that populates an empty list with 100 random numbers between a minumum and maximum of your choice. Then, sort your new list from smallest to biggest and print your newly sorted list.
true
5b9dff75a516f758e8e8aef83cf89794176b488b
Mukilavan/LinkedList
/prblm.py
880
4.21875
4
#Write a Python program to find the size of a singly linked list. class Node: def __init__(self, data, next=None): self.data = data self.next = next class linkedList: def __init__(self): self.head = None def insert_beg(self, data): node = Node(data, self.head) self.head = node def insert_end(self, data): if self.head is None: self.insert_beg(data) return itr = self.head while itr.next: itr = itr.next itr.next = Node(data) def list_size(self): itr = self.head count = 0 while itr: count += 1 itr = itr.next return count if __name__ == '__main__': ll = linkedList() ll.insert_beg(20) ll.insert_beg(20) ll.insert_end(50) print(ll.list_size())
true
6da93542a02ae983ed180784310ea3eeaa2985dc
Paradox-1337/less3
/les3_4.py
1,344
4.21875
4
# Решение1 # x = int(input("Введите чило для возведения в степень: ")) # y = int(input("Введите отрицательное чило, для возведения числа X в эту степень: ")) # if y <= 0: # x_y = x**y # print(x_y) # else: # print("Введите отрицательное число! ") # Решение 2 # def my_func(): # x = float((input("Введите чило для возведения в степень: "))) # y = int(input("Введите отрицательное чило, для возведения числа X в эту степень: ")) # if y <= 0: # return x**y # else: # return "Введите отрицательное число!" # # # print(my_func()) # Решение 3 # def my_func(x, y): # result = 1 # for i in range(abs(y)): # result *= x # if y >= 0: # return "Нужно отрицательное число!" # else: # return 1 / result # # # print(my_func(float(input("Введите число 'X' для возведения в степень: ")), # int(input("Введите отрицательное чило, для возведения числа X в эту степень: "))))
false
f10be4d04fea97886db620447999632fc3c706da
Nishinomiya0foa/Old-Boys
/1_base_OO_net/day24_3features/4_multi_Inheritance.py
1,402
4.53125
5
"""多继承 平时尽量不用! 应使用单继承 """ # class A: # def func(self): # print('A') # # class B: # def func(self): # print('B') # # class C: # def func(self): # print('C') # # class D(A, B, C): # pass # # def func(self): # # print('D') # # d = D() # d.func() # 如果D()中有 func方法,则调用其本身的 # 如果D()中没有func方法,则调用A类中的,从左往右,顺序为(A,B,C) """钻石继承 A,B,C,D 四个类 # PS。-> 表示继承关系 B->A C->A D->B,C """ class A: def func(self):print('A') class B(A): pass # def func(self):print('B') class C(A): def func(self):print('C') class D(B, C): pass # def func(self):print('D') d = D() d.func() # 如果D()中,有func方法,则调用本身的 # 如果D()中,无func方法,则调用父类B()中的 # 如果父类B()中,也无func方法;则调用D()的第二个父类C()中的 ---- 先找同级的! """广度优先!""" # 如果第二个父类C()中,也无func方法,则找第一个父类的父类方法 print(D.mro()) # mro()方法记录了继承顺序 # 就近原则 # 新式类的继承顺序:广度优先 # 经典类的继承顺序:深度优先 # super的本质:不是直接找父类,而是根据调用者的节点位置的广度优先
false
50042e3c7051ee2be4a19e9d4f858a22a7be88f7
clarkjoypesco/pythoncapitalname
/capitalname.py
332
4.25
4
# Write Python code that prints out Clark Joy (with a capital C and J), # given the definition of z below. z = 'xclarkjoy' name1 = z[1:6] name1 = name1.upper() name1 = name1.title() name2 = z[-3:] name2 = name2.upper() name2 = name2.title() print name1 + ' ' + name2 s = "any string" print s[:3] + s[3:] print s[0:] print s[:]
true
ee8a14b46db017786571c81da934f06a614b3553
Jamsheeda-K/J3L
/notebooks/lutz/supermarket_start.py
1,724
4.3125
4
""" Start with this to implement the supermarket simulator. """ import numpy as np import pandas as pd class Customer: '''a single customer that can move from one state to another''' def __init__(self, id, initial_state): self.id = id self.state = initial_state def __repr__(self): return f'Supermarket with {len(self.customers)} customers' def next_state(self): pass def is_active(self): pass class Supermarket: """manages multiple Customer instances that are currently in the market. """ def __init__(self): # a list of Customer objects self.customers = [] self.minutes = 0 self.last_id = 0 def __repr__(self): pass def get_time(): """current time in HH:MM format, """ def print_customers(): """print all customers with the current time and id in CSV format. """ def next_minute(): """propagates all customers to the next state. """ #increase the time of the supermarket by one minute lidl.next_minute def add_new_customers(): """randomly creates new customers. """ def remove_exitsting_customers(): """removes every customer that is not active any more. """ # start a simulation if __name__ == '__main__': # this code executed when we run the file python supermarket.py lidl = Supermarket() print(lidl) lidl.next_minute() #for every customer determine their next state #remove churned customers from the supermarket lidl.remove_exitsting_customers() #generate new customers at their initial location #repeat from step 1
true
7c61f608b0278498c5bac3c8c2833d827754f124
lynnxlmiao/Coursera
/Python for Everybody/Using Database with Python/Assignments/Counting Organizations/emaildb.py
2,686
4.5
4
"""PROBLEM DESCRIPTION: COUNTING ORGANIZATIONS This application will read the mailbox data (mbox.txt) count up the number email messages per organization (i.e. domain name of the email address) using a database with the following schema to maintain the counts: CREATE TABLE Counts (org TEXT, count INTEGER) When you have run the program on mbox.txt upload the resulting database file above for grading. If you run the program multiple times in testing or with dfferent files, make sure to empty out the data before each run. You can use this code as a starting point for your application: http://www.pythonlearn.com/code/emaildb.py. The data file for this application is the same as in previous assignments: http://www.pythonlearn.com/code/mbox.txt. Because the sample code is using an UPDATE statement and committing the results to the database as each record is read in the loop, it might take as long as a Few minutes to process all the data. The commit insists on completely writing all the data to disk every time it is called. The program can be speeded up greatly by moving the commit operation outside of the loop. In any database program, there is a balance between the number of operations you execute between commits and the importance of not losing the results of operations that have not yet been committed. """ import sqlite3 conn = sqlite3.connect('emaildb.sqlite') cur = conn.cursor() #Deleting any possible table that may affect this assignment cur.execute('DROP TABLE IF EXISTS Counts') cur.execute(''' CREATE TABLE Counts (org TEXT, count INTEGER)''') fname = input('Enter file name: ') if ( len(fname) < 1 ) : fname = 'C:/Files/Workspaces/Coursera/Python for Everybody/Using Database with Python/Assignments/Counting Organizations/mbox.txt' fh = open(fname) for line in fh: if not line.startswith('From: '): continue pieces = line.split() email = pieces[1] (emailname, organization) = email.split("@") print (email) cur.execute('SELECT count FROM Counts WHERE org = ? ', (organization,)) row = cur.fetchone() if row is None: cur.execute('''INSERT INTO Counts (org, count) VALUES (?, 1)''', (organization,)) else: cur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?', (organization,)) # ommit the changes after for loop finished because this speeds up the # execution and, since our operations are not critical, a loss wouldn't suppose # any problem conn.commit() # # Getting the top 10 results and showing them sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10' for row in cur.execute(sqlstr): print(str(row[0]), row[1]) cur.close()
true
9415684dc35e4d73694ef14abe732a7ba32bf301
lenatester100/AlvinAileyDancers
/Helloworld.py
806
4.1875
4
print ("Hello_World") print ("I am sleepy") ''' Go to sleep print ("sleep") Test1=float(input("Please Input the score for Test 1...")) Test2=float(input("Please Input the score for Test 2...")) Test3=float(input("Please Input the score for Test 3...")) average=(Test1+Test2+Test3)/3 print ("The Average of all 3 tests is ", average) print (3+4) print(3-4) print(3*4) print(3/4) print(3%2) print(3**4) print(3//4) print (5.0/9.0) print (5.0/9) print (5/9.0) print (5/9) print (9.0/5.0) print (9.0/5) print (9/5.0) print (9/5) ''' temp = int (input ("what is the temperature? ")) def temperature (): if temp >= 90: print ("hot") elif temp <= 60: print ("chilly") else: print ("Take me to Hawaii") temperature()
true
b719b552170b8128a75a5121ac7578aa51a3e691
Krishan27/assignment
/Task1.py
1,466
4.375
4
# 1. Create three variables in a single a line and assign different # values to them and make sure their data types are different. Like one is # int, another one is float and the last one is a string. a=10 b=10.14 c="Krishan" print(type(a)) print(type(b)) print(type(c)) # 2. Create a variable of value type complex and swap it with # another variable whose value is an integer. d= 50 + 3j print(type(d)) b=d #here I swap the value of d with the b and then printed print(b) # 3 Swap two numbers using the third variable as the result name # and do the same task without using any third variable. a1=10 b1=5 result=a1 a1=b1 b1=result print(a1) # 4. Write a program to print the value given # by the user by using both Python 2.x and Python 3.x Version. user1=input("Type your name???") print(user1) age1=int(input("Type your age???")) print(age1) # 6. Write a program to check the data type of the entered values. # HINT: Printed output should say - The input value data type is: int/float/string/etc a=10 b=10.14 c="Krishan" d=True print(f"The input value data type is: {type(a)}") print(f"The input value data type is: {type(b)}") print(f"The input value data type is: {type(c)}") print(f"The input value data type is: {type(d)}") # 7. If one data type value is assigned to ‘a’ variable and then a different data # type value is assigned to ‘a’ again. Will it change the value. If Yes then Why? a=5 a=6 print(a)
true
953ed2c94e19a170fbe076f10339ff79ccda32f7
chaithanyabanu/python_prog
/holiday.py
460
4.21875
4
from datetime import date from datetime import datetime def holiday(day): if day%6==0 or day%5==0: print("hii this is weekend you can enjoy holiday") else: print("come to the office immediately") date_to_check_holiday=input("enter the date required to check") day=int(input("enter the day")) month=int(input("enter the month")) year=int(input("enter the year")) today=date(year,month,day) day_count=today.weekday() print(day_count) holiday(day_count)
true
91572a07bf2cbe5716b5328c0d4afc34c5f375f8
prince5609/Coding_Bat_problems
/make_bricks.py
1,151
4.5
4
""" QUESTION = 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. make_bricks(3, 1, 8) → True make_bricks(3, 1, 9) → False make_bricks(3, 2, 10) → True """ def make_bricks(small, big, goal): total_big_len = big * 5 if goal == total_big_len: return True elif goal == small: return True else: if total_big_len + small >= goal: big_req = int(goal / 5) if big_req <= big: big_length_used = big_req * 5 small_req = goal - big_length_used if small_req <= small: total_length = big_length_used + small_req if total_length == goal: return True else: return False else: return False else: return True else: return False print(make_bricks(3, 1, 8)) print(make_bricks(6, 0, 11))
true
022d1d89d419686f2ecf256f9e9a67aff141f13b
he44/Practice
/leetcode/35.py
822
4.125
4
""" 35. Search Insert Position Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. """ class Solution: def searchInsert(self, nums, target) -> int: size = len(nums) # no element / smaller than first element if size == 0 or target < nums[0]: return 0 for i in range(size): if target == nums[i]: return i if target < nums[i]: return i # larger than all elements return size def main(): s = Solution() nums = [1,3,5,6] targets = [5,2,7,0] for target in targets: output = s.searchInsert(nums, target) print(output) if __name__ == "__main__": main()
true
158ebdaca82112ce33600ba4f14c92b2c628a2b8
Anjalics0024/GitLearnfile
/ListQuestion/OopsConcept/OopsQ10.py
880
4.3125
4
#Method Overloading :1. Compile time polymorphisam 2.Same method name but different argument 3.No need of more than one class #method(a,b) #method(a,b,c) class student: def __init__(self,m1,m2): self.m1 = m1 self.m2 = m2 def add(self,a= None, b=None, c=None): s = a+b+c return s s1 = student(66,100) print(s1.add(2,9,10)) #Method Overriding 1.Example of compile time popymorphism 2.Atleast two class are requied 3.Same method and same argument class A: def fun1(self): print('feature_1 of class A') def fun2(self): print('feature_2 of class A') class B(A): # Modified function that is # already exist in class A def fun1(self): print('Modified feature_1 of class A by class B') def fun3(self): print('feature_3 of class B') # Create instance obj = B() # Call the override function obj.fun1()
true
0cc3fb7a602f1723486a9e3f4f4394e7b4b89f90
zhuxiuwei/LearnPythonTheHardWay
/ex33.py
572
4.3125
4
def addNum(max, step): i = 0 numbers = [] while(i < max): print "At the top i is %d" % i numbers.append(i) i += step print "Numbers now: ", numbers print "At the bottom i is %d" % i return numbers numbers = addNum(10, 2) print "The numbers: ", numbers for num in numbers: print num # below is add point item. numbers = [] print "######## Now use for-loop instead of while-loop##########" def addNum_for(max, step): numbers = [] for i in range(0, max, step): numbers.append(i) return numbers numbers = addNum_for(10, 2) print "The numbers: ", numbers
true
230f959d35d8e8f8e3d7fa98045d73896691f7dc
Pankaj-GoSu/Python-Data-Structure-Exercises
/450 Questions Of Data Structure/Qu3 Array.py
713
4.125
4
#====== Find the kth max and min elelment of an array ========= ''' Input --> N = 6 arr[] = 7 10 4 3 20 15 k = 3 output : 7 Explanation: 3rd smallest element in the given array is 7 ''' # kth smallest element list = [7,10,4,3,20,15] k = 3 asceding_list =[] def kth_min_element(list): i = list[0] if len(list) == 1: asceding_list.append(list[0]) else: for item in list: if item < i: i = item asceding_list.append(i) list.remove(i) kth_min_element(list) kth_min_element(list) print("kth minimum") print(asceding_list[k-1]) # kth max element desceding_list = asceding_list[::-1] print("kth maximum") print(desceding_list[k-1])
false
0249f8cb4fce6702f631c51de53449e0e80b5fde
sidhanshu2003/LetsUpgrade-Python-Batch7
/Python Batch 7 Day 3 Assignment 1.py
700
4.3125
4
# You all are pilots, you have to land a plane, the altitude required for landing a plane is 1000ft, #if less than that tell pilot to land the plane, or it is more than that but less than 5000 ft ask pilot to # come down to 1000ft else if it is more than 5000ft ask pilot to go around and try later! Altitude = input("Enter the number") Altitude = int(Altitude) if(Altitude>=1 and Altitude <=1000): print("Safe to land plane from Altitude: ",Altitude) elif(Altitude>1000 and Altitude<=5000): print("Altitude required for landing plane is 1000ft") elif(Altitude>5000): print("Turn Around and try later") else: print("Altitude value should be greater than zero")
true
1c5d80a5243fb8636f82ca76f0cb1945d25627ec
ash8454/python-review
/exception-handling-class20.py
1,414
4.375
4
###Exception handling """ The try block lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks. """ try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") #You can use else to print out other command a = 10 b = 1 try: c=a/b except: print("Something else went wrong") else: print("Nothing went wrong") #Finally - The finally block, if specified, will be executed regardless if # the try block raises an error or not. try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished") #try to open and write to a file that is not writable # try: # f = open('demofile.txt') # f.write("Lorum Ipsum") # except: # print("Something went wrong when writing to the file") # finally: # f.close() #Raise an exception """ As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword. """ x = -1 if x < 0: raise Exception("Sorry, no numbers below 0") #raise type error x = "hello" if not type(x) is int: raise TypeError("Only integers is allowed") x="ashok" if not type(x) is str: raise TypeError("Only string is allowed") else: print("No error")
true
7e8cf8455bbc07fbe9e46c10a6f26dd188d599bc
ash8454/python-review
/if-else-class8.py
1,168
4.1875
4
#if else a = 3 b = 200 if b > a: print('b is greater than a') #if-elif-else a = 36 b = 33 if b > a: print('b is greater than a') elif b == a: print('b and a are equal') else: print('a is greater than b') #short hand if else c = 30 d = 21 if c > d: print('a is greater than b') #short hand if elif e = 31 f = 25 print("e is greater than f") if e > f else print("f is greater than e") #three conditions a = 330 b = 330 print('A') if a > b else print("=") if a == b else print('B') #grade grade = 3.3 if grade >= 3.5 and grade <=4.0: print("A grade") elif grade >= 3.0 and grade < 3.5: print("B grade") elif grade >= 2.5 and grade < 3.0: print("C grade") elif grade >= 2.0 and grade < 2.5: print('D grade') else: print("Failed") #or condition amount=500000 age = 70 if age >= 70 or amount >=1000000: print("you can retire now") else: print("You still need to save some money") #nested if x = 15 if x > 10: print("Above ten") if x > 20: print("Above 20") else: print("Not above 20") #printing no content a = 33 b = 200 if b > a: pass #does not print anything or throws error
false
0f26b50662decd207ceaf2ce4367b138a9644ee7
saad-ahmed/Udacity-CS-101--Building-a-Search-Engine
/hw_2_6-find_last.py
617
4.3125
4
# Define a procedure, find_last, that takes as input # two strings, a search string and a target string, # and outputs the last position in the search string # where the target string appears, or -1 if there # are no occurences. # # Example: find_last('aaaa', 'a') returns 3 # Make sure your procedure has a return statement. def find_last(search,find): index = -1 while True: i = search.find(find,index+1) if i == -1: break index = i return index print find_last('aaaa', 'a') print find_last('aaaa', 'b') print find_last('', '') print find_last('', 'b')
true
cdb7b7ba096285c5c6e732820544bd43c2e36a2b
varunkamboj11/python_project
/wheel.py
1,255
4.125
4
#create the account #print("1>:signup") #print("2>:create the acoount") a=int(input("1>: Create the account \n 2>: Signup ")) if(a==1): b=input("Firstname: ") print("Avoid using coomon words and include a mix of letters and numbers ") c=input("Lastname: ") print("PASSWORD MUST CONTAIN 1 NUMERIC 1 CHARACTER MINIMUM LENGTH 6") v=str(input("E-mail")) r=input("Password: ") n=input("Re-Enter Password:") if(r!=n): print("PASSWORD INCORRECT") x=len(r) q=len(n) if(x and q >= 6): print("check your password") d=input('Location: ') e=input("Enter gender type: ") g=input("Enter country name: ") print("MM/DD/YYYY") h=str(input("Brithday")) f=input("submit") if(f=="submit"): print("YOU HAVE SUCEESSFULLY CREATED AN ACCOUNT ,\n,WELCOME TO dRINK ON wHEEL") f=open("test.txt",'w',encoding='utf-8') f.write('\n'+v) f.write('\n'+r) f.close() if(a==2): #database="test.txt" p=input("Enter your e-mail") j=input("enter your password") f = open("test.txt", 'r', encoding='utf-8') database=f.read() if(p and j in database): print("YOU ARE SUCCESSFULLY LOGIN ") else: print("TRY AGAIN")
false
d7a51f2eabba8da6c74a184e518dacf683a0651a
Gioia31/tuttainfo
/es25p293.py
1,684
4.1875
4
''' Crea la classe Triangolo, la classe derivata TriangoloIsoscele e, da quest'ultima, la classe derivata TriangoloEquilatero. ''' class Triangolo(): def __init__(self, lato1, lato2, lato3): self.lato1 = lato1 self.lato2 = lato2 self.lato3 = lato3 def info_scaleno(self): print("Il triangolo è scaleno ") print("Il perimetro del triangolo è ", self.lato1 + self.lato2 + self.lato3) class TriangoloIsocele(Triangolo): def __init__(self, lato1, lato2, lato3): super().__init__(lato1, lato2, lato3) def info_isoscele(self): print("Il triangolo è isoscele") print("Il perimetro del triangolo è", self.lato1+ self.lato2 + self.lato3) class TriangoloEquilatero(TriangoloIsocele): def __init__(self, lato1, lato2, lato3): super().__init__(lato1, lato2, lato3) def info_equilatero(self): print("Il triangolo è equilatero") print("Il perimetro del triangolo è", self.lato1 * 3) def main(): lato1 = int(input("Inserisci la misura del primo lato: ")) lato2 = int(input("Inserisci la misura del secondo lato: ")) lato3 = int(input("Inserisci la misura del terzo lato: ")) if lato1 != lato2 and lato1 != lato3 and lato2 != lato3: triangolo1 = Triangolo(lato1, lato2, lato3) triangolo1.info_scaleno() elif lato1 == lato2 and lato1 == lato3 and lato2 == lato3: triangolo1 = TriangoloEquilatero(lato1, lato2, lato3) triangolo1.info_equilatero() else: triangolo1 = TriangoloIsocele(lato1, lato2, lato3) triangolo1.info_isoscele() main()
false
98cfbcf9b135a4851035453a1182acfbb389545f
samicd/coding-challenges
/duplicate_encode.py
738
4.1875
4
""" The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate. Examples "din" => "(((" "recede" => "()()()" "Success" => ")())())" "(( @" => "))((" """ def duplicate_encode(word): # converting to lower case l = word.lower() # finding the set of chars with duplicates dupes = set([x for x in l if l.count(x) >1]) # returning ')' if char is a member of dupes and '(' else return ''.join([')' if s in dupes else '(' for s in l ])
true
f52079869f41ba7c7ac004521b99586c6b235dad
Ritella/ProjectEuler
/Euler030.py
955
4.125
4
# Surprisingly there are only three numbers that can be # written as the sum of fourth powers of their digits: # 1634 = 1^4 + 6^4 + 3^4 + 4^4 # 8208 = 8^4 + 2^4 + 0^4 + 8^4 # 9474 = 9^4 + 4^4 + 7^4 + 4^4 # As 1 = 1^4 is not a sum it is not included. # The sum of these numbers is 1634 + 8208 + 9474 = 19316. # Find the sum of all the numbers that can be written as the # sum of fifth powers of their digits. # SOLUTION: if n is the number of digits, the maximum 5th power sum # that can be written is n * 9^5 # Therefore, find n such that (n) * (9^5) < 10^n - 1 # n can't be more than 6 max_num = 10**6 power_summands = [] for i in range(1, max_num): str_i = str(i) sum_d = 0 for d in str_i: sum_d += int(d)**5 if sum_d == i and len(str_i) != 1: power_summands.append(i) print(sum(power_summands)) # NOTE: cannot name a variable 'sum' or python gets confused since the # sum object takes precedence over the sum function
true
83571a887f9f89107aa9d621c0c2ebcac139fd2e
Ritella/ProjectEuler
/Euler019.py
1,836
4.15625
4
# You are given the following information, # but you may prefer to do some research for yourself. # 1 Jan 1900 was a Monday. # Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on leap years, twenty-nine. # A leap year occurs on any year evenly divisible by 4, # but not on a century unless it is divisible by 400. # How many Sundays fell on the first of the month # during the twentieth century (1 Jan 1901 to 31 Dec 2000)? reg_year_days_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] leap_year_days_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # your starting dating is 1 Jan 1900 so begin with that and remove after month_lengths = [] for year in range(1900, 2001, 1): if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): days_month = leap_year_days_month else: days_month = reg_year_days_month month_lengths.extend(days_month) dates = [] for month_length in month_lengths: dates.extend([i for i in range(1, month_length + 1)]) # 1900 is not a leap year so to start with 1901, we need start_idx = sum(reg_year_days_month) sundays_with_1 = [1 for i in range(start_idx, len(dates)) \ if (i + 1) % 7 == 0 and dates[i] == 1] print(sum(sundays_with_1)) # NOTE: pay attention to month_lengths.extend(days_month) method for # adding a list to a list # could also have done calendar_dates += days_month # importantly, can't use append neatly # PAY ATTENTION to dates.extend. # ALSO, extremely important. You cannot just add a range as a list # Python returns a range, so you need to recast as a list using # list() or item by item list comprehension # also, look at how i wrote sundays_with_1 and avoided almost making an # indexing mistake
true
146af7c28e0698203d3a45ff3e9494f44d17f13f
Unclerojelio/python_playground
/drawcircle.py
479
4.1875
4
""" drawcircle.py A python program that draws a circle From the book, "Python Playground" Author: Mahesh Venkitachalam Website: electronut.in Modified by: Roger Banks (roger_banks@mac.com) """ import math import turtle # draw the circle using turtle def drawCircleTurtle(x, y, r): turtle.up() turtle.setpos(x + r, y) turtle.down() # draw the circle for i in range(0, 365, 5): a = math.radians(i) turtle.setpos(x + r*math.cos(a),y + r*math.sin(a)) drawCircleTurtle(100, 100, 50) turtle.mainloop()
false
b284b148982d4c0607e0e0c15ac07641aea81011
ho-kyle/python_portfolio
/081.py
229
4.21875
4
def hypotenuse(): a, b = eval(input('Please enter the lengths of the two shorter sides \ of a right triangle: ')) square_c = a**2 + b**2 c = square_c**0.5 print(f'The length of hypotenuse: {c}') hypotenuse()
true
9aa293a22aa5a13515746f2b669bf095b21cb84e
sreekanthramisetty/Python
/Scope.py
1,198
4.25
4
# s = 10 # def f(): # print(s) # # print(s) # f() # print(s) # # # # # # # # # # # # # # # # # # # # # # s = 20 # def f(): # s = 30 # print(s) # print(s) # f() # print(s) # # # # # # # # # # # # # # # # # # # # # # We cannot print global variable directly inside the functions if we are assigning a value after the print ,without declaring again like above. # s = 20 # def f(): # print(s) # s = 30 #Due to this we caanot # print(s) # # print(s) # f() # print(s) # # s = 20 # def f(): # global s # print("Inside Function Global",s) # s = 30 # s = s + 10 # print("Last",s) # # print("Out Of Function Global",s) # f() # print("Final",s) # # # def add(): # x = 15 # # def change(): # global x # x = 20 # print("Function: ", x) # print("Before making change: ", x) # print("Making change") # change() # print("After making change: ", x) # add() # print("Value of x", x) # a = 10 # print(id(a)) # def f(): # a = 9 # x = globals()['a'] # print(id(x)) # print(a) # globals() ['a'] = 15 # f() # print(id(a)) # print(a) # # a = 10 # def f(): # print(a) # s = a + 10 # print(s) # f()
false
817a57ad576fcc602e6de0a8daa1a0811f5a6657
chilperic/Python-session-coding
/mutiple.py
868
4.28125
4
#!/usr/bin/env python #This function is using for find the common multiple of two numbers within a certain range def multiple(x,y,m,t): #x is the lower bound the range and y higher bound from sys import argv x, y, m, t= input("Enter the the lower bound of your range: "), input("Enter the the higher bound of your range: "), input("enter the first number: "), input("enter the second number: ") x, y, m, t= int(x), int(y), int(m), int(t) a=[] if x>y: print str(x)+ " should be greater or equal to " +str(y) exit() if y<m and y<t: print "The range is too small. Enter a number bigger than "+ str(m) + " or " + str(t) exit() for i in range (x,y): if (i % m)==0 and (i % t)==0: #m and t are the number that we are looking for their multiple a.append(i) print a return sum(a) print multiple(x,y,m,t) multiple(0,1000000,5,12)
true
228e5e3c7ca9ae56d0b6e0874f592c58cbaadc24
TeknikhogskolanGothenburg/PGBPYH21_Programmering
/sep9/textadventure/game.py
2,467
4.3125
4
from map import the_map from terminal_color import color_print def go(row, col, direction): if direction in the_map[row][col]['exits']: if direction == "north": row -= 1 elif direction == "south": row += 1 elif direction == "east": col += 1 elif direction == "west": col -= 1 else: print("You can't go in that direction.") return row, col def get(row, col, item, inventory): # Check if the selected item is in the room if item in the_map[row][col]['items']: color_print("yellow", f"You pick up the {item}") the_map[row][col]['items'].remove(item) inventory.append(item) else: color_print("red", f"There is no {item} in this room") def drop(row, col, item, inventory): # Check if the selected item is in the inventory if item in inventory: color_print("yellow", f"You drop the {item} to the floor") inventory.remove(item) the_map[row][col]["items"].append(item) else: color_print("red", f"There is no {item} in your inventory") def show_inventory(inventory): if len(inventory) == 0: color_print("red", "Your inventory is empty") else: print("You have the following in your inventory:") for item in inventory: color_print("magenta", f"* {item}") def main(): row = 1 col = 0 inventory = [] running = True while running: print("You are now in", the_map[row][col]['description']) color_print("blue", f"There are exits to the {the_map[row][col]['exits']}") if len(the_map[row][col]['items']) > 0: print("Items in the room:", the_map[row][col]['items']) command = input("> ") command_parts = command.split() main_command = command_parts[0].lower() if main_command == "go": row, col = go(row, col, command_parts[1].lower()) elif main_command == "get": get(row, col, command_parts[1].lower(), inventory) elif main_command == "drop": drop(row, col, command_parts[1].lower(), inventory) elif main_command == "inventory": show_inventory(inventory) elif main_command == "quit": running = False else: print("I don't understand", command_parts[0]) print("Thanks for playing the game.") if __name__ == '__main__': main()
true
db64c4552a3eef0658031283a760edc8cf20b3c0
mprzybylak/python2-minefield
/python/getting-started/functions.py
1,568
4.65625
5
# simple no arg function def simple_function(): print 'Hello, function!' simple_function() # simple function with argument def fib(n): a, b = 0, 1 while a < n: print a, a, b = b, a+b fib(10) print '' # example of using documentation string (so-called docstring) def other_function(): """Simple gibbrish print statement""" print 'Hello' other_function() print other_function.__doc__ # functions can be assigned to variables f = simple_function f() # return values with return statement def fib_ret(n): result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result print fib_ret(20) # default values in function def default_args_fun(a=1, b=2): print a, b default_args_fun() default_args_fun(10) default_args_fun(100, 1000) # keyword argument notation # keyword arguments goes after positional arguments default_args_fun(b=1000) # *[name] argument contains positional arguments def positional_arguments(a=1,b=2, *arguments): print str(arguments) positional_arguments(1,2) positional_arguments(1,2,3,4) # **[name] argument contains keyword arguments def keyword_arguments(a,b, **arguments): print str(arguments) keyword_arguments(10,20) keyword_arguments(10,20, aa=1, bb=2) # unpacking argument # When function requires e.g. three arguments, and we have it all in one list (list with 3 elements), we can use "unapck" synatx def unpack_function(a,b): print a,b args = [1,2] unpack_function(*args) # We can unpack key arguments from map as a keyword arguments args_map = {"a":1, "b":2} unpack_function(**args_map)
true
336522ccc3314a8dc4e7e3d0b361a2538152ed46
mprzybylak/python2-minefield
/python/getting-started/for.py
1,128
4.40625
4
# Regular for notation acts as an interator words = ['first', 'second', 'third'] print 'Regular loop over list: ' + str(words) for w in words: print w # If we want to modify list inside for - it is best to create copy of list list_to_modify = ['1', '22', '333'] print 'example of modifiaction list in loop: ' + str(list_to_modify) for m in list_to_modify: print m for m in list_to_modify[:]: if len(m) > 1: list_to_modify.insert(0, m) print 'modified list: ' + str(list_to_modify) for m in list_to_modify: print m # We can simulate java-like for with range fuction print 'range(10) = ' + str(range(10)) print 'range(5,10) = ' + str(range(5,10)) print 'range(0,10,2) = ' + str(range(0,10,2)) print 'for v in range(10)' for v in range(10): print v print 'for v in range(5,10)' for v in range(5,10): print v print 'for v in range(0,10,2)' for v in range(0,10,2): print v # iterate over array with intexes idiom some_list = ['first', 'second', 'third'] print 'interate over array with indexes. List = ' + str(some_list) print 'for i in range(len(some_list)):' for i in range(len(some_list)): print i, some_list[i]
false
457c259a8515b806833cf54ccd0c79f8069f874c
surenderpal/Durga
/Regular Expression/quantifiers.py
481
4.125
4
import re matcher=re.finditer('a$','abaabaaab') for m in matcher: print(m.start(),'...',m.group()) # Quantifiers # The number of occurrences # a--> exactly one 'a' # a+-> atleast one 'a' # a*-> any number of a's including zero number also # a?-> atmost one a # either one a or zero number of a's # a{num}-> Exactly n number of a's # ^a -> it will check whether the given string starts with a or not # a$ -> it will check whether the given string ends with a or not #
true
2c53a0967ba066ca381cc67d277a4ddcd9b3c4e7
adreena/DataStructures
/Arrays/MaximumSubarray.py
358
4.125
4
''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. ''' def maxSubarray(nums): max_sum = float('-inf') current_sum = nums[0] for num in nums[1:]: current_sum = max(current_sum+num, num) max_sum = max(max_sum, current_sum) return max_sum
true
cf2b6794d3d6dbe17d5ee7d88cabecae3b9894d2
xuyuntao/python-code
/2/def.py
1,049
4.125
4
print("来学习函数吧") def MySun(*args): sum = 0 for i in args: sum += i return sum print(MySun(1,2,3,4,5,6)) def func(**args): print(args) print(type(args)) func(x=1, y=2, z=3) """ lambada的主体是有一个表达式,而不是代码块,仅仅只能在lambda中 封装简单逻辑 lambada的函数有自己的命名空间 """ sum = lambda num1, num2: num1 + num2 print(sum(1,2)) # 打印99乘法表 def Print9x9(): str = " " for i in range(1,10): for j in range(1,i+1): print("%d x %d = %d " % (j, i, j * i)) Print9x9() def func(): print('good good study ,day day up') def outer(func): def inner(): print('**************************') func() return inner() f = outer(func) # 作用域 局部作用域、全局作用域、内建作用域 try: #print(num) #print(3 / 0) print(3/1) except ZeroDivisionError as e: print("除数为0") except NameError as e: print("没有定义该变量") else: print("代码没问题")
false
f5b7673a8c092aa49bec8f2d464f01acb67c6d80
xuyuntao/python-code
/2/turtle_test.py
496
4.125
4
""" 一个简单绘图工具 提供一个小海龟,可以把它理解为一个机器人,只能听懂有限的命令 其他命令 done()保持程序不结束 """ import turtle turtle.speed(10) turtle.forward(100) turtle.right(45) turtle.forward(100) turtle.left(45) turtle.forward(100) turtle.goto(0,0) turtle.up() turtle.goto(-100,100) turtle.down() turtle.pensize(5) turtle.pencolor("red") turtle.goto(100,-100) while 1: turtle.right(45) turtle.circle(50) turtle.done()
false
855817e03fa062cb755c166042bdb16037aefe5c
IEEE-WIE-VIT/Awesome-DSA
/python/Algorithms/quicksort.py
898
4.28125
4
# Function that swaps places for to indexes (x, y) of the given array (arr) def swap(arr, x, y): tmp = arr[x] arr[x] = arr[y] arr[y] = tmp return arr def partition(arr, first, last): pivot = arr[last] index = first i = first while i < last: if arr[i] <= pivot: # Swap if current element is smaller to the pivot arr = swap(arr, i, index) index += 1 i += 1 arr = swap(arr, index, last) return index def quickSort(arr, first, last): if first < last: pivot = partition(arr, first, last) # Implement quicksort on both sides of pivot quickSort(arr, first, pivot-1) quickSort(arr, pivot+1, last) return arr # Test array array = [1, 10, 2, 4, 1, 9, 6, 7, 10, 4, 11, 3] print("Unsorted test array: ", array) quickSort(array, 0, len(array)-1) print("Sorted test array: ", array)
true
5d81d3e6f16f4fc1d5c9fcc5ed452becefa95935
IEEE-WIE-VIT/Awesome-DSA
/python/Algorithms/Queue/reverse_k_queue.py
1,231
4.46875
4
# Python3 program to reverse first k # elements of a queue. from queue import Queue # Function to reverse the first K # elements of the Queue def reverseQueueFirstKElements(k, Queue): if (Queue.empty() == True or k > Queue.qsize()): return if (k <= 0): return Stack = [] # put the first K elements # into a Stack for _ in range(k): Stack.append(Queue.queue[0]) Queue.get() # Enqueue the contents of stack # at the back of the queue while (len(Stack) != 0): Queue.put(Stack[-1]) Stack.pop() # Remove the remaining elements and # enqueue them at the end of the Queue for _ in range(Queue.qsize() - k): Queue.put(Queue.queue[0]) Queue.get() # Utility Function to print the Queue def Print(Queue): while (not Queue.empty()): print(Queue.queue[0], end=" ") Queue.get() # Driver code if __name__ == '__main__': Queue = Queue() Queue.put(10) Queue.put(20) Queue.put(30) Queue.put(40) Queue.put(50) Queue.put(60) Queue.put(70) Queue.put(80) Queue.put(90) Queue.put(100) k = 5 reverseQueueFirstKElements(k, Queue) Print(Queue)
true
43012784b596503267cd6db2beb45bd19a7d1b0a
cuongnguyen139/Course-Python
/Exercise 3.3: Complete if-structure
262
4.1875
4
num=input("Select a number (1-3):") if num=="1": num="one." print("You selected",num) elif num=="2": num="two." print("You selected",num) elif num=="3": num="three." print("You selected",num) else: print("You selected wrong number.")
true
297071abe7a2bbfdb797a7cc84cc1aeac99f4850
RickyCode/CursoProgramacionBasico
/Codigos Clase 4/04_cuadrado.py
309
4.15625
4
# Se le pide un número al usuario: numero = int(input('>>> Ingresa un número: ')) # La función int() transformará el texto a número. # Se calcula el cuadrado del número: cuadrado_num = numero ** 2 # Se muestra en la pantalla el resultado: print('El cuadrado del número es: ', cuadrado_num)
false
d99103049b500922d6d7bab8268503ad8190067c
osudduth/Assignments
/assignment1/assignment1.py
1,987
4.1875
4
#!/usr/bin/env python3 #startswith,uppercase,endswith, reverse, ccat # # this will tell you the length of the given string # def length(word): z = 0 for l in word: z = z + 1 return z # # returns true if word begins with beginning otherwise false # def startsWith(word, beginning): for x in range(0, length(beginning) ): if beginning[x] != word[x]: return False return True # # This will return true if a string contains another smaller string and false if it doesnt # def contains(word, subWord): if length(word) < length (subWord): return False for y in range (0, length(word)): w = word[y:] if startsWith (w, subWord): return True return False # #In this function you will give it a string and it will reverse the order of the letters in the string # def mirror(word): x = length(word) - 1 mirrorWord = [None] * length(word) for l in word: mirrorWord[x] = l x = x - 1 return ''.join(mirrorWord) # #This function will take in a word and then a subword and it will see if the word ends with the subword # def endsWith(word, subword): mirror(word) mirror(subword) if startsWith(mirror(word), mirror(subword)): return True else: return False if contains("wordword", "poop"): print("failed") else: print("passed") if contains("wordword", "rdw"): print ("passed") else: print("failed") if startsWith("oliver", "oliv"): print("passed") else: print("failed") if contains ("oli", "oliver"): print ("failed") else: print ("passed") if (contains("zza", "azza")): print("failed") else: print("passed") if "eyb" == mirror("bye"): print("passed") else: print("failed") if endsWith ("birthday", "day"): print ("passed") else: print ("failed") if endsWith ("birthday", "dag"): print ("passed") else: print ("failed")
true
d0524ae575c3cf1697039a0f783618e247a96d18
TeresaChou/LearningCpp
/A Hsin/donuts.py
222
4.25
4
# this program shows how while loop can be used number = 0 total = 5 while number < total: number += 1 donut = 'donuts' if number > 1 else 'donut' print('I ate', number, donut) print('There are no more donuts')
true
0d7273d3c8f1599fa823e3552d5dfe677f2eb37b
AdarshMarakwar/Programs-in-Python
/Birthday Database.py
1,456
4.15625
4
import sys import re birthday = {'John':'Apr 6','Robert':'Jan 2','Wayne':'Oct 10'} print('Enter the name:') name=input() if name in birthday.keys(): print('Birthday of '+name+' is on '+birthday[name]) else: print('The name is not in database.') print('Do you want to see the entire databse?') reply=input() if reply=='yes': for names,bdate in birthday.items(): print('Birthday of '+names+' is on '+bdate) print('Would you like to include '+name+' in database?') answer=input() if answer=='yes': print('Enter the birthdate of '+name) birthdate=input() # matching birthdate pattern birthdayRegex=re.compile(r'\w+\s\d\d') while birthdayRegex.search(birthdate) is None or birthdate[0].islower(): print('The pattern of birthdate is : \w+\s\d\d. \nFor example Oct 06 is a valid pattern.') print('Please enter the correct pattern birthdate of '+name+' .') birthdate=input() birthday[name]=birthdate else: birthday[name]=birthdate print('Enter the correct name:') name=input() while name in birthday.keys(): print('Birthday of '+name+' is on '+birthday[name]) sys.exit() while name not in birthday.keys(): print('Name '+name+' not in database.') sys.exit()
true
f6f745b08e14bb8d912565e1efecf3bbf9a437a1
mnk343/Automate-the-Boring-Stuff-with-Python
/partI/ch3/collatz.py
321
4.1875
4
import sys def collatz(number): if number%2 : print(3*number+1) return 3*number+1 else: print(number//2) return number//2 number = input() try : number = int(number) except ValueError: print("Please enter integer numbers!!") sys.exit() while True: number = collatz(number) if number == 1: break
true
34ce2cbc18f6a937592da46d748ce032e709cfa4
Rusvi/pippytest
/testReact/BasicsModule/dictionaries.py
867
4.125
4
#Dictionaries (keys and values) # simple dictionary student = { "name": "Mark", "student_id": 15163, "feedback": None } #Get values print(student["name"])# = Mark #print(student["last_name"]) KeyError if there is no key #avoid by get("key","default value") print(student.get("last_name","Unknown_key"))# = Unknown_key #get keys print(student.keys())# returns list of keys #get values print(student.values())# returns list of values #Change value student["name"] = "James" print(student) #deleting keys del student["name"] print(student) #List of dictionaries all_students = [ {"name": "Mark", "student_id": 15163,"feedback": None}, {"name": "Katarina", "student_id": 63112,"feedback": None}, {"name": "Jessica", "student_id": 30021,"feedback": None} ] for s in all_students:#itterate through dictionary list print(s)# print(s["name"])
true
0eb8624cbe3c84cfbeeb7c3494e271fb00bfb726
SchoBlockchain/ud_isdc_nd113
/6. Navigating Data Structures/Temp/geeksforgeeks/geeksforgeeks_BFS_udacity.py
1,679
4.3125
4
# Program to print BFS traversal from a given source # vertex. BFS(int s) traverses vertices reachable # from s. from collections import defaultdict # This class represents a directed graph using adjacency # list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited # visited = [False]*(len(self.graph)) visited = defaultdict(bool) #because node could be of any label, not just integer # Create a frontier for BFS frontier = [] # Mark the source node as visited and enfrontier it frontier.append(s) visited[s] = True # if frontier is empty, quit while frontier: # Defrontier a vertex from frontier and print it s = frontier.pop(0) print(s) # Get all adjacent vertices of the defrontierd # vertex s. If a adjacent has not been visited, # then mark it visited and enfrontier it for i in self.graph[s]: if visited[i] == False: frontier.append(i) visited[i] = True # Driver code # Create a graph given in the above diagram g = Graph() g.addEdge('A', 'B') g.addEdge('A', 'C') g.addEdge('B', 'C') g.addEdge('C', 'A') g.addEdge('C', 'D') g.addEdge('D', 'D') print("Following is Breadth First Traversal (starting from vertex 2)") g.BFS('C')
true
4599cd49493f9376018cee225a14f139fd9c316f
m-tambo/code-wars-kata
/python-kata/counting_duplicate_characters.py
1,112
4.21875
4
# https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/python # Write a function that will return the count of distinct # case-insensitive alphabetic characters and numeric digits # that occur more than once in the input string. # The input string can be assumed to contain only # alphabets (both uppercase and lowercase) and numeric digits. def duplicate_count(text): characters = list(text.upper()) char_set = set() duplicate_set = set() count = 0 for char in characters: x = char.upper() if not x in char_set: char_set.add(x) elif not x in duplicate_set: count += 1 duplicate_set.add(x) return count if __name__ == '__main__': print(str(duplicate_count("abcde")) + " should equal 0") print(str(duplicate_count("abcdea")) + " should equal 1") print(str(duplicate_count("indivisibility")) + " should equal 1") print(str(duplicate_count("Indivisibilities")) + " should equal 2") print(str(duplicate_count("aA11")) + " should equal 2") print(str(duplicate_count("ABBA")) + " should equal 2")
true
39dd901b68ac263934d07e52ace777357d37edbc
ProgrammingForDiscreteMath/20170828-karthikkgithub
/code.py
2,881
4.28125
4
from math import sqrt, atan, log class ComplexNumber: """ The class of complex numbers. """ def __init__(self, real_part, imaginary_part): """ Initialize ``self`` with real and imaginary part. """ self.real = real_part self.imaginary = imaginary_part def __repr__(self): """ Return the string representation of self. """ return "%s + %s i"%(self.real, self.imaginary) def __eq__(self, other): """ Test if ``self`` equals ``other``. Two complex numbers are equal if their real parts are equal and their imaginary parts are equal. """ return self.real == other.real and self.imaginary == other.imaginary def modulus(self): """ Return the modulus of self. The modulus (or absolute value) of a complex number is the square root of the sum of squares of its real and imaginary parts. """ return sqrt(self.real**2 + self.imaginary**2) def sum(self, other): """ Return the sum of ``self`` and ``other``. """ return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary) def product(self, other): """ Return the product of ''self'' and ''other''. """ return ComplexNumber(self.real*other.real - self.imaginary*other.real, self.real*other.imaginary - self.imaginary*imaginary.real) def complex_conjugate(self): """ Return the complex conjugate of self. The complex conjugate of a complex number is the same real part and opposite sign of its imaginary part. """ self.imaginary = -self.imaginary class NonZeroComplexNumber(ComplexNumber): def __init__(self, real_part, imaginary_part): """ Initialize ``self`` with real and imaginary parts after checking validity. """ if real_part == 0 and imaginary_part == 0: raise ValueError("Real or imaginary part should be nonzero.") return ComplexNumber.__init__(self, real_part, imaginary_part) def inverse(self): """ Return the multiplicative inverse of ``self``. """ den = self.real**2 + self.imaginary**2 return NonZeroComplexNumber(self.real/den, -self.imaginary/den) def polar_coordinates(self): """ Return the polar co-ordinates of ''self''. The polar coordinates is (r, theta), in which r = sqrt(x**2 + y**2) and theta = atan(y/x) """ return sqrt(self.real**2 + self.imaginary**2), atan(self.imaginary/self.real) def logarithm(self): """ Return the logarithm of ''self'' The logarithm is log(r) + theta i """ return log(self.polar_coordinates()[0]) + self.polar_coordinates()[1]
true
aef037a891c81af4f75ce89a534c7953f5da6f57
christian-million/practice-python
/13_fibonacci.py
653
4.1875
4
# 13 Fibonacci # Author: Christian Million # Started: 2020-08-18 # Completed: 2020-08-18 # Last Modified: 2020-08-18 # # Prompt: https://www.practicepython.org/exercise/2014/04/30/13-fibonacci.html # # Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. # Make sure to ask the user to enter the number of numbers in the sequence to generate. # (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence # is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
true
88157f9c38fd2952634c6a17f987d0d1a5149965
git-uzzal/python-learning
/genPrimeNumbers.py
579
4.21875
4
def isPrime(n): for num in range(2,n): if n % num == 0: return False return True def get_valid_input(): ''' Get valid integer more than equal to 3''' while(True): try: num = int(input('Enter a number: ')) except: print("I dont undersand that") continue else: if num < 3: print("Number must be more than 2") continue else: break return num print('This program generates all the less than a given number') n = get_valid_input() print('List of prime number less than', n, 'are:') for num in range(2,n): if isPrime(num): print(num)
true
e5d7cde3aa799b147de8bb6a5ff62b308cac45d5
ruchit1131/Python_Programs
/learn python/truncate_file.py
896
4.1875
4
from sys import argv script,filename=argv print(f"We are going to erase {filename}") print("If you dont want that hit Ctrl-C") print("If you want that hit ENTER") input("?") print("Opening file") target=open(filename,'w') print("Truncating the file.") target.truncate()#empties the file print("Write 3 lines") line1=input("line 1:") line2=input("line2 :") line3=input("line3 :") target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") #target.write(f"{line1}{line2}{line3}") can also be used print("Andfinally we close it") #print(target.read()) error: io.UnsupportedOperation: not readable target.close() #now to read the file target=open(filename) print(target.read()) # modes #w for writing r for reading and a for append a+ for reading and writing #open() opens in read mode default
true
d636b023af3f4e570bef64a37a4dbb5a162bd6db
chavarera/codewars
/katas/Stop gninnipS My sdroW.py
1,031
4.34375
4
''' Stop gninnipS My sdroW! Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test" other Answers:https://www.codewars.com/kata/5264d2b162488dc400000001/solutions/python ''' #By Ravishankar chavare( Github: @chavarera) def spin_words(sentence): return " ".join([text[::-1] if len(text)>4 else text for text in sentence.split(" ")]) result=spin_words("Weme ddgggg trere") print(result) ''' spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" ) => returns "This is rehtona test" '''
true
1b081dfc115a840dde956934dbab0ee5f3b41891
harshaghub/PYTHON
/exercise.py
457
4.15625
4
"""Create a list to hold the to-do tasks""" to_do_list=[] finished=False while not finished: task = input('enter a task for your to-do list. Press <enter> when done: ') if len(task) == 0: finished=True else: to_do_list.append(task) print('Task added') """Display to-do list""" print() print('your to-do list: ') print('-' * 16) for task in to_do_list: print(task)
true
4fa45f63c6bbadc3ab8c3490058f3ac239648957
NikhilDusane222/Python
/DataStructurePrograms/palindromeChecker.py
965
4.1875
4
#Palindrome checker #class Dequeue class Deque: def __init__(self): self.items = [] def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0, item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) def is_empty(self): return self.items == [] def size(self): return len(self.items) def pal_check(string): # Palindrome checker using Deque pal_dq = Deque() for character in string: pal_dq.add_front(character) match = True while (pal_dq.size() > 1 and match): front = pal_dq.remove_front() rear = pal_dq.remove_rear() if front != rear: match = False return match string=input("Enter string to check palindrome: ") if (pal_check(string)): print(string, "is Palindrome ") else: print(string, "is not Palindrome ")
false
f4bd846af010b1782d0e00da64f0fdf4314e93ba
mikikop/DI_Bootcamp
/Week_4/day_3/daily/codedaily.py
700
4.1875
4
choice = input('Do you want to encrypt (e) or decrypt (d)? ') cypher_text = '' decypher_text = '' if choice == 'e' or choice == 'E': e_message = input('Enter a message you want to encrypt: ') #encrypt with a shift right of 3 for letter in e_message: if ord(letter) == 32: cypher_text += chr(ord(letter)) else: cypher_text += chr(ord(letter)+3-26) print(cypher_text) elif choice == 'd' or choice == 'D': d_message = input('Enter a message you want to decrypt: ') #decrypt for letter in d_message: if ord(letter) == 32: decypher_text += chr(ord(letter)) else: decypher_text += chr(ord(letter)-3+26) print(decypher_text) else: print("Sorry that's not an option. Retry!")
true
25e86fc49773801757274ede8969c27c68168747
mikikop/DI_Bootcamp
/Week_4/day_5/exercises/Class/codeclass.py
1,542
4.25
4
# 1 Create a function that has 2 parameters: # Your age, and your friends age. # Return the older age def oldest_age(my_age,friend_age): if my_age > friend_age: return my_age return friend_age print(oldest_age(34,23)) # 2. Create a function that takes 2 words # It must return the lenght of the longer word def longest_word(word1, word2): if len(word1) > len(word2): return word1 else: return word2 print(longest_word('toto', 'longest word')) # 3. Write the max() function yourself... def max(my_list): for i in range(0,len(my_list)-1): for j in range(0,len(my_list)-1): if my_list[i] >= my_list[j]: big = my_list[i] else: big = my_list[j] return big print(max([1,5,43,2,7])) print(max([1,5,43,2,7,-3])) print(max([-1,-5,-43,-2,-7])) # 4. Create a function that takes a list as an argument # The list should contain any number of entries. # each entry should have a name and grade # return the name of the person with the highest grade def highest_grade(my_list): for key in my_list: for key2 in my_list: if my_list[key]>my_list[key2]: name = key else: name = key2 return name print(highest_grade ({'mike':40,'jon':60,'dina':90})) # Example with default argument def say_happy_birthday(name, age, from_name=None): print(f"Happy Birthday {name}! You are {age} years old.") if from_name is not None: print(f"From {from_name}")
true
aff2134f2e4a76a59dc2d99184a548e17f290de0
LStokes96/Python
/Code/teams.py
945
4.28125
4
#Create a Python file which does the following: #Opens a new text file called "teams.txt" and adds the names of 5 sports teams. #Reads and displays the names of the 1st and 4th team in the file. #Create a new Python file which does the following: #Edits your "teams.txt" file so that the top line is replaced with "This is a new line". #Print out the edited file line by line. teams_file = open("teams.txt", "w") teams_1 = str(input("Name a team: ")) teams_2 = str(input("Name a team: ")) teams_3 = str(input("Name a team: ")) teams_4 = str(input("Name a team: ")) teams_5 = str(input("Name a team: ")) teams_file.write(teams_1 + "\n") teams_file.write(teams_2 + "\n") teams_file.write(teams_3 + "\n") teams_file.write(teams_4 + "\n") teams_file.write(teams_5 + "\n") teams_file.close() teams_file = open("teams.txt", "r") print(teams_file.readline()) teams_file.readline() teams_file.readline() print(teams_file.readline()) teams_file.close()
true
58d75067e577cf4abaafc6e369db8da6cf8e7df1
FL9661/Chap1-FL9661
/Chap3-FL9661/FL9661-Chap3-3.py
2,254
4.5
4
# F Lyness # Date 23 Sept 2021 # Lab 3.4.1.6: the basics of lists # # Task: use a list to print a series of numbers hat_numbers = [1,2,3,4,5] #list containing each number value known as an element print ('There once was a hat. The hat contained no rabbit, but a list of five numbers: ', hat_numbers [0], hat_numbers [1], hat_numbers [2], hat_numbers [3], 'and', hat_numbers [4]) # prints each element value using its index numeber hat_numbers [3] = input('Please assign new number value: ') # step 1 prompt the user to replace the middle element value del hat_numbers [-1] # removes the last element from the list (Step 2) print ('number of list entries is: ', len(hat_numbers)) #outputs to the console number of elements within the list # Lab 3.4.1.13: the Beatles # # step 1 create an empty list named beatles; beatles = [] # name of list = [] empty element container print('Step 1:', beatles) # Outputs list elemetns to console # step 2 - Add first memebr elements beatles.append('John Lennon') #0 beatles.append('Paul McCartney') #1 beatles.append('George Harrison') #2 print('Step 2:', beatles) # Outputs list elemetns to console # step 3 - input new memebr elements a = input ('enter Pete Best: ') b = input ('enter Stu Sutcliffe: ') for i in beatles: if a == ('Pete Best'): beatles.append (a) if b == ('Stu Sutcliffe'): beatles.append (b) print('Step 3:', beatles) break # step 4 - remove old memebr elements del beatles [4] # Del George Harrison del beatles [3] # Del Stu Sutcliffe #Step 5 beatles.insert(0, 'Ringo Star') print('step 4:', beatles) # Lab 3.6.1.9 - copying uniques numbers to a new list Forename = input('Please enter your Forename: ') # users firstname Surname = input('Please enter your Forename: ') # users surname mylist = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]#current list newlist = [] #new blank list print('Hello', Forename, Surname, 'I have taken your old list that contained') print('these values ', mylist, '.', '\n', '\n', sep='' ) for i in mylist: #for numbers within mylist if i not in newlist: #if i is unique not in newlist newlist.append (i) # add i to new list print('I have made a new list that has', (len(newlist)), 'unique instances. These instances are:') print (newlist)
true
6c68a4b129524de39ef050160decd697dfec5a86
sigrunjm/Maximum-number
/maxnumb.py
471
4.4375
4
num_int = int(input("Input a number: ")) # Do not change this line # Fill in the missing code #1. Get input from the user #2. if number form user is not negative print out the largest positive number #3. Stop if user inputs negative number max_int = 0 while num_int > 0: if num_int > max_int: max_int = num_int num_int = int(input("Input a number: ")) # Do not change this line print("The maximum is", max_int) # Do not change this line
true
28962e9e8aaa5fb3ce7f67f8b4109c426fed0f65
yaseenshaik/python-101
/ints_floats.py
539
4.15625
4
int_ex = 2 float_ex = 3.14 print(type(float_ex)) # Float/normal division print(3 / 2) # 1.5 # Floor division print(3 // 2) # gives 1 # Exponent print(3 ** 2) # 9 # Modulus print(3 % 2) # 1 # priorities - order of operations print(3 + 2 * 4) # 11 # increment int_ex += 1 print(int_ex) # round (takes a integer for decimal) print(round(3.75, 1)) # 3.8 # comparison print(int_ex == float_ex) # same for !=, >, <, >=, <= # typecasting hund = '100' # print(hund + int_ex) # Will throw error print(int(hund) + int_ex)
true
dae861a719ced79a05da501c28302a2452395924
abercrombiedj2/week_01_revision
/lists_task.py
493
4.4375
4
# 1. Create an empty list called `task_list` task_list = [] # 2. Add a few `str` elements, representing some everyday tasks e.g. 'Make Dinner' task_list.append("Make my bed") task_list.append("Go for a run") task_list.append("Cook some breakfast") task_list.append("Study for class") # 3. Print out `task_list` print(task_list) # 4. Remove the last task task_list.pop() # 5. Print out `task_list` print(task_list) # 6. Print out the number of elements in `task_list` print(len(task_list))
true
a430e9bb28ae56dfe1309b2debbfff29b73a41b8
milincjoshi/Python_100
/95.py
217
4.40625
4
''' Question: Please write a program which prints all permutations of [1,2,3] Hints: Use itertools.permutations() to get permutations of list. ''' import itertools l = [1,2,3] print tuple(itertools.permutations(l))
true
fac3f0586e4c82f66a35d23b3ec09640da8dab44
milincjoshi/Python_100
/53.py
682
4.6875
5
''' Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. Hints: To override a method in super class, we can define a method with the same name in the super class. ''' class Shape(): def __init__(self):# constructor pass def area(self): return 0 class Square(Shape): def __init__(self, length): Shape.__init__(self)# calling super constructor self.length = length def area(self): return self.length**2 square = Square(5) print square.area()
true
2822a1bdf75dc41600d2551378b7c533316e6a86
milincjoshi/Python_100
/45.py
318
4.25
4
''' Question: Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use lambda to define anonymous functions. ''' #print map([x for x in range(1,11)], lambda x : x**2) print map( lambda x : x**2,[x for x in range(1,11)])
true
bc2efffa5e46d51c508b6afa2f5deda322a77765
milincjoshi/Python_100
/28.py
247
4.15625
4
''' Question: Define a function that can receive two integral numbers in string form and compute their sum and then print it in console. Hints: Use int() to convert a string to integer. ''' def sum(a,b): return int(a)+int(b) print sum("2","4")
true
e95d429da8c1244e407913413e549ed08316bf59
LMIGUE/Github-mas-ejercicios-py
/classCircle.py
717
4.25
4
class Circle: def __init__ (self, radius): self.radius = radius def circumference(self): pi = 3.14 circumferenceValue = pi * self.radius * 2 return circumferenceValue def printCircumference (self): myCircumference = self.circumference() print ("Circumference of a circle with a radius of " + str(self.radius) + " is " + str(myCircumference)) # Primera instancia de la clase Circle. circle1 = Circle(4) # Llame a la PrintCircumference para la clase circle1 instanciada. circle1.printCircumference() # Dos instancias más y llamadas a métodos para la clase Circle. circle2 = Circle(6) circle2.printCircumference() circle3 = Circle(10) circle3.printCircumference()
false
9de6d50bce515e0003aaff576c3c92d04b162b9d
chandanakgd/pythonTutes
/lessons/lesson6_Task1.py
1,513
4.125
4
''' * Copyright 2016 Hackers' Club, University Of Peradeniya * Author : Irunika Weeraratne E/11/431 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ''' ''' TASK 1: add dict dictionary object to myList sort array by index select first 4 elements sort it by name print the list ''' #Answer dict = {'id':4, 'name': 'Amare'} #This is a dictionary in Python which is similar data structure like 'struct' in C print 'id :', dict['id'] #Extract 'id' from the dictionary 'a' print 'name :', dict['name'] #Extracted 'name' from the dictionary 'a' myList = [ {'id':2, 'name':'Bhagya'}, {'id':1, 'name':'Irunika'}, {'id':7, 'name':'Tharinda'}, {'id':3, 'name':'Ruchira'}, {'id':6, 'name':'Namodya'}, {'id':5, 'name':'Menaka'} ] myList.append(dict) #add dict dictionary object to myList myList.sort(key=lambda x:x['id']) #Sort array by index myList_new = myList[0:4] #select first 4 elements myList_new.sort(key=lambda item:item['name']) #sort it by name #print the list for item in myList_new: print item
true
6a0c9526c14dd7fb71a9ba8002d3673e7da8b29b
yangzhao1983/leetcode_python
/src/queue/solution225/MyStack.py
1,512
4.125
4
from collections import deque class MyStack(object): def __init__(self): """ Initialize your data structure here. """ self.q1 = deque() self.q2 = deque() def push(self, x): """ Push element x onto stack. :type x: int :rtype: None """ while len(self.q1) > 0: self.q2.append(self.q1.popleft()) self.q1.append(x) def pop(self): """ Removes the element on top of the stack and returns that element. :rtype: int """ top = self.q1.popleft() while len(self.q2)> 1: self.q1.append(self.q2.popleft()) self.q1, self.q2 = self.q2, self.q1 return top def top(self): """ Get the top element. :rtype: int """ return self.q1[0] def empty(self): """ Returns whether the stack is empty. :rtype: bool """ return len(self.q1) == 0 and len(self.q2) == 0 # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty() def test1(): my_stack = MyStack() my_stack.push(1) my_stack.push(2) my_stack.push(3) print(my_stack.top()) print(my_stack.pop()) print(my_stack.top()) print(my_stack.pop()) print(my_stack.empty()) if __name__ == '__main__': test1()
true
a657612ac1dbce789b2f2815e631ffad2a8de060
AlexMazonowicz/PythonFundamentals
/Lesson2.1/solution/urlvalidator_solution.py
1,040
4.28125
4
import requests def validate_url(url): """Validates the given url passed as string. Arguments: url -- String, A valid url should be of form <Protocol>://<hostmain>/<fileinfo> Protocol = [http, https, ftp] Hostname = string Fileinfo = [.html, .csv, .docx] """ protocol_valid = True valid_protocols = ['http', 'https', 'ftp'] valid_fileinfo = ['.html', '.csv', '.docx'] #first split the url to get protocol protocol = url.split("://")[0] if protocol not in valid_protocols: protocol_valid = False fileinfo_valid = False for finfo in valid_fileinfo: if url.endswith(finfo): fileinfo_valid = True # both protocol and fileinfo should be valid to return true. if protocol_valid and fileinfo_valid: return True else: return False #take home solution def get_url_response(url): r = requests.get(url) if r.status_code == 200: return r.text else: return r.status_code if __name__ == '__main__': url = input("Enter an Url: ") print(validate_url(url))
true
79a2b5f3b7e3594ed0137ed3f0d12912f15e6d6f
mulus1466/raspberrypi-counter
/seconds-to-hms.py
302
4.15625
4
def convertTime(seconds): ''' This function converts an amount of seconds and converts it into a struct containing [hours, minutes, seconds] ''' second = seconds % 60 minutes = seconds / 60 hours = minutes / 60 Time = [hours, minutes, second] return Time
true
5be76054d3e797c6f7a997569a99f01aedfbd6a8
Nilsonsantos-s/Python-Studies
/Mundo 1 by Curso em Video/Exercicios Python 3/ex022.py
458
4.125
4
# leia um nome completo e mostre : letra maiusculas, letras miusculas, quantas letras sem espaços, letras tem o primero nome. nome = input('Digite seu nome completo:') print(f' O seu nome completo em maiusculo é : {nome.upper()}') print(f' O seu nome completo em minusculo é : {nome.lower()}') print(f' O seu nome tem {len(nome.replace(" ",""))} letras sem espaços') linha = nome.split() print(f' O seu nome tem {len(linha[0])} Letras no primeiro nome')
false
ba25f64610567598313f2b33919334f925db8b86
Nilsonsantos-s/Python-Studies
/Mundo 3 by Curso em Video/Exercicios/ex115/__init__.py
2,125
4.34375
4
# crie um pequeno sistema modularizado que # permita cadastrar pessoas pelo seu nome e idade em um arquivo de txt simples # o sistema so vai ter 2 opções: cadastrar uma nova pessoa e listar todas as pessoas cadastradas def titulo(texto): texto = str(texto) print('*-' * 25) print(f'{texto.title(): ^50}') print('*-' * 25) def menu(): titulo('menu primario') print(''' 1 - Ver pessoas Que estão cadastradas 2 - Cadastrar novas Pessoas 3 - Sair do Programa ''') while True: try: escolha = int(input('Escolha uma opção:')) except ValueError: print('Erro: Digite um valor inteiro Corretamente!!') except: print('Erro: Desconhecido') else: if 1 <= escolha <= 3: break else: print(f'A opção "{escolha}" não existe') return escolha def lerNome(): while True: try: nome = str(input('Digite o Nome:')).strip().title() vazio = nome.split() vazio = ''.join(vazio) except: print('Erro: Desconhecido') else: if vazio.isalpha() and nome != '': break return nome def lerIdade(): while True: try: idade = int(input('Digite a Idade:')) except ValueError: print('Erro: Digite Corretamente uma idade') except: print('Erro: Desconheido') else: if idade > 0: break else: print('Idade não pode ser negativa ou igual a 0') return idade def formatarTexto(nome,idade): formato = f'{nome[:40]: <42}{idade: >3} Anos' return formato def salvarDados(texto_formatado): texto_formatado = str(texto_formatado) arquivo = open('base_dados.txt', 'a+') arquivo.write(f'{texto_formatado}\n') def lerDados(): try: arquivo = open('base_dados.txt', 'r+') except: print('Erro: Salve ao menos 1 registro para abrir') else: titulo('pessoas no banco de dados') print(arquivo.read())
false
2fbde86ebba0d575833e4aeb65e77dfd1f2e0ab2
Nilsonsantos-s/Python-Studies
/basic_python/aulas_by_geek_university/reversed.py
986
4.65625
5
''' -> Reversed OBS: não confundir com reverse pois é uma função das listas: lista.reverse() # Retorna a lista invertida O Reversed funciona para quaisquer iterável, invertendo o mesmo. -> Retorna um iterável propio, de nome: List Reversed Iterator # Exemplos: ## Iteraveis dados = list(range(10)) print(dados) # Iterável print(reversed(dados)) # Objeto Propio que também é iterável print(type(reversed(dados))) # list_reverseiterator print(list(reversed(dados))) # Convertido em lista ## Strings ### Invertendo Nome nome = 'LUCAS NUNES DE ASSIS' print(nome) print(nome[::-1]) # Método mais fácil [print(letra, end='') for letra in reversed(nome)] # Utilizando For e Reversed print() print(''.join(list(reversed(nome)))) # Utilizando join e Reversed ## Range ### Invertendo range dados_reversed = reversed(range(10)) # Utilizando Reversed dados_range = list(range(9, -1, -1)) # Utilizando Parametros do range print(list(dados_reversed)) print(dados_range) '''
false
8d1947a37f5305936fe58775d47c8267a767db97
Nilsonsantos-s/Python-Studies
/Mundo 3 by Curso em Video/Exercicios/075.py
1,207
4.125
4
# leia quatro valores pelo teclado e guardalos em uma tupla, no final mostrar, quantas vezes apareceu o valor 9. # em que posição foi digitado o primeiro valor 3, quais foram os numeros pares. valores = pares = tuple() # Forma Realizada for x in range(0,4): inpu = input('Digite um valor:') valores += tuple(inpu) if int(inpu) % 2 == 0: pares += tuple(str(inpu)) """ # forma alternativa inpu = (int(input('Digite um valor:')), int(input('Digite um valor:')), int(input('Digite um valor:')), int(input('Digite um valor:'))) for x in range(0,4): if int(inpu[x]) % 2 == 0: pares += tuple(str(inpu[x])) valores = inpu """ print(f'Os Valores digitados foram: {valores}') if 9 in valores or '9' in valores: print(f'O Numero 9 foi digitado {valores.count("9")} Vezes') else: print('O valor 9 não foi digitado') if 3 in valores or '3' in valores: print(f'A Posição digitada do Numero 3 foi : {valores.index("3")}') else: print('O valor 3 não foi Digitado') if len(pares) != 0: print('Os numeros pares são : ', end = '') for x in pares: print(x,end = ' ') else: print('Não Foram digitados Numeros pares')
false
3ae76c70671c80b157240feeef76e21f52312354
Nilsonsantos-s/Python-Studies
/basic_python/aulas_by_geek_university/ordered_dict.py
491
4.21875
4
""" Modulo Collections (Modulo conhecido por alta performance) - Ordered Dict > Um dicionario que tem a ordem de inserção garantida # Demonstrando Diferença entre Dict e Ordered Dict from collections import OrderedDict dict1 = {'a':1,'b':2} dict2 = {'b':2,'a':1} print(dict1 == dict2) # True odict1 = OrderedDict({'a':1,'b':2}) odict2 = OrderedDict({'b':2,'a':1}) print(odict1 == odict2) # False # Ordered dict retornou falso pois os elementos não são iguais pela ordem """
false
45d1a3a08d68b4f7f24f36b9dc01f505ee715004
JamesSG2/Handwriting-Conversion-Application
/src/GUI.py
1,998
4.40625
4
#tkinter is pre-installed with python to make very basic GUI's from tkinter import * from tkinter import filedialog root = Tk() #Function gets the file path and prints it in the command #prompt as well as on the screen. def UploadAction(event=None): filename = filedialog.askopenfilename() print('Selected:', filename) myLabel1 = Label(root, text=filename) myLabel1.grid(row=1,column=0) #function specifies actions that take place on the click of myButton def myClick(): #prints the user input from the entry box. mylabel2 = Label(root, text="retrieving data for: " + e.get()) mylabel2.grid(row=4,column=0) #creates button that calls function myClick myButton = Button(root, text="type your name", command = myClick) myButton.grid(row=2, column=0) #entry box for user's name when adding images to program e = Entry(root, width=50) e.grid(row=3, column =0) #very simple button that calls the upload action Function button = Button(root, text='Upload a sample', command=UploadAction, width=40) button.grid(row=0, column=0) #----------------------------------------------------------------------------------------- #hand used when the user wants to type a sentece and see the ai output def hand(): #function prints the string that the user wants converted. def sentence(): mylabel3 = Label(root, text="your sentece is: " + entry2.get()) mylabel3.grid(row=4,column=1) #Button and corrisponding entry box that obtains characters to be converted. myButton3 = Button(root, text="now type your desired characters", command=sentence) myButton3.grid(row=2, column=1) entry2 = Entry(root, width=50) entry2.grid(row=3, column=1) #the name of the person who wants to type and see their generated handwriting button2 = Button(root, text="recive handwriting, type your name below", command=hand) button2.grid(row=0, column=1) entry = Entry(root, width=50) entry.grid(row=1, column=1) root.mainloop()
true
fcfe2cc13a4f75d0ea9d47f918a7d53e3f8495df
cs-fullstack-2019-fall/python-basics2f-cw-marcus110379
/classwork.py
1,610
4.5
4
### Problem 1: #Write some Python code that has three variables called ```greeting```, ```my_name```, and ```my_age```. Intialize each of the 3 variables with an appropriate value, then rint out the example below using the 3 variables and two different approaches for formatting Strings. #1) Using concatenation and the ```+``` and 2) Using an ```f-string```. Sample output: #YOUR_GREETING_VARIABLE YOUR_NAME_VARIABLE!!! I hear that you are YOUR_MY_AGE_VARIABLE today! #greeting = "hello" #my_name = "marcus" #my_age = 39 #print(f"{greeting} {my_name}!!! I hear that you are {my_age} today") #print(greeting + " " + my_name + "!!! I hear that you are " + str(my_age) + " today") ### Problem 2: #Write some Python code that asks the user for a secret password. Create a loop that quits with the user's quit word. If the user doesn't enter that word, ask them to guess again. userInput = input("enter a password") userInput2 = input("enter password again") while userInput != userInput2 and userInput2 != "q": userInput2 = input("enter password again or q to quit") ### Problem 3: #Write some Python code using ```f-strings``` that prints 0 to 50 three times in a row (vertically). #for i in range(0, 50 +1, 1): # print(f"{i} {i} {i}") ### Problem 4: #Write some Python code that create a random number and stores it in a variable. Ask the user to guess the random number. Keep letting the user guess until they get it right, then quit. #import random #randomNum = random.randint(1, 10 + 1) #userInput = 0 #while userInput != randomNum: # userInput = int(input("guess the random number"))
true
3763ee2e94ab64e04a0725240cdc3a7a6990a3ad
yz398/LearnFast_testing
/list_module/max_difference.py
1,314
4.125
4
def max_difference(x): """ Returns the maximum difference of a list :param x: list to be input :type x: list :raises TypeError: if input is not a list :raises ValueError: if the list contains a non-float or integer :raises ValueError: if list contains +/-infinity :return: the maximum difference of adjacent numbers :rtype: float """ try: import logging from math import fabs except ImportError: print("Necessary imports failed") return logging.basicConfig(filename='max_difference.log', filemode='w', level=logging.DEBUG) if type(x) is not list: logging.error("Input is not a list") raise TypeError() curr_max = 0.0 for index, entry in enumerate(x): try: num = float(entry) except ValueError: print("your input has a invalid value: {}".format(entry)) return None if num == float('inf') or num == float('-inf'): logging.warning("List contains infinities") raise ValueError() if index > 0: diff = fabs(entry - x[index-1]) curr_max = max(curr_max, diff) logging.info("Returning the maximum difference") return curr_max
true
70276b8e585bd6299b8e9a711f5271089f25ab04
BenjaminLBowen/Simple-word-frequency-counter
/word_counter.py
938
4.25
4
# Simple program to list each word in a text that is entered by the user # and to count the number of time each word is used in the entered text. # variable to hold users inputed text sentence= input("Type your text here to count the words: ") # function to perform described task def counting_wordfunc(sentence): # variable and dictionary used in the function new_sentence= sentence.split() counting_words= {} # the part of the function that adds words to the dictionary and counts # each time the word is used for word in new_sentence: if word not in counting_words: counting_words[word] = 1 else: counting_words[word] += 1 # returns the value of the completed dictionary return counting_words # prints a line to tell the user what is to folow print("Here is a count of each word in the text you entered:") # prints the result of the function print(counting_wordfunc(sentence))
true
e557e78a72b9ad5863b730d7d207b726612b5989
TH-Williamson/Class-Projects
/dateformat.py
688
4.3125
4
#need to tqke an integer input, and convert it to mm/dd/yyyy AND DD-MM-YYY format #TH Williamson, intro to programming, Prof. Kurdia user_day = str(input('Please enter day: ')) user_month = str(input('Please enter month: ')) user_year = str(input('Please enter year: ')) if user_day[0] == 0: user_day = '0' + user_day else: user_day = user_day #US, Micronesia date format print('Here is the formatted date:', user_month, end='') print('/', end='') print(user_day, end='') print('/', end='') print(user_year) #Rest of world format print('Here is the formatted date:', user_day, end='') print('-', end='') print(user_month, end='') print('-', end='') print(user_year)
false
c7b32d7c040304d87a25b09008f6045d0d5d304b
rj-fromm/assignment3b-python
/assignment3b.py
530
4.375
4
# !user/bin/env python3 # Created by: RJ Fromm # Created on: October 2019 # This program determines if a letter is uppercase or lowercase def main(): ch = input("Please Enter a letter (uppercase or lowercase) : ") if(ord(ch) >= 65 and ord(ch) <= 90): print("The letter", ch, "is an uppercase letter") elif(ord(ch) >= 97 and ord(ch) <= 122): print("The letter", ch, "is a lowercase letter") else: print(ch, "is Not a lowercase or Uppercase letter") if __name__ == "__main__": main()
true
27b16e6ee0cbd9477fc99475382e5e8e95d1efb7
gautamdayal/natural-selection
/existence/equilibrium.py
2,379
4.28125
4
from matplotlib import pyplot as plt import random # A class of species that cannot reproduce # Population is entirely driven by birth and death rates class Existor(object): def __init__(self, population, birth_rate, death_rate): self.population = population self.birth_rate = birth_rate self.death_rate = death_rate # Updates population based on birth and death rates def update(self): if random.randint(0, 100) < self.birth_rate: self.population += 1 for organism in range(self.population): if random.randint(0, 100) < self.death_rate: self.population -= 1 # Returns the predicted equilibrium value based on our equation def getEquilibrium(self): return(self.birth_rate/self.death_rate) # Takes three arguments: number of cycles, whether to plot equilibrium, whether to plot mean def plotPopulation(self, cycles, with_equilibrium = False, with_mean = False): Y = [] for cycle in range(cycles): self.update() Y.append(self.population) plt.ylim(0, 5 * self.getEquilibrium()) plt.plot(Y, label='Population') if with_mean: mean = sum(Y)/len(Y) plt.plot([mean for i in range(cycles)], label = 'Mean population') if with_equilibrium: plt.plot([self.getEquilibrium() for i in range(cycles)], label = 'Predicted equilibrium') plt.xlabel('Cycles') plt.ylabel('Number of organisms') plt.legend() plt.show() # A more realistic child class of Species as organisms can replicate class Replicator(Existor): def __init__(self, population, birth_rate, death_rate, replication_rate): Existor.__init__(self, population, birth_rate, death_rate) self.replication_rate = replication_rate # Inherited from Existor but modified to include a replication rates def update(self): Existor.update(self) for organism in range(self.population): if random.randint(0, 100) < self.replication_rate: self.population += 1 def getEquilibrium(self): return(self.birth_rate/(self.death_rate - self.replication_rate)) raindrop = Existor(0, 100, 10) pigeon = Replicator(3, 10, 5, 3) # raindrop.plotPopulation(500, True, True) pigeon.plotPopulation(500, True, True)
true
1a5f5335e97941b5797ba92bc13877e4a73acd00
markagy/git-one
/Mcq_program.py
1,487
4.25
4
# Creating a class for multiple choice exam questions.Each class object has attribute "question" and "answer" class Mcq: def __init__(self, question, answer): self.question = question self.answer = answer # Creating a list of every question test = [ "1.How many sides has a triangle?\n (a) 1\n (b) 2\n (c) 3\n\n", "2.How many sides has a rectangle?\n (a) 3\n (b) 4\n (c) 5\n\n", "3.How many sides has a hexagon?\n (a) 1\n (b) 5\n (c) 6\n\n", "4.What is the total internal angle of a Triangle?\n (a) 120\n (b) 180\n (c) 360\n\n", "5.A square has the same sides as a rectangle?\n (a) True\n (b) False\n (c) None\n\n", ] # Creating a list that contains object of the class with attributes to serve as a marking scheme marking_scheme = [ Mcq(test[0], "c"), Mcq(test[1], "b"), Mcq(test[2], "c"), Mcq(test[3], "b"), Mcq(test[4], "a") ] #Defining function that marks test with the marking scheme def mark_script(marking_scheme): print("\n\nEND OF SEMESTER EXAMS\nType the letter that corresponds to your answer!!\n\n") score = 0 for obj in marking_scheme: answer = input(obj.question) if answer == obj.answer: score += 1 print("\nYou got " + str(score) + "/" + str(len(test)) + " correct!") if score < 3: print("Sorry you need to take the exam again!!") else: print("Congratulations, you can proceed to the next class") mark_script(marking_scheme)
true
a3e8cfb8a4f8f7765e9088883440d151e6d972d5
nagios84/AutomatingBoringStuff
/Dictionaries/fantasy_game_inventory.py
767
4.1875
4
#! python3 # fantasy_game_inventory.py - contains functions to add a list of items to a dictionary and print it. __author__ = 'm' def display_inventory(inventory): total_number_of_items = 0 for item, quantity in inventory.items(): print(quantity, item) total_number_of_items += quantity print("Total number of items: " + str(total_number_of_items)) def add_to_inventory(inventory, items_to_add): for item in items_to_add: inventory[item] = inventory.get(item, 0) + 1 def main(): inventory = {'gold coin': 42, 'rope': 1} dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] add_to_inventory(inventory, dragon_loot) display_inventory(inventory) if __name__ == "__main__": main()
true
017b0543fd031602af8129b05cd6567ce67fc5db
AnuraghSarkar/DataStructures-Algorithms_Practice
/queue.py
1,671
4.53125
5
class queue: def __init__(self): self.items = [] def enqueue(self, item): """ Function to add item in first index or simply enqueue. Time complexity is O(n) or linear. If item is added in first index all next items should be shifted by one. Time depends upon list length. """ self.items.insert(0, item) def dequeue(self): """ It removes and return the first element which is added in a list or last item in list. Time complexity is O(1) or constant since it works on last index only. """ if self.items: return self.items.pop() return None def peek(self): """ Return last element in list or front-most in queue that is going to be deleted next. Time complexity is O(1) """ if self.items: return self.items[-1] return None def size(self): """ Return length of the queue. Time complexity O(1). """ return len(self.items) def is_empty(self): """ Check if queue is empty or not. O(1). """ if self.items: return 'not empty!' return 'empty!' my_queue = queue() my_queue.enqueue('apple') my_queue.enqueue('banana') my_queue.enqueue('orange') print(f'My queue order is {my_queue.items}.') print(f'Removing the first item you inserted in list that is {my_queue.dequeue()}.') print(f'The item going to be deleted next is {my_queue.peek()}.') print(f'My queue order is {my_queue.items}.') print(f'The size of queue is {my_queue.size()}.') print(f'My queue status is {my_queue.is_empty()}.')
true
75d580033b9ae7be6a86340e7b214ac101d25fdb
xpansong/learn-python
/对象(2)/3. 方法重写.py
1,079
4.21875
4
print('----------方法重写---------------') '''如果子类对继承自父类的某个属性或方法不满意,可以在子类中对其(方法体)进行重新编写''' '''子类重写后的方法中可以通过super().XXX()调用父类中被重写的方法''' class Person: #也可以写Person(object) def __init__(self,name,age): self.name=name self.age=age def info(self): print(self.name,self.age) class Student(Person): def __init__(self,name,age,stu_no): super().__init__(name,age) self.stu_no=stu_no def info(self): #方法重写 super().info() #调用父类中的方法 print(stu.stu_no) class Teacher(Person): def __init__(self,name,age,teach_of_year): super().__init__(name,age) self.teach_of_year=teach_of_year def info(self): super().info() print(teacher.teach_of_year) stu=Student('宋晓盼',33,'1001') teacher=Teacher('张三',35,'9') stu.info() #info是从Person类继承name和age,从子类继承stu_no teacher.info()
false