blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
dc72e0c85760fb647f5ce64289303cbe915fdb04
Anosike-CK/class_code
/Membership_Operartors.py
1,389
4.625
5
# MEMBERSHIP OPERATORS ARE USED TO CHECK FOR THE MEMBERSHIP OF A VARIABLE IN A SEQUENCE a = 10 b = 20 num_list = [1, 2, 3, 4, 5 ] if ( a in num_list ): print ("Line 1 - a is available in the given num_list") else: print ("Line 1 - a is not available in the given num_list") if ( b not in num_list ): print ("Line 2 - b is not available in the given num_list") else: print ("Line 2 - b is available in the given num_list") a = 2 if ( a in num_list ): print ("Line 3 - a is available in the given num_list") else: print ("Line 3 - a is not available in the given num_list") print("\n For IN operator") name = "Adebayo" print("x" in name) #print false because 'x' is not a member in name print("a" in name) #print true because 'a' is in name print("x" not in name, "after adding not logigical operator") #print true because not negates the original answer print("\n mixing menbership operators with the logicaloperators for multiple tests\n") test_list = [1,4,5,6,7,8] print(1 in test_list, ", single test") print(1 in test_list and 32 in test_list, ",multiple tests with 'AND' logical operator") print(1 in test_list and 32 not in test_list, ",multiple tests with 'AND' logical operator and 'NOT' inverting factor") print(1 in test_list and 32 not in test_list or 8 in test_list, ",multiple tests with 'AND' logical operator and 'NOT' inverting factor")
true
fd0012b59d8cda95b17f00aecef6093446defd34
Anosike-CK/class_code
/first_thonny_practice.py
330
4.25
4
"""website = "Apple.com" #we re-write the program to change the value of website to programiz.com website = "programiz.com" print(website) """ """#Assign multiple values to multiple variables a,b,c = 5,3,5.2 print(a) print(b) print(c)""" #Assign the same value to multiple variables x = y = z = "hmm" print(x) print(y) print(z)
true
eec3c15f8d1a40faddbb551aafe9ee823c09cd09
zs1621/pythostudy
/argparse/argparse_example.py
808
4.28125
4
#!/usr/bin/env python # coding: utf-8 """ parser = argparse.ArgumentParser() - parser.add_argument help: description action: 动作 count-参数个数, default-参数默认值, store_true-如果参数指定,赋值 True 或 args.verbose, choice-参数可以选择的值, type-参数的类型 - parser.parse_args """ import argparse parser = argparse.ArgumentParser() parser.add_argument("square", help="echos the string you use here", type=int) parser.add_argument("-v","--verbosity", action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2 if args.verbosity == 2: print "the square of {} equals {}".format(args.square, answer) elif args.verbosity == 1: print "{}^2 == {}".format(args.square, answer) else: print answer
false
921c99126444561c5f940f00e569a7a1367765b1
zs1621/pythostudy
/class/attribute.py
1,147
4.21875
4
#!/usr/bin/env python # coding: utf-8 """ In Python, only class attributes can be defined here; data attributes are defined in the __init__ method. """ class Test: a = 0 #class attributes def __init__(self): self.a += 1 #data attributes print(Test.a) print(Test().a) """ 如果想改变 类的属性 """ class counter: count = 0 def __init__(self): self.__class__.count += 1 self.count = 9 print counter, '---' # __main__.counter print counter.count # 0 c = counter() # 这里创建类实例 会影响到类的自身属性值变化 print c.count # 1 print counter.count # 1 d = counter() # 第一次创建实例后, 类的count 属性值变为1 print d.count # 2 print c.count # 2 print counter.count # 2 # 类的属性 是被类和类实例共享 """ 如果没有定义self.* = ** """ class Test_share(): a = 'ddddd' def __init__(self): #self.a = 'eeeee' pass def get_a(self): print self.a k = Test_share() k.get_a() # ddddd """ 如果有兴趣可以看下将注释的self.count = 9 运行 能很明显的了解 类属性和实例属性的区别 """
false
90e061241a1de2eb2ec544b864782218ec8d6711
Kllicks/DigitalCraftsPythonExercises
/OddNumbers.py
356
4.375
4
#using while loop, print out the odd numbers 1-10 inclusive, one on a line #initiate variable i = 1 #while loop to cycle through and print 1-10 while i <= 10: #if statement to check if the number is also odd #can't use and on outer while loop because it would end the program when 2 failed if i % 2 != 0: print(i, "") i += 1
true
5c250f4557d71212cde13a0002b7ebc8f39f4bc6
yasar84/week1
/lists.py
2,166
4.5
4
cars = ["toyota","lexus", "bmw", "merc" ] print(cars) # accessing the list print("first element of cars list: " + cars[0]) print("second element of cars list: " + cars[1]) print("third element of cars list: " + cars[2]) print("fourth element of cars list: " + cars[3]) print("last element of cars list: " + cars[-1]) print("second element from last of cars list: " + cars[-2]) # IndexError expected "list index out of range" # print("fourth element of cars list: " + cars[4]) # adding elements to the list >> append() cars.append("range rover") print(cars) cars.append("mazda") print(cars) print("fifth element of cars list: " + cars[4]) print("sixth element of cars list: " + cars[5]) # modifying, replacing the element on certain index # cars[3] = "bentley" cars.extend("bentley") print(cars) # cars[0] = "ram" cars.extend("ram") print(cars) # deleting the elements by index del cars[0] print(cars) del cars[-9:] print(cars) # adding an element to a specific position cars.insert(0, "audi") print(cars) cars.insert(3, "tesla") print(cars) # remove() deleting the element from the list using the value cars.remove("range rover") print(cars) # pop() removes last element and returns the value sold_cars = [] # empty list sold_cars.append(cars.pop()) # adding the removed car to the end of the new list sold_cars.insert(0, cars.pop()) # adding the removed car to the beginning of the new list # adding the removed car(first car in the list) to the beginning of the new list sold_cars.insert(0, cars.pop(0)) print(sold_cars) print(cars) # organize your lists # sort() # cars.sort() # list is sorted in ascending order # cars.sort(reverse=True) # list is ordered in descending order sorted_cars = sorted(cars) print(cars) print(sorted_cars) sorted_cars_desc = sorted(cars, reverse=True) print(sorted_cars_desc) print(cars) # cars.reverse() # does not apply ordering asc or desc, it just reverses the list # print(cars) # copying the list cars.append("moskvish") print(cars) print(new_cars) new_cars_copy = cars[:] # copying the list and creating independent new_cars_copy list cars.append("lada") print(cars) print(new_cars) print(new_cars_copy)
true
1d001ee57009334fa0394946f4b65c4f46741172
AgguBalaji/MyCaptain123
/file_format.py
380
4.71875
5
"""Printing the type of file based on the extension used in saving the file eg: ip-- name.py op--it is a python file""" #input the file name along with the extension as a string file=input("Input the Filename:") #it is a python file if it has .py extension if ".py" in file: print("The extension of the file is : 'python'") else: print("File type cannot be identified")
true
af8d1a4b71460e9ecd5819fddd63a97d4ccd7bfa
cai-michael/kemenyapprox
/matrix.py
1,382
4.3125
4
""" Defines some matrix operations using on the Python standard library """ def generate_zeros_matrix(rows, columns): """ Generates a matrix containing only zeros """ matrix = [[0 for col in range(columns)] for row in range(rows)] return matrix def get_column_as_list(matrix, column_no): """ Retrieves a column from a matrix as a list """ column = [] num_rows = len(matrix) for row in range(num_rows): column.append(matrix[row][column_no]) return column def calculate_cell(matrix_a, matrix_b, row, column): """ Calculates an individual cell's value after multiplication """ matrix_b_column = get_column_as_list(matrix_b, column) column_length = len(matrix_b_column) products = [matrix_a[row][i]*matrix_b_column[i] for i in range(column_length)] return sum(products) def matrix_multiplication(matrix_a, matrix_b): """ Multiplies two matrices by each other """ a_rows = len(matrix_a) a_columns = len(matrix_a[0]) b_rows = len(matrix_b) b_columns = len(matrix_b[0]) if a_columns != b_rows: raise Exception(f'Dimension mismatch: {a_columns}, {b_rows}') result = generate_zeros_matrix(a_rows, b_columns) for i in range(a_rows): for j in range(b_columns): result[i][j] = calculate_cell(matrix_a, matrix_b, i, j) return result
true
31a9494408c46a07d34b9b4d5f1338d1de9b37ef
Jon710/python-topicos2
/p2/analise_string.py
1,788
4.1875
4
# lista que será traduzida list_of_words = ['thy', 'thine', 'thee', 'thou', 'hath'] # função que busca as palavras e quantidade total das palavras do Middle English def find_middle_english_words(text): # lista que irá conter as palavras, entre as que estão na lista, encontradas no texto words_found = [] counter = 0 # contador para armazenar o numero total de palavras do Ingles Arcaico text = text.split() # separa o livro/soneto aberto em uma lista de strings for word in text: for i in range(len(list_of_words)): if word == list_of_words[i]: # adiciona cada palavra encontrada no fim da lista. words_found.append(word) counter += 1 print('No total, há {} palavras do Inglês Arcaico (Middle English). As encontradas foram: {}.'.format( counter, words_found)) translate_words( input('Digite a palavra que será traduzida para o português: ')) def translate_words(word): # função que traduz as palavras da lista para o portugues if word == list_of_words[0]: print('Thy -> teu, teus') elif word == list_of_words[1]: print('Thine -> teus') elif word == list_of_words[2]: print('Thee -> ti') elif word == list_of_words[3]: print('Thou -> tu, vós') elif word == list_of_words[4]: print('Hath -> ter, tem') else: # caso seja uma palavra fora da lista, imprime isso print('Essa palavra não está na lista!!!') def read_book(path): # funcão para abrir e ler o texto escolhido. 'sonetos.txt' por exemplo with open(path, 'r', encoding='utf8') as file: text = file.read() return text text = read_book(input('Arquivo do livro a ser lido: ')) find_middle_english_words(text)
false
9465c54f43091c6fad9eb280bee17541b764017b
RomaMol/MFTI
/DirBasePython/Lec3/main.py
865
4.25
4
#!/usr/bin/python # -*- coding: utf-8 -*- # https://www.youtube.com/watch?v=HrlUxTOxil4 # Python 3 #3: функции input и print ввода/вывода # """ работа input() input() a = input() print(a) """ """ вычисляем периметр w = int(input()) h = int(input()) p = (w+h)*2 print(p) """ """ # вычисляем периметр w = int(input("Введите ширину :")) h = int(input("Введите длину :")) p = (w+h)*2 print(f'Периметр равен : {p}') """ # Форматный вывод функции print name = "fedia" f_name = "dmitrii" familia = "sokol" age = 18 print("Фамилия: %s Имя: %s Отчество: %s Возраст %d" % (familia, name, f_name, age), ) print(f'Фамилия: %s \nИмя: %s \nОтчество: %s \nВозраст %d' % (familia, name, f_name, age))
false
5c49261669a5d5655595e79976836a98af03287b
RomaMol/MFTI
/DirOPP/Lec2/main.py
2,481
4.34375
4
# https://www.youtube.com/watch?v=7kk2gRf8Uws&list=PLA0M1Bcd0w8zo9ND-7yEFjoHBg_fzaQ-B&index=2 # ООП Python 3 #2: методы класса, параметр self, конструктор и деструктор class House: """Класс существительное с большой буквы x = 1 y = 1 атрибуты == данные def fun() - методы == функции """ def __init__(self, x=0, y=0): # метод конструктор КЛАССА """Создание экземпляра КЛАССА House""" print("Создание экземпляра КЛАССА House") self.x = x self.y = y def __del__(self): # метод деструктор экземпляра КЛАССА """Удаление экземпляра КЛАССА после удаления ссылок на методы класса""" print("Удаление экземпляра КЛАССА" + self.__str__()) def fun_var1(self): # self - указание ссылка на экземпляр класс print('атрибуты класса ', self.__dict__) return self.__dict__ def fun_var2(self, x, y): """ H1.fun_var2("fest", "second") передача в функцию атрибутов из экземпляра класса """ self.a = x self.b = y # ----"""Создание экземпляра КЛАССА House""" H1 = House() # self - указание ссылка на экземпляр класс def fun_var1(self): print(H1.fun_var1()) H1.x = 5 H1.y = 10 print(H1.fun_var1()) # - вызов метода класс House экземпляром H1 и передача в метод атрибутов (5, 10 ) H1.fun_var2("fest", "second") print('H1.__dict__ ', H1.__dict__) # - передача в метод класс House атрибутов (5, 10 ) и экземпляра класса H1 print("House.fun_var2(H1,5,10)", House.fun_var2(H1, 5, 10)) print('H1.__dict__ ', H1.__dict__) print() # --- def __init__(self, x=0, y=0): """Создание экземпляра КЛАССА House""" H2 = House() H3 = House(5) H4 = House(5, 10) print(('Создание экземпляра КЛАССА House ', H2.__dict__), ('Создание экземпляра КЛАССА House ', H3.__dict__), ('Создание экземпляра КЛАССА House ', H4.__dict__), sep="\n")
false
fd012f62255613d28ef3d9976b2aca82a9b92ebc
RomaMol/MFTI
/DirBasePython/Lec14/main.py
763
4.1875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # https://www.youtube.com/watch?v=WElr9nSS6bo # Python 3 #14: функции (def) - объявление и вызов def printHelow(): print("Hellow world") # printHelow() p = printHelow p() def myxvkbd(x): x = x ** 2 return x print(myxvkbd(3)) def ispositive(p): if p >= 0: return True else: return False lst = [] for p in range(-10, 10): if ispositive(p): lst.append(p) print(lst) lst1 = [1,2,-5,8,-12,4,-6,26] lst2 = [] for p in lst1: if ispositive(p): lst2.append(p) print(lst2) def printHelow2(msg, end = " !!!"): #print("Hellow world") return print(msg + end) printHelow2("Hellow world") printHelow2("Hellow world", " @@@@")
false
37f813e7e6974fe499252e476755e3e7411a037c
khayk/learning
/python/cheatsheet.py
1,311
4.28125
4
# 1. Print two strings with formatting # see https://www.programiz.com/python-programming/input-output-import print("Hello %s %s! You just delved into python." % (a, b)) # 2. Map each item from the input to int integer_list = map(int, input().split()) # Creates a tuple of integers t = tuple(integer_list) # Creates a tuple of integers l = list(integer_list) # 3. Read the first string inside the command and the rest inside args command, *args = input().split() # 4. Locates the main function and call it if __name__ == '__main__': print("You are inside main") # 5. strip returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). " hello ".strip() # result is 'hello' # 6. Your task is to find out if the string contains: alphanumeric characters any([char.isalnum() for char in S]) # 7. String adjustements width = 20 'HackerRank'.ljust(width,'-') # HackerRank---------- 'HackerRank'.center(width,'-') # -----HackerRank----- 'HackerRank'.rjust(width,'-') # ----------HackerRank # 8. The textwrap module provides two convenient functions: wrap() and fill(). print(textwrap.wrap(string,8)) print(textwrap.fill(string,8)) # 9. Make the first letter uppercase 'name'.capitalize()
true
50b86447072eac47a70ad3e35bb1a285cd5a3619
BTHabib/Lessons
/Lesson 2 Trevot test.py
820
4.21875
4
""" Author: Brandon Habib Date: 1/21/2016 """ #Initializing the array numbers = [] #Initializing A A = 0 #Printing instructions for the user print ("Give me an integer Trevor and then type \"Done\" when you are done. When all is finished I will show you MAGIC!") #A while loop to continue adding numbers to the array while (A != "Done"): A = input ("Give me an integer Trevor --> ") #If statement appending the inputs if (A != "Done"): numbers.append(int(A)) #Initializing the Sum Sum = 0 #Printing updates to the user print ("MAGICING THE NUMBERS FORM THE ARRAY") #For loop to sum the elements in the array numbers and prints number for number in numbers: Sum = Sum + number print (number) #Prints final message and the sum of numbers print ("THIS IS THE MAGICAL SUM " + str(Sum))
true
771de63fb0fd06a32f10e41fd6411f28bd3b985c
mfcarrasco/Python_GIS
/AdvGIS_Course/MyClassPractice.py
720
4.15625
4
class Myclass: var = "This is class variable" def __init__(self, name):# first parameter always self in a class self.name = name def funct(self):#using method and a function within aclass so ALWAYS start with self print "This is method print", self.name foo = Myclass("Malle") #this step is called instantiate. This instance of class assigned to foo. now foo become object print foo.var # no parantheses because it is not an attribute and it is not a method so NO parantheses foo.funct() #need to put parantheses becuase funct is a method; foo is the "self" becuase it has the instance of the class foo1 = Myclass("sara") foo2 = Myclass("bob") foo3 = Myclass ("jeff")
true
13ab27733b3c75d0c5f0c278698b43c3dd04d5a3
haaruhito/PythonExercises
/Day1Question3.py
495
4.125
4
# With a given integral number n, write a program to generate a dictionary that # contains (i, i x i) such that is an integral number between 1 and n (both included). # and then the program should print the dictionary.Suppose the following input is # supplied to the program: 8 # Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} num = int(input("Enter a number: ")) dictionary = {} for i in range (1, num+1): dictionary[i] = i * i print(dictionary)
true
b197f01edc925e63d28fc0a0a4228d64fb3f767d
johannalbino/python
/exercicio_1.py
247
4.21875
4
#exercicio 1 python #Faça um programa que receba a idade do usuário e diga se ele e maior ou menor de idade idade = int(input("Qual a sua idade :")) if idade >= 18: print ("Você é maior de idade!") else: print ("Você é menor de idade!")
false
c142586277e8f59719f324b7c2aea239ecc98680
kmiroshkhin/Python-Problems
/medium_vowelReplacer.py
622
4.21875
4
"""Create a function that replaces all the vowels in a string with a specified character. Examples replace_vowels("the aardvark", "#") ➞ "th# ##rdv#rk" replace_vowels("minnie mouse", "?") ➞ "m?nn?? m??s?" replace_vowels("shakespeare", "*") ➞ "sh*k*sp**r*" """ def replace_vowels(txt,ch): vowels = ['a','e','i','o','u'];replacementlist=[];replacement="" for i in txt: if i in vowels: replacementlist.append(ch) else:replacementlist.append(i) for i in replacementlist: replacement+=i return replacement print(replace_vowels('Eurika!','#'))
true
561b7063ef63e21a32f425e8aa2cd0060d1e3048
kmiroshkhin/Python-Problems
/easy_recursion_Sum.py
353
4.25
4
"""Write a function that finds the sum of the first n natural numbers. Make your function recursive. Examples sum_numbers(5) ➞ 15 // 1 + 2 + 3 + 4 + 5 = 15 sum_numbers(1) ➞ 1 sum_numbers(12) ➞ 78 """ def sum_numbers(n): addition=int() for i in range(1,n+1): addition+=i return addition print(sum_numbers(5))
true
9e4a81ce2ea3628967b2f2194caee577914bd1d8
kmiroshkhin/Python-Problems
/Hard_WhereIsBob.py
650
4.3125
4
"""Write a function that searches a list of names (unsorted) for the name "Bob" and returns the location in the list. If Bob is not in the array, return -1. Examples find_bob(["Jimmy", "Layla", "Bob"]) ➞ 2 find_bob(["Bob", "Layla", "Kaitlyn", "Patricia"]) ➞ 0 find_bob(["Jimmy", "Layla", "James"]) ➞ -1 """ def find_bob(names): counter = -1;encounterBob=False for name in names: if name =='Bob': counter += 1 encounterBob=True break elif name !='Bob': counter += 1 if encounterBob == True: return counter else: return -1
true
3700278b8bb878b60eaaf97e88a321ec53e146d0
erikayi/python-challenge
/PyPoll/main_final.py
2,013
4.21875
4
# Analyze voting poll using data in csv file. # import csv and os. import csv import os # define the location of the data. election_csv = "Resources/election_data.csv" # open the data. with open(election_csv, 'r') as csvfile: election_csv = csv.reader(csvfile) header = next(election_csv) # define the values. vote_count = 0 popular_vote = 0 candidate_dict = {} # find total number of votes cast. for row in election_csv: vote_count += 1 candidate_dict[row[2]] = candidate_dict.get(row[2], 0) + 1 # print the results using print() function. print(f"=========================") print(f'Election Results') print(f'=========================') print(f'Total Votes: {vote_count}') print(f'=========================') # Discover complete list of candidates received the most votes. for candidate, vote in candidate_dict.items(): # Find the percentage of votes that each candidate received. # Find the total number of votes each candidate won. won_candidate = (f'{candidate}: {vote / vote_count * 100:.3f}% ({vote})') print(won_candidate) # Find the winner of the election based on the popular vote. # Use If and greater than function to find who has the most votes to win the election. if vote > popular_vote: winner = candidate # print the results using print() function. print(f'=========================') print(f'Winner: {candidate}') print(f'=========================') # Finalize the script and Export to a .txt. file with results. output_file = os.path.join("Analysis.txt") with open(output_file, "w") as text_file: text_file.write ("Election Results\n") text_file.write ("===========================\n") text_file.write ("Total Votes: {}\n".format(vote_count)) text_file.write ("===========================\n") text_file.write ("{}\n".format(won_candidate)) text_file.write ("===========================\n") text_file.write ("Winner: {}\n".format(candidate))
true
9e7d6229ad3039076757cff1edf336796064b671
Sudhijohn/Python-Learnings
/conditional.py
388
4.1875
4
#Conditional x =6 ''' if x<6: print('This is true') else: print('This is false') ''' #elif Same as Else if color = 'green' ''' if color=='red': print('Color is red') elif color=='yellow': print('Color is yellow') else: print('color is not red or yellow') ''' #Nested if if color == 'green': if x <10: print('Color is Green and number is lessthan 10')
true
5b3eeada4baa5ebf3a774b911e582541cfdd9e5b
Aravind2595/MarchPythonProject
/questions/demo5.py
708
4.125
4
#Create a child class Bus that will inherit all of the variables and methods of Vehicle class? class Vehicle: def setval(self,tyre,type,gear,seat): self.tyre=tyre self.type=type self.gear=gear self.seat=seat def printval(self): print("tyre:",self.tyre) print("Disel or petrol:",self.type) print("gear:",self.gear) print("seat:",self.seat) class Bus(Vehicle): def set(self,company,ac): self.company=company self.ac=ac def print(self): print("company:",self.company) print("A/C or Non A/C:",self.ac) obj=Bus() obj.set("Ashok Leyland","A/C") obj.setval(6,"Diesel",6,32) obj.print() obj.printval()
false
60b2ea5bc3f7100de9f8f05c80dee8b0a803de46
Aravind2595/MarchPythonProject
/Flow controls/demo6.py
235
4.21875
4
#maximum number using elif num1=int(input("Enter the number1")) num2=int(input("Enter the number2")) if(num1>num2): print(num1,"is the highest") elif(num1<num2): print(num2,"is the highest") else: print("numbers are equal")
true
aa97b8e2e82b353ca5f1d3c14c97471b30d12521
Aravind2595/MarchPythonProject
/Flow controls/for loop/demo6.py
237
4.15625
4
#check a given number is prime or not num=int(input("Enter the number")) flag=0 for i in range(2,num): if(num%i==0): flag=1 if(flag>0): print(num," is not a prime number") if(flag==0): print(num,"is a prime number")
true
8a48a24a816b1693e493ddd2795f5f44aa958523
kblicharski/ctci-solutions
/Chapter 1 | Arrays and Strings/1_6_String_Compression.py
2,506
4.375
4
""" Problem: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string 'aabcccccaaa' would become 'a2b1c5a3'. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a-z). Implementation: We can return early if our string is under 3 characters long, because there is no way that compression would benefit it. Otherwise, we need to traverse the string and count the number of consecutive characters, appending them to the list that stores the "tokens" of our compressed string. We then finally join the tokens back into a string and compare the lengths of our compressed string and our original string to determine which should be returned. Because we have to traverse the original string in O(N) time, and then join the compressed string in (worst case, when we have all unique characters) O(2N) time, the total runtime is linear. Efficiency: Time: O(N) Space: O(N) """ def compressed_string(string: str) -> str: """ Compress a string using the counts of its repeated characters, if possible. Args: string (str): The string to be compressed. Returns: str: The compressed string if its size is smaller than the original. Examples: >>> compressed_string('aabcccccaaa') 'a2b1c5a3' >>> compressed_string('abcdd') 'abcdd' """ if len(string) < 3: return string compressed_chars = [] count = 1 for i, c in enumerate(string): try: if c == string[i + 1]: count += 1 else: compressed_chars.append(c) compressed_chars.append(str(count)) count = 1 except IndexError: compressed_chars.append(c) compressed_chars.append(str(count)) compressed_str = ''.join(compressed_chars) if len(compressed_str) < len(string): return compressed_str return string assert compressed_string('') == '' assert compressed_string('a') == 'a' assert compressed_string('aa') == 'aa' assert compressed_string('aaa') == 'a3' assert compressed_string('abc') == 'abc' assert compressed_string('abcdefgh') == 'abcdefgh' assert compressed_string('aabcccccaaa') == 'a2b1c5a3' assert compressed_string('abcdd') == 'abcdd'
true
61a24ed9b8931c925de092f0116f780e253de52e
kblicharski/ctci-solutions
/Chapter 1 | Arrays and Strings/1_8_Zero_Matrix.py
2,826
4.125
4
""" Problem: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. Implementation: My initial, naive approach to the problem was to first find all occurrences of zeros and add their row and column values to two lists. Afterwards, we would check these lists and zero their respective rows and columns. This works well, but we still need to allocate an additional O(M+N) space for the two lists. Instead, we can reduce this to O(1) space by storing this information of what rows and columns to zero in the original matrix itself. This relies on the order in which we check the values in the matrix. When we check a value, we have checked all of the values preceding it -- the values in all previous rows, and all previous columns of that row. We can then set the first row at that column to zero, and the first column at that row to zero. These two slices of our matrix will store the information we need to zero all elements in these rows and columns. After parsing the matrix for zeros, we then just need to parse the first row and the first column. Efficiency: Time: O(MN) Space: O(1) """ from typing import List def zero_matrix(matrix: List[List[int]]) -> None: """ Set the contents of an element's row and column to 0 if the element is 0. Args: matrix (List[List[int]]): The matrix we are zeroing in-place. """ # Find the rows and the columns we want to zero for row, row_slice in enumerate(matrix): for col, value in enumerate(row_slice): if value == 0: matrix[row][0] = 0 matrix[0][col] = 0 # Zero the correct rows for row in range(1, len(matrix)): if matrix[row][0] == 0: for col in range(len(matrix[row])): matrix[row][col] = 0 # Zero the correct columns for col in range(1, len(matrix[0])): if matrix[0][col] == 0: for row in range(len(matrix)): matrix[row][col] = 0 # 1x1 matrix m = [[1]] zero_matrix(m) assert m == [[1]] # 1x1 matrix m = [[0]] zero_matrix(m) assert m == [[0]] # 1x2 matrix m = [[1, 0]] zero_matrix(m) assert m == [[0, 0]] # 2x1 matrix m = [ [1], [0] ] zero_matrix(m) assert m == [ [0], [0] ] # 2x2 matrix m = [ [1, 1], [0, 1] ] zero_matrix(m) assert m == [ [0, 1], [0, 0] ] # 3x3 matrix m = [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ] zero_matrix(m) assert m == [ [1, 0, 1], [0, 0, 0], [1, 0, 1] ] # 4x5 matrix with two zeros m = [ [1, 1, 1, 1, 1], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0] ] zero_matrix(m) assert m == [ [1, 0, 1, 1, 0], [0, 0, 0, 0, 0], [1, 0, 1, 1, 0], [0, 0, 0, 0, 0] ]
true
86fd334b83e5da79823e2858a504ce50d30ac10c
LevanceWam/DPW
/madlib/madlib.py
1,650
4.40625
4
ice_cream = raw_input("What's your flavor: ") print "Tom was walking down the street and wanted a "+ice_cream+" Ice cream cone" friends = ["Monster", "T-Rex", "Jello"] print "Tom's friends wanted Ice cream too and they all had the same amount of money, Tom already has $5.00" for f in friends: print f + ", Has $2.00 on with them." quest = raw_input("Please put in a random word: ") print "The group decided to go to "+quest+ ", for Ice cream" print "At "+quest+" their ultimate Ice cream Sundae cost $25" print "Tom know's that he has money in his piggy bank but can't remember how much was in there but he know's it's no greater than 5" print "Tom's friends also have some extra money but they have $2 less than he has" print "Tom goes and checks the piggy bank" # piggy = raw_input("How much money was in the bank: ") piggy = int(piggy) if 5 < piggy: raw_input("Please check again") else: print "Tom has $" + str(piggy) #function to find how much money toms friends have def all (a): b = a - 2 return b #toms friends money returnb = all(piggy) print "Tom's friends individually have $" + str(returnb) #All of toms friends money all together extra_friend_money_all = int(returnb) * 3 + 6 print extra_friend_money_all tom_money_all = int(piggy) + 5 print "after going counting all of the money Tom had $"+str(tom_money_all)+", and his friends had $"+str(extra_friend_money_all) tom_money_all print "When they added it together it totaled out to $"+str(final_amount) final_amount = int(final_amount) if final_amount < 25 or None: print"Sorry No Ice cream for you" else: print"Yay For Ice Cream"
true
416d8b79e8c1c70a12e0b22bbf444045505e1b97
GabrielNew/Python3-Basics
/World 2/ex037.py
513
4.46875
4
# -*- coding: utf-8 -*- ''' ex037 -> Escreva um programa que leia um número e pergunte ao usuário, para qual base ele quer converter o número. 1 - Binário 2 - Octal e 3 - Hexadecimal ''' num = int(input('Digite um número: ')) print('1 - Binário\n2 - Octal\n3 - Hexadecimal') op = int(input(f'Para qual base deseja transformar o {num}?')) if op == 1: print(f'{bin(num)}') elif op == 2: print(f'{oct(num)}') elif op == 3: print(f'{hex(num)}') else: print('Opção Inválida...')
false
f83dcadf559443152cf57962e83c4337e82928c6
3116005131/pythone_course
/currency_converter_v1.0.py
946
4.25
4
""" 作者:段浩彬 功能:货币兑换 版本:1.0 日期:2019/3/21 """ # def convert_currency(im, er): # """ # 汇率兑换函数 # """ # out = im * er # return out def main(): """ 主函数 """ # 汇率 USD_VS_RMB = 6.77 # 带单位的货币输入 currency_str_value = input("请输入带单位的货币金额") unit = currency_str_value[-3:] if unit == "CNY": exchange_rate = USD_VS_RMB elif unit == "USD": exchange_rate = 1 / USD_VS_RMB else: exchange_rate = -1 if exchange_rate != -1: in_money = eval(currency_str_value[:-3]) # 使用lambda定义函数 convert_currency = lambda x: x * exchange_rate out_money = convert_currency(in_money) print('转换后的金额', out_money) else: print('不支持该种货币') if __name__ == '__main__': main()
false
9d9b4d12ab4445af1644d1f29f7dda9c6cfbe32e
spanneerselvam/Marauders-Map
/marauders_map.py
1,750
4.25
4
print("Messers Moony, Wormtail, Padfoot, and Prongs") print("Are Proud to Present: The Marauders Map") print() print("You are fortunate enough to stuble upon this map. Press 'Enter' to continue.") input() name = input("Enter your name: ") input2 = input("Enter your house (gryffindor, ravenclaw, hufflepuff, slytherin): ") if input2 == "gryffindor": print("Ahh, a fellow gryffindor! The best house in Hogwarts and where the brave at heart dwell! Welcome {}!".format(name)) print("Enjoy and remember when your done to give it a tap and say 'Mischief Managed' otherwise anyone can read it!") print("Cheers, Mates!") if input2 == "ravenclaw": print("Oh look what we have here, a snobby Ravenclaw... Praised for your cleverness and wit... Hahaha.") print("Mr. Padfoot wonders if you are all so clever then why was that prat Gilderoy Lockhart a Ravenclaw.") print("Mr. Prongs agrees with Padfoot and believes that you should go on and read a book instead.") if input2 == "hufflepuff": print("Congratulations {}!".format(name)) print("You have come across the mobile version of 'Hogwarts, A History' by Bathilda Bagshot. This is a book concerning Hogwarts School of Witchcraft and Wizardry and its history. Enjoy at your pleasure.") if input2 == "slytherin": print("Mr. Moony presents his compliments to {} and begs {} to keep their abnormally large nose out of other people's business".format(name,name)) print("Mr. Prongs agrees with Mr. Moony and would like to add that {} is an ugly git".format(name)) print("Mr. Padfoot would like to register his astonishment that an idiot like that was even accepted to Hogwarts") print("Mr. Wormtail bids {} good day, and advises {} to wash their hair, the slime-ball".format(name, name))
true
b5ec6c31ea7a394cbbdf7e2b8a0ea42640d8b1d5
nagendrakamath/1stpython
/encapsulation.py
715
4.15625
4
calculation_to_unit = 24 name_of_unit ="hours" user_input = input("please enter number of days\n") def days_to_units(num_of_days): return (f"{num_of_days} days are {num_of_days * calculation_to_unit} {name_of_unit}") def validate(): try: user_input_number = int(user_input) if user_input_number > 0: my_var = days_to_units(user_input_number) print (f"your input is {user_input} days") print(my_var) elif user_input_number == 0: print ("you have enterd Zero, Please correct it") else: print ("you have enterd -ve number, Please correct it") except: print ("Please enter only +ve number") validate()
true
2836cf6c0a9351a3687a244b6034eb760cc2f5ba
pya/PyNS
/pyns/operators/dif_x.py
636
4.1875
4
""" Returns runnig difference in "x" direction of the matrix sent as parameter. Returning matrix will have one element less in "x" direction. Note: Difference is NOT derivative. To find a derivative, you should divide difference with a proper array with distances between elements! """ # ============================================================================= def dif_x(a): # ----------------------------------------------------------------------------- """ Args: a: matrix for differencing. Returns: Matrix with differenced values. """ return (a[1:,:,:] - a[:-1,:,:]) # end of function
true
494cc5b447f85b112110e34dcc16e156f7ff4c2b
raveendradatascience/PYTHON
/Dev_folder/assn85.py
1,334
4.3125
4
#*********************************************************************************# # 8.5 Open the file mbox-short.txt and read it line by line. When you find a line # # that starts with 'From ' like the following line: # # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # # You will parse the From line using split() and print out the second word in # # the line (i.e. the entire address of the person who sent the message). # # Then print out a count at the endself. # # Hint: make sure not to include the lines that start with 'From:'. # # You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt # # ***********************************************************************************# fname = raw_input("Enter file name: ") # prompts use to enter file name string fh = open(fname) # opens and reads the file name. count = 0 # initialising counter for line in fh: # looping line by line nospln=line.rstrip() # stripping \n character if nospln.startswith("From ") : # finding required line splitwd=nospln.split() # splitting words print splitwd[1] # printing second word count=count+1 print "There were", count, "lines in the file with From as the first word"
true
652e6e20d73239960e48d9dea1ad75ce3a802cca
KaustubhDhokte/python-code-snippets
/deep&shallowCopy.py
1,562
4.4375
4
''' Two types of copy operations are applied to container objects such as lists and dictionaries: a shallow copy and a deep copy. A shallow copy creates a new object but populates it with references to the items contained in the original object. ''' a = [1, 2, [8, 9], 5] print id(a) # Output: 47839472 b = list(a) print b # Output: [1, 2, [8, 9], 5] print id(b) # Output: 47858872 # Object Id changes a[0] = 100 print a # Output: [100, 2, [8, 9], 5] print b # Output: [1, 2, [8, 9], 5] a.append(30) print a # Output: [100, 2, [8, 9], 5, 30] print b # Output: [1, 2, [8, 9], 5] a[1] += 3 print a # Output: [100, 5, [8, 9], 5, 30] print b # Output: [1, 2, [8, 9], 5] a[2][1] = 10 print a # Output: [100, 5, [8, 10], 5, 30] print b # Output: [1, 2, [8, 10], 5] b[2][0] = 11 print a # Output: [100, 5, [11, 10], 5, 30] print b # Output: [1, 2, [11, 10], 5] ''' In this case, a and b are separate list objects, but the elements they contain are shared. Therefore, a modification to one of the elements of a also modifies an element of b, as shown. ''' ''' A deep copy creates a new object and recursively copies all the objects it contains. There is no built-in operation to create deep copies of objects. However, the copy.deepcopy() function in the standard library can be used. ''' import copy a = [1, 2, [3, 4]] b = copy.deepcopy(a) print id(a) # Output: 44433160 print id(b) # Output: 44394576 a[2][1] = 6 print a # Output: [1, 2, [3, 6]] print b # Output: [1, 2, [3, 4]] b[2][0] = 8 print a # Output: [1, 2, [3, 6]] print b # Output: [1, 2, [8, 4]]
true
11692778a4a716519e08e49f5a129ab743542f7d
KaustubhDhokte/python-code-snippets
/closures_TODO.py
475
4.125
4
# https://realpython.com/blog/python/inner-functions-what-are-they-good-for/ ''' def generate_power(number): """ Examples of use: >>> raise_two = generate_power(2) >>> raise_three = generate_power(3) >>> print(raise_two(7)) 128 >>> print(raise_three(5)) 243 """ # define the inner function ... def nth_power(power): return number ** power # ... which is returned by the factory function return nth_power '''
true
444297ec4f122e9e9419dbc4ea56e5d9752bfec3
KaustubhDhokte/python-code-snippets
/metaclasses_TODO.py
2,756
4.3125
4
# https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python ''' A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass. ''' ''' When the class statement is executed, Python first executes the body of the class statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the __metaclass__ attribute of the class-to-be (if any) or the __metaclass__ global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it. ''' ''' >>> class MyShinyClass(object): ... pass can be created manually this way: >>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object >>> print(MyShinyClass) <class '__main__.MyShinyClass'> >>> print(MyShinyClass()) # create an instance with the class <__main__.MyShinyClass object at 0x8997cec> You'll notice that we use "MyShinyClass" as the name of the class and as the variable to hold the class reference. They can be different, but there is no reason to complicate things. type accepts a dictionary to define the attributes of the class. So: >>> class Foo(object): ... bar = True Can be translated to: >>> Foo = type('Foo', (), {'bar':True}) And used as a normal class: >>> print(Foo) <class '__main__.Foo'> >>> print(Foo.bar) True >>> f = Foo() >>> print(f) <__main__.Foo object at 0x8a9b84c> >>> print(f.bar) True And of course, you can inherit from it, so: >>> class FooChild(Foo): ... pass would be: >>> FooChild = type('FooChild', (Foo,), {}) >>> print(FooChild) <class '__main__.FooChild'> >>> print(FooChild.bar) # bar is inherited from Foo True Eventually you'll want to add methods to your class. Just define a function with the proper signature and assign it as an attribute. >>> def echo_bar(self): ... print(self.bar) ... >>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar}) >>> hasattr(Foo, 'echo_bar') False >>> hasattr(FooChild, 'echo_bar') True >>> my_foo = FooChild() >>> my_foo.echo_bar() True And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object. >>> def echo_bar_more(self): ... print('yet another method') ... >>> FooChild.echo_bar_more = echo_bar_more >>> hasattr(FooChild, 'echo_bar_more') True You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically. This is what Python does when you use the keyword class, and it does so by using a metaclass. '''
true
5193aded8a6ba9ce63f4104567bd714ab6b19887
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/caesar_cipher.py
2,421
4.53125
5
# Option 1 Difficulty Level: Elementary: One of the first known # examples of encryption was used by Julius Caesar. Caesar needed # to provide written instructions to his generals, but he didn’t want # his enemies to learn his plans if the message slipped into their hands. # As result, he developed what later became known as the Caesar Cipher. # The idea behind this cipher is simple (and as a result, it provides # no protection against modern code breaking techniques). Each letter in the # original # message is shifted by 3 places. As a result, A becomes D, # B becomes E, C becomes F, D becomes G, etc. The last three letters in the alphabet # are wrapped around to the beginning: X becomes A, Y becomes B and Z becomes C. # Non-letter characters are not modified by the cipher. Write a program that # implements a Caesar cipher. Allow the user to supply the message and the # shift amount, and then display the shifted message. Ensure that your program # encodes both uppercase and lowercase letters. Your program should also support # negative shift values so that it can be used both to encode messages and decode # messages. (please see the attached image for more detail) import string from itertools import chain def caesar_cipher(): message = input("Please enter the message to code: ") shift = int(input("Please enter the shift to code: ")) alpha_low = list(string.ascii_lowercase) alpha_upp = list(string.ascii_uppercase) alpha_low.extend(alpha_upp) if shift >= 0: low_a, low_z, upp_a, upp_z = ord("a") + shift, ord("z") + 1, ord("A") + shift, ord("Z") + 1 code_low = list(chain(range(low_a, low_z), range(ord("a"), low_a))) code_upp = list(chain(range(upp_a, upp_z), range(ord("A"), upp_a))) else: low_a, low_z, upp_a, upp_z = ord("a"), ord("z") + shift + 1, ord("A"), ord("Z") + shift + 1 code_low = list(chain(range(low_z, ord("z") + 1), range(low_a, low_z))) code_upp = list(chain(range(upp_z, ord("Z") + 1), range(upp_a, upp_z))) print(code_low) code_low.extend(code_upp) code_iter = dict(zip(alpha_low, code_low)) print(code_iter) coded_list = [] for i in message: if ("a" <= i <= "z") or ("A" <= i <= "Z"): coded_list.append(chr(code_iter.get(i))) else: coded_list.append(i) coded_message = ''.join(coded_list) print(coded_message) caesar_cipher()
true
f88cd2ec59b884787116eb60c476374990109b9b
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/unique_characters.py
1,124
4.40625
4
# Create a program that determines and displays the number of unique characters in a string entered by the user. # For example, Hello, World! has 10 unique characters while zzz has only one unique character. Use a dictionary or # set to solve this problem def unique_characters(text): # Solution using dictionary dictionary_solution(text) # Solution using set set_solution(text) def dictionary_solution(text): # Declare an empty dictionary my_dict = {} # Fill the dictionary with unique characters for i in text: my_dict.update({i: 0}) # Print unique characters in an ascendant order list print(f"Solution using a dictionary: {sorted(list(my_dict.keys()))} {len(my_dict)} unique characters") def set_solution(text): # Convert test to set to get unique characters solution1 = set(text) # Print unique characters in an ascendant order list print(f"Solution using a set: \t\t {sorted(list(solution1))} {len(solution1)} unique characters") if __name__ == '__main__': unique_characters(input("Please enter the sentence to get unique characters: "))
true
34e456552f63f881b56f9e06e924cbc6c4528d4b
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/license_plate.py
1,408
4.59375
5
#License plate #Option 1 Difficulty Level: Elementary: In a particular jurisdiction, # older license plates consist of three uppercase letters followed by three numbers. # When all of the license plates following that pattern had been used, the format was # changed to four numbers followed by three uppercase #letters. Write a program that begins by reading a string of characters from the user. # Then your program should display a message indicating whether the characters # are valid for an older style license plate or a newer style license plate. # Your program should display an appropriate message if the string entered by the user # is not valid for either style of license plate. def valid_plate(): plate_input=input("Please enter the license plate: ") if len(plate_input)==6: letters, numbers=plate_input[:3], plate_input[3:] valid_style(letters, numbers, plate_input) elif len(plate_input)==7: numbers, letters = plate_input[:4], plate_input[4:] valid_style(letters, numbers, plate_input) else: print(f"The plate {plate_input} is not a valid stYle for a license plate") def valid_style(letters, numbers, plate_input): if letters.isupper() and numbers.isdigit(): print(f"Plate {plate_input} is an valid style of plate") else: print(f"The plate {plate_input} is not a valid stYle for a license plate") valid_plate()
true
b01a758c609d2701d59a74f7bf019c7c4bd9f608
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/calc.py
1,676
4.53125
5
# For this exercise I want you to write a function (calc) that expects a single argument -a string containing # a simple math expression in prefix notation- with an operators and two numbers, your program will parse the input # and will produce the appropriate output. For our purposes is enough to handle the six basic arithmetic operations # in Python: addition, substraction, multiplication, division(/), modulus(%), and exponentiation(**). The normal Python # math rules should work, such that division always result in a floating-point number. # We will assume for our purposes that the argument will only contain one of our six operators and two valid numbers. # But wait there is a catch -or a hint, if you prefer: you should implement each of the operations in a single function- # and you shouldn't use an if statement to decide which function should be run. Another hint: look at the operator module # whose functions implements many of the Python's operators def calc(text): op, num1, num2 = text.split() oper = {"+": add, "-": sub, "*": mul, "/": div, "%": mod, "**": pow} first=int(num1) second=int(num2) return oper[op](first,second) # Another option is just to reorder the expresion and evaluate it def calc2(text): op, num1, num2 = text.split() return eval(num1+op+num2) def add(num1, num2): return num1 + num2 def sub(num1, num2): return num1 - num2 def mul(num1, num2): return num1 * num2 def div(num1, num2): return num1 / num2 def mod(num1, num2): return num1 % num2 def pow(num1, num2): return num1 ** num2 if __name__ == '__main__': print(calc("/ 10 5")) print(calc2("/ 10 5"))
true
76fddfefedace4aca36548cbc3b6f2ab6f9d3188
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/reverse_lines.py
814
4.3125
4
# In this function, we do a basic version of this idea. The function takes two arguments: the names of the input # file (to be read from) and the output file (which will be created). def reverse_lines(orig_f, targ_f): # Read original file storing one line at the time with open(orig_f, mode="r") as f_input: for line in f_input: # Reverse the line and adding new line at the end line = line.rstrip()[::-1] + "\n" # Write every reversed line to a new target file with open(targ_f, mode="a") as f_output: f_output.write(line) if __name__ == '__main__': # Declaring the names of the files to be send as parameters in the function orig_file = "orig_f.txt" targ_file = "targ_f.txt" reverse_lines(orig_file, targ_file)
true
b8ceabe1af9f24f1acb694641f32f61c05ca34a6
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/dice_simulation.py
2,603
4.53125
5
# In this exercise you will simulate 1,000 rolls of two dice. Begin by writing a function that simulates rolling # a pair of six-sided dice. Your function will not take any parameters. It will return the total that was rolled on # two dice as its only result. # Write a main program that uses your function to simulate rolling two six-sided dice 1,000 times. As your program runs, # it should count the number of times that each total occurs. Then it should display a table that summarizes this data. # Express the frequency for each total as a percentage of the total number of rolls. Your program should also display # the percentage expected by probability theory for each total. Sample output is shown below from random import randint def dice_simulation(): # Create a blank dictionary my_dict = {} # Fill the dictionary with the possible total as keys for i in range(2, 13): my_dict.update({str(i): 0}) # Initialize variables to count the occurrences of each total v_2, v_3, v_4, v_5, v_6, v_7, v_8, v_9, v_10, v_11, v_12 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 # Simulate 2 dices rolling for i in range(1000): dice1 = randint(1, 6) dice2 = randint(1, 6) # Increase each variable according to the total obtained if dice1 + dice2 == 2: v_2 += 1 if dice1 + dice2 == 3: v_3 += 1 if dice1 + dice2 == 4: v_4 += 1 if dice1 + dice2 == 5: v_5 += 1 if dice1 + dice2 == 6: v_6 += 1 if dice1 + dice2 == 7: v_7 += 1 if dice1 + dice2 == 8: v_8 += 1 if dice1 + dice2 == 9: v_9 += 1 if dice1 + dice2 == 10: v_10 += 1 if dice1 + dice2 == 11: v_11 += 1 if dice1 + dice2 == 12: v_12 += 1 # Filling the dictionary with a list as value my_dict.update({"2": [v_2 / 1000 * 100, 2.78]}) my_dict.update({"3": [v_3 / 1000 * 100, 5.56]}) my_dict.update({"4": [v_4 / 1000 * 100, 8.33]}) my_dict.update({"5": [v_5 / 1000 * 100, 11.11]}) my_dict.update({"6": [v_6 / 1000 * 100, 13.89]}) my_dict.update({"7": [v_7 / 1000 * 100, 16.67]}) my_dict.update({"8": [v_8 / 1000 * 100, 13.89]}) my_dict.update({"9": [v_9 / 1000 * 100, 11.11]}) my_dict.update({"10": [v_10 / 1000 * 100, 8.33]}) my_dict.update({"11": [v_11 / 1000 * 100, 5.56]}) my_dict.update({"12": [v_12 / 1000 * 100, 2.78]}) # Print the table print(f"Total\tSimulated\tExpected") print(f"\t\tPercent\t\tPercent") for k, v in my_dict.items(): print(f"{k}\t\t{format(v[0], '.2f')}\t\t{v[1]}") if __name__ == '__main__': dice_simulation()
true
d52add20d1d0518c2c3fb82ce15f9015ce91890f
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/vowel_consonant.py
856
4.46875
4
# Option 2: Difficulty Level: Pre-Intermediate: In this exercise # you will create a program that reads a letter of the alphabet from the user. # If the user enters a, e, i, o or u then your program should display a message # indicating that the entered letter is a vowel. If the user enters y # then your program should display a message indicating that sometimes y is a vowel, # and sometimes y is a consonant. Otherwise your program should display a message # indicating that the letter is a consonant. def vowel_consonant(str): if str == "a" or str == "e" or str == "i" or str == "o" or str == "u": print("The entered letter is a vowel") elif str == "y": print("Sometimes is a vowel, and sometimes is a consonant") else: print("The entered letter is a consonant") vowel_consonant(input("Please enter a letter"))
true
f52eb17ccbdecf837794acd87b21ee422bbdf6c5
ak-alam/Python_Problem_Solving
/secondLargestNumberFromList/main.py
286
4.21875
4
''' For a list, find the second largest number in the list. ''' lst = [1,3,9,3,7,4,5] largest = lst[0] sec_largest = lst[0] for i in lst: if i > largest: largest = sec_largest largest = i elif i > sec_largest: sec_largest = i print(f'Largest Number: {sec_largest}')
true
9167003e750f0216857d8dab3aa3424231a33e11
jiezheng5/PythonFundamentals
/app5-DatabaseAppUsing-TinkerSqlite/app5_backend.py
2,261
4.375
4
""" A program that stores the book information: Title, Author Year, ISBN User can: view all records search an entry add entry update entry delete close https://www.udemy.com/the-python-mega-course/learn/v4/t/lecture/4775396?start=0 """ from tkinter import * import sqlite3 import numpy as np import itertools as it #import app5_frontend def create(): conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTs books \ (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)") conn.commit() conn.close() def insert(title, author, year, isbn): conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("INSERT INTO books VALUES (NULL, ?,?,?,?)", (title, author, year, isbn)) conn.commit() conn.close() def update(id, title, author, year, isbn): conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("UPDATE books SET title=?, author=?, year=?, isbn=? WHERE id=?", \ (title, author, year, isbn, id)) conn.commit() conn.close() def delete(id): conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("DELETE FROM books WHERE id=?", (id,)) conn.commit() conn.close() def search(title='', author='', year='', isbn=''): conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("SELECT * FROM books WHERE title=? OR author=? OR year=? OR isbn=?", \ (title,author,year, isbn)) selected_rows=cur.fetchall() #conn.commit() conn.close() return selected_rows def view_table(): conn=sqlite3.connect("books.db") cur=conn.cursor() cur.execute("SELECT * FROM books") rows=cur.fetchall() #conn.commit() conn.close() return rows create() # insert('The Earch', 'John Smith', 1980, 908223214) # insert('The Sun', 'Joe 3th', 1976, 908223214) # update(112,'The Moon', 'Brian 4th', 1917, 908223214 ) # print(view_table()) # for i in it.chain(range(0, 110), range(120, 150)): # #for i in range(0,112):#np.arange(40,100):#range(30): # delete(i) # print(view_table()) # print('\n search result: \n' , search(year='1980')) #print('test running of backend.py in importing') #print('\nTable: \n', view_table()) #print('\n search result: \n' , search(author='John Smith')) #print('test')
true
30bb3921d340b257331bdc7a5bc747fbd244055d
Ediel96/platzi-python
/conversor_de_string.py
237
4.15625
4
nombre = "hamilton" print(nombre.upper()) print(nombre.capitalize()) print(nombre.strip()) print(nombre.lower()) print(nombre.replace('o','a')) print(nombre[0]) print(len(nombre)) print(nombre[0:5]) print(nombre[3:]) print(nombre[:5])
false
dde99e6ba6b6a333681bef405e8af0524f576e94
gaozejing/test2
/列表.py
844
4.125
4
#建立一个空姓名列表 NameList = [] print("Enter 5 names:") #在姓名列表内添加姓名 for i in range(5): name = input() NameList.append(name) #输出姓名列表中的姓名 print("The names are ",end="") for name in NameList: print(name+" ",end="") print() #对姓名列表进行排序操作,且不改变原来的列表 NameListCopy = NameList[:] NameListCopy.sort() print("NameList:",end="") print(NameList) print("NameList sort:",end="") print(NameListCopy) #输出原列表中的第三个姓名 print("The third name is: "+NameList[2]) #根据输入对原列表中的其中一个姓名进行替换 ReplayNameNum = int(input("Replace one name.Which one?(1-5):")) ReplayName = input("New name: ") NameList[ReplayNameNum-1] = ReplayName print("The names are ",end="") for name in NameList: print(name+" ",end="")
false
5f7098de49958aa36f2f76363f40da4302140291
gaozejing/test2
/BankAccount(类、属性、方法、对象).py
1,540
4.21875
4
class BankAccount: #属性账户名、账户号、账户余额 def __init__(self): self.account_name = "name" self.account_num = "000000" self.account_balance = 0 def __str__(self): msg1 = "Your account name: " + self.account_name msg2 = "Your account number: " + self.account_num msg3 = "Your account balance: " +str(self.account_balance) msg = msg1 +'\n'+ msg2+ '\n' + msg3+ '\n' return msg #计算余额 def banlance(self,cost): self.account_balance = self.account_balance + cost return self.account_balance #存钱 def save(self,cost): return cost #取钱 def draw(self,cost): cost = -cost return cost #子类包含利率 class InterestAccount(BankAccount): def __init__(self): BankAccount.__init__(self) self.interest = 0 #计算算上利率后的余额 def addInterest(self,addinterest): self.interest = addinterest self.account_balance = self.account_balance*(1+self.interest) print(self.account_balance) myAccount = BankAccount() print(myAccount) myAccount.account_name = "Vicky" myAccount.account_num = "123456" myAccount.account_balance = 1000 print(myAccount) cost1 = myAccount.save(100) print(myAccount.banlance(cost1)) cost2 = myAccount.draw(200) print(myAccount.banlance(cost2)) print(myAccount) myAccount = InterestAccount() cost1 = myAccount.save(100) print(myAccount.banlance(cost1)) myAccount.addInterest(0.1) print(myAccount)
false
a521ef2d94a766a9dfbfcc33fa6145537855af9e
Rekapi/PyProblemSolving
/PS02.py
2,898
4.1875
4
# Continue from __future__ import print_function import sys import math import textwrap import http.client # 41. how to Sum two given numbers and return a number (functions) def summation(x, y): suma = x + y if suma in range(15, 20): return 20 else: return suma print(summation(2, 2)) # 42. how to add two objects if both objects are an integer type def add_number(a, b): if not (isinstance(a, int) and isinstance(b, int)): raise TypeError("Must be Integer") return a + b print(add_number(1, 1)) # 43. how to display name, age, address in three different lines def personal_detail(): name, age = "mahmoud", 20 address = "El Shrouk city " print("Name : {}\nage: {}\naddress: {}".format(name, age, address)) personal_detail() # 44. how to solve quadratic equation def solve_eq(a, b, c): y = b ** 2 - 4 * a * c z = 2 * a x1 = (-b + (math.sqrt(y))) x2 = (-b - (math.sqrt(y))) return x1 / z, x2 / z """a1 = float(input("The value of a : ")) b1 = float(input("The value of b : ")) c1 = float(input("The value of c : "))""" print("(x1, x2) =", solve_eq(1, 5, 6)) # 45. how to calculate the future value of rate of interest and a number of years # 46. how to calculate the distance between two points p1 = [4, 0] p2 = [6, 8] distance = math.sqrt(((p1[0] - p2[0]) ** 2 + ((p1[1] - p2[1]) ** 2))) print(distance) # 47. check if a file exists # 48. check if python version is 64 or 32 # 49. check the os name, platform and release information # 50. how to find the location of python site package directory # 51. how to call an external command # 52. how to get path and name of a file that currently executing in python # 53. how to find out the number of CPUs # 54. how to convert strings to float or int n = "244.3" print(float(n)) print(int(float(n))) # 55. how to print stderr def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) eprint("abc", "efg", "xyz", sep="__") # 56. how to sort counter by value # 57. converts height in feet and inches to centimeters # 58. calculate the hypotenuse of a right angled triangle # 59. how to get file creation & modification date times # 60. calculate body mass index # 61. converts seconds to day, hour, minutes and seconds # 62. get a list of built in modules module_name = ', '.join(sorted(sys.builtin_module_names)) print(textwrap.fill(module_name, width=70)) # 63. how to find ASCII value of a character # 64. remove the first item of a list # 65. how to read the contents of an URL conn = http.client.HTTPConnection("www.google.com") conn.request("GET", "/") result = conn.getresponse() contents = result.read() print(contents) # 66. how to get the system hostname # 67. how to swap two variables # 68. how to concatenate N strings # 69. how to find file path or directory # 70. how to get the users environment (77 in the PlayList)
true
90aa9b98e719c314488a86b049ba9d220eda47fb
PrtagonistOne/Beetroot_Academy
/lesson_04/task_2.py
815
4.21875
4
def main(): number = input('Enter your phone number here: ') message = phone_validator(number) if message == 'lenght': print('Your number should consist of exactly 10 digits') elif message == 'digits': print('Your number should consist of only numerical chars') elif message == 'valid': print('Your number is valid!') else: print('Something went wrong! Contact developer') def phone_validator(phone_number: str) -> str: """Return tuple(bool and message) if the phone number consist of 10 digits Message specifies the what's wrong with the number provided""" if len(phone_number) < 10: return f'lenght' elif not phone_number.isdigit(): return 'digits' else: return 'valid' if __name__ == '__main__': main()
true
5faa6ec0949f2cc7700a12ead0f83e74265d6bb3
PrtagonistOne/Beetroot_Academy
/lesson_07/task_1.py
704
4.125
4
# Make a program that has some sentence (a string) on input and returns a dict # containing all unique words as keys and the number of occurrences as values. # For testing: # 'Hello, my name is Andrey. Andrey is from Odessa. Andrey currently studies python language at Beetroot Academy in Python for Begginers course. Beetroot Academy is a great place to learn python!' import string raw_text = input('Enter your text here: ') # get rid of punctuation in a raw_string processed_text = raw_text.translate(str.maketrans('', '', string.punctuation)) # count words in a dict words = {} for word in processed_text.split(): word = word.lower() words[word] = words.get(word, 0) + 1 print(words)
true
94204564422e698810bbcad1c30c3faf3fc20833
PrtagonistOne/Beetroot_Academy
/lesson_13/task_1.py
1,157
4.21875
4
# Method overloading. # Create a base class named Animal with a method called talk and then create two subclasses: Dog and Cat, # and make their own implementation of the method talk be different. For instance, Dog’s can be to print ‘woof woof’, # while Cat’s can be to print ‘meow’. # Also, create a simple generic function, which takes as input instance of a Cat or Dog classes and performs talk method on input parameter. class Animal: def __init__(self, name, color) -> None: self.name = name self.color = color def talk(self) -> None: print('Sound') class Dog(Animal): def __init__(self, name, color) -> None: super().__init__(name, color) def talk(self) -> None: print('woof woof') class Cat(Animal): def __init__(self, name, color) -> None: super().__init__(name, color) def talk(self) -> None: print('meow meow') def talk_func(animal: object) -> None: animal.talk() unknown_spicie = Animal('Alien', 'black') dog = Dog('Jack', 'black') cat = Cat('Marty', 'white') talk_func(unknown_spicie) talk_func(dog) talk_func(cat)
true
7c68e814e22c38c69fdd41fc981f8bcfb9153479
Pabitra-26/Problem-Solved
/LeetCode/Flipping_an_image.py
792
4.28125
4
# Problem name: Flipping an image # Description: Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. # To flip an image horizontally means that each row of the image is reversed. # For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. # To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. # For example, inverting [0, 1, 1] results in [1, 0, 0]. class Solution: def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: for i in range(len(A)): A[i].reverse() for j in range(len(A[i])): if(A[i][j]==0): A[i][j]=1 else: A[i][j]=0 return A
true
88433a61b1a4375a5c71b61e8aa900e11a954961
Pabitra-26/Problem-Solved
/Hackerrank/Marc'sCakewalk.py
1,290
4.28125
4
# Problem name: Marc's Cakewalk """ Description: Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and Marc can walk a distance to expend those calories. If Marc has eaten j cupcakes so far, after eating a cupcake with c calories he must walk at least (2^j)*c miles to maintain his weight. Given the individual calorie counts for each of the cupcakes, determine the minimum number of miles Marc must walk to maintain his weight. Note that he can eat the cupcakes in any order. Strategy: Multiply the largest number with smallest power of two. Arrange the array of calories in descending order and multiply each with ascending powers of 2""" import math import os import random import re import sys def marcsCakewalk(calorie): calorie.sort(reverse=True) # descending order s=0 # to calculate sum for i in range(len(calorie)): s+=(calorie[i]*(2**i)) # multiply with increasing powers of 2 return s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) calorie = list(map(int, input().rstrip().split())) result = marcsCakewalk(calorie) fptr.write(str(result) + '\n') fptr.close()
true
254dd8950176dd184ca30efe93188af449d8627b
prateekbhat91/Algorithms
/Heap.py
1,806
4.125
4
""" Building Heaps, Max.Heap, Heapsort implementation @author: Prateek Bhat """ import math """Function returns position of parent of a node""" def parent(i): return int(math.floor((i-1)/2)) """Function returns the position of left child of a node""" def left(i): return int(math.floor((i*2)+1)) """Function returns the position of right child of a node""" def right(i): return int(math.floor((i*2)+2)) """Swapping two items""" def swap(a,b): return b,a """Produce a Max Heap""" def maxheapify(arr, i): largest = i l = left(i) r = right(i) if l<len(arr): if arr[l] > arr[i]: largest = l if r<len(arr): if arr[r] > arr[largest]: largest = r if largest != i: arr[largest], arr[i] = swap(arr[largest], arr[i]) maxheapify(arr, largest) """Build a Max Heap on a list of numbers""" def buildmaxheap(arr): l = int(math.floor((len(arr))/2)) -1 for i in range(l, -1, -1): maxheapify(arr,i) """Returns the height of the heap""" def heapheight(arr): return int(math.floor(math.log(len(arr), 2))) """Insert a number into heap, while maintaining its max heap property""" def insert(arr,i): arr.append(i) buildmaxheap(arr) """Sorts the list into descending order""" def heapsort(arr, sorted): l = len(arr)-1 arr[0], arr[l] = swap(arr[0], arr[l]) sorted.append(arr[l]) del arr[l] if l != 0: maxheapify(arr, 0) heapsort(arr, sorted) if __name__ == "__main__": print "Enter the elements of array separated with space" s = raw_input() arr = map(int, s.split()) print arr buildmaxheap(arr) print arr print "Heap Height =",heapheight(arr) insert(arr,23) print arr sorted = [] heapsort(arr, sorted) print sorted
false
fd7c6633a7d1479b223fa8ce8f9e2cf5a05d326c
Pancc123/python_learning
/base_practice/quit.py
475
4.21875
4
pizza='' message='\nplease choose a ingredients on pizza:' message+="\nplease input 'quit' to stop" while pizza != 'quit': pizza=input(message) if pizza != 'quit': print(pizza) message='How old are you ?' age='' while True: age=input(message) if int(age)<3: print('you can look the movie for free.') elif int(age)<=12: print('you need pay 10 dollars for the movie') else: print('you need pay 15 dollars for the movie') if age =='quit': break
true
c74ff911b9ee2da78543d23f131934fcff166f4e
alehpineda/bitesofpy
/Bite_15/enumerate_data.py
1,061
4.1875
4
""" Iterate over the given names and countries lists, printing them prepending the number of the loop (starting at 1). Here is the output you need to deliver: 1. Julian Australia 2. Bob Spain 3. PyBites Global 4. Dante Argentina 5. Martin USA 6. Rodolfo Mexico Notice that the 2nd column should have a fixed width of 11 chars, so between Julian and Australia there are 5 spaces, between Bob and Spain, there are 8. This column should also be aligned to the left. Ideally you use only one for loop, but that is not a requirement. Good luck and keep calm and code in Python! """ names = "Julian Bob PyBites Dante Martin Rodolfo".split() countries = "Australia Spain Global Argentina USA Mexico".split() def enumerate_names_countries(): """Outputs: 1. Julian Australia 2. Bob Spain 3. PyBites Global 4. Dante Argentina 5. Martin USA 6. Rodolfo Mexico""" c = 1 for i, j in zip(names, countries): print("{}. ".format(c) + i + " " * (11 - len(i)) + j) c += 1
true
e9220e9906b453816143716ec56a5f26cd294959
alehpineda/bitesofpy
/159/calculator.py
733
4.125
4
import operator CALCULATIONS = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, } def simple_calculator(calculation): """Receives 'calculation' and returns the calculated result, Examples - input -> output: '2 * 3' -> 6 '2 + 6' -> 8 Support +, -, * and /, use "true" division (so 2/3 is .66 rather than 0) Make sure you convert both numbers to ints. If bad data is passed in, raise a ValueError. """ try: num1, sign, num2 = calculation.split() return CALCULATIONS[sign](int(num1), int(num2)) except (ValueError, KeyError, ZeroDivisionError) as error: print(error) raise ValueError
true
22ba385cb0df70b44cb22f6fea070d33db4ecb7a
alehpineda/bitesofpy
/Bite_107/list_comprehensions.py
570
4.15625
4
""" Complete the function below that receives a list of numbers and returns only the even numbers that are > 0 and even (divisible by 2). The challenge here is to use Python's elegant list comprehension feature to return this with one line of code (while writing readable code). """ def filter_positive_even_numbers(numbers): """Receives a list of numbers, and returns a filtered list of only the numbers that are both positive and even (divisible by 2), try to use a list comprehension.""" return [i for i in numbers if i % 2 == 0 and i > 0]
true
1c0617c520da6181d9379cf8e7ba471b8b8a78c6
alehpineda/bitesofpy
/119/xmas.py
913
4.21875
4
def generate_xmas_tree(rows=10): """Generate a xmas tree of stars (*) for given rows (default 10). Each row has row_number*2-1 stars, simple example: for rows=3 the output would be like this (ignore docstring's indentation): * *** *****""" xmas = [] for row in range(1, rows + 1): space = (rows - row) * " " xmas.append(space + (row * 2 - 1) * "*") return "\n".join(xmas) # Pybites solution def generate_xmas_tree1(rows=10): """Generate a xmas tree of stars (*) for given rows (default 10). Each row has row_number*2-1 stars, simple example: for rows=3 the output would be like this (ignore docstring's indentation): * *** *****""" width = rows * 2 output = [] for i in range(1, width + 1, 2): row = "*" * i output.append(row.center(width, " ")) return "\n".join(output)
true
cd70d79780f6305f1feaa9af76346bf3568d5ef5
alehpineda/bitesofpy
/127/ordinal.py
1,286
4.53125
5
def get_ordinal_suffix(number): """Receives a number int and returns it appended with its ordinal suffix, so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc. Rules: https://en.wikipedia.org/wiki/Ordinal_indicator#English - st is used with numbers ending in 1 (e.g. 1st, pronounced first) - nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second) - rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third) - As an exception to the above rules, all the "teen" numbers ending with 11, 12 or 13 use -th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth) - th is used for all other numbers (e.g. 9th, pronounced ninth). """ number = str(number) # create a dictionary with keys 1,2,3 and values st, nd, rd f_123 = dict(zip("1 2 3".split(), "st nd rd".split())) # save the suffix # use get from dict to check if the number ends with 1,2, or 3 if not # save 'th' suffix = f_123.get(number[-1]) or "th" # teen numbers # if the number is 10 or more and the second last is 1 if len(number) > 1 and number[-2] == "1": suffix = "th" # return f-string with number and suffix return f"{number}{suffix}"
true
07fff703625eb01413ea7445b7be39b9c0590681
alehpineda/bitesofpy
/Bite_3/wordvalue.py
2,730
4.21875
4
""" Calculate the dictionary word that would have the most value in Scrabble. There are 3 tasks to complete for this Bite: - First write a function to read in the dictionary.txt file ( = DICTIONARY constant), returning a list of words (note that the words are separated by new lines). - Second write a function that receives a word and calculates its value. Use the scores stored in LETTER_SCORES. Letters that are not in LETTER_SCORES should be omitted (= get a 0 score). With these two pieces in place. - Third write a function that takes a list of words and returns the word with the highest value. Look at the TESTS tab to see what your code needs to pass. Enjoy! """ import os import urllib.request from tempfile import gettempdir # PREWORK TMP = gettempdir() DICTIONARY = os.path.join(TMP, "dictionary.txt") urllib.request.urlretrieve("http://bit.ly/2iQ3dlZ", DICTIONARY) scrabble_scores = [ (1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"), (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z"), ] LETTER_SCORES = { letter: score for score, letters in scrabble_scores for letter in letters.split() } # start coding def load_words(): """load the words dictionary (DICTIONARY constant) into a list and return it""" words = [] # don't read the whole file into memory when you don't have too # files are iterable with open(DICTIONARY) as f: for line in f: line = line.strip() if not line: continue words.append(line) return words def calc_word_value(word): """given a word calculate its value using LETTER_SCORES""" value = [] for char in word: for val, lists in scrabble_scores: if char.lower() in lists.lower().split(): value.append(val) return sum(value) def max_word_value(words=None): """given a list of words return the word with the maximum word value""" if words == None: words = load_words() value_list = [calc_word_value(word) for word in words] return words[value_list.index(max(value_list))] # Pybites solution # START HERE def load_words1(): """load the words dictionary (DICTIONARY constant) into a list and return it""" with open(DICTIONARY) as f: return [word.strip() for word in f.read().split()] def calc_word_value1(word): """given a word calculate its value using LETTER_SCORES""" return sum(LETTER_SCORES.get(char.upper(), 0) for char in word) def max_word_value1(words=None): """given a list of words return the word with the maximum word value""" if words is None: words = load_words() return max(words, key=calc_word_value)
true
c1a03320e99ded66b6d47084423527e367ed43c8
Innanov/PYTHON
/Area_of_rectangle.py
282
4.1875
4
# By INNAN Nouhaila # Compute the area of a rectangle, given its width and height. width = 5 height = 9 # Rectangle area formula area = width * height print("A rectangle " + str(width) + " inches wide and " + str(height) + " inches high has an area of " + str(area) + " square inches.")
true
05abc4d61d16c63496659697c9417c24bf27fd75
asdcxzqwe2/bill-splitter
/main.py
2,182
4.125
4
import random class BillSplitter: def __init__(self, n_of_friends): self.n_of_friends = n_of_friends self.friends_dictionary = {} self.total_bill = None self.lucky = None def friends_name(self): print("\nEnter the name of every friend (including you), " "each on a new line:") i = 0 while i != self.n_of_friends: name = input() self.friends_dictionary[name] = 0 i += 1 self.total_invoice_value(i) self.who_is_lucky() print(f"\n{self.friends_dictionary}") def total_invoice_value(self, number_of_friends): self.total_bill = int(input("\nEnter the total bill value:\n")) cost_for_one = round(self.total_bill / number_of_friends, 2) for i in self.friends_dictionary: self.friends_dictionary[i] = round(cost_for_one, 2) def who_is_lucky(self): self.lucky = input('\nDo you want to use the "Who is lucky?" ' 'feature? Write Yes/No:\n') if self.lucky == "Yes": name = random.choice(list(self.friends_dictionary.keys())) self.friends_dictionary[name] = 0 for i in self.friends_dictionary: if i != name: self.friends_dictionary[i] \ = round(self.total_bill / (len(self.friends_dictionary) - 1), 2) print(f"\n{name} is the lucky one!") elif self.lucky == "No": for i in self.friends_dictionary: self.friends_dictionary[i] \ = round(self.total_bill / len(self.friends_dictionary), 2) print("\nNo one is going to be lucky") if __name__ == '__main__': number = int(input("Enter the number of friends " "joining (including you):\n")) try: assert number > 0 except Exception: print("\nNo one is joining for the party") else: person = BillSplitter(number) person.friends_name()
false
bf2deeb289ddb3539008fcf4312d09921fc8d477
Ratna04priya/-Python-worked-problems-
/prob_-_soln/age_finder.py
359
4.21875
4
# Gives the age from datetime import date def calculate_age(dtob): today = date.today() return today.year - dtob.year - ((today.month, today.day) < (dtob.month, dtob.day)) a= int(input("Enter the year of birth : ")) b= int(input("Enter the month of birth : ")) c= int(input("Enter the date of birth : ")) print(calculate_age(date(a,b,c)))
true
c88ad612ba91849583a1fa1355343acd248f74ea
m0rtal/GeekBrains
/algorythms/lesson6/task1.py
1,262
4.1875
4
""" 1. Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Примечания: a. алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных, b. постарайтесь сделать алгоритм умнее, но помните, что у вас должна остаться сортировка пузырьком. Улучшенные версии сортировки, например, расчёской, шейкерная и другие в зачёт не идут. """ from random import shuffle def bubble_sort(arr): n, t = 1, True size = len(arr) while t: t = False for i in range(size - n): if arr[i] < arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] t = True n += 1 array = [i for i in range(-100, 100)] shuffle(array) print(array) bubble_sort(array) print(array)
false
b8cd317c831848b1d33ba51ad96ec0acc80c1272
poly451/Tutorials
/Instance vs Class Variables/dunder classes (iter, next).py
1,819
4.3125
4
# ------------------------------------------------- # clas Car # ------------------------------------------------- class Car: def __init__(self, name, tires, seats): self.name = name self.tires = tires self.seats = seats def print_car(self): s = "name: {}, tires: {}, seats: {}".format(self.name, self.tires, self.seats) print(s) # ------------------------------------------------- # clas Cars # ------------------------------------------------- class Cars: def __init__(self): self.cars = [] self.current = 0 def add_car(self, name, tires, seats): new_car = Car(name, tires, seats) self.cars.append(new_car) def print_car(self): print("Number of cars:", len(self.cars)) print("-" * 30) for elem in self.cars: elem.print_car() def __len__(self): return len(self.cars) def __repr__(self): s = "" for elem in self.cars: s += "{}\n".format(elem.print_string()) return(s.strip()) def __iter__(self): return self def __next__(self): print("current:", self.current) try: item = self.cars[self.current] except IndexError: self.current = 0 raise StopIteration() self.current += 1 return item # ************************************************* # mycars = Cars() # mycars.add_car(name="ford", tires=4, seats=4) # mycars.add_car(name="parsche", tires=4, seats=4) # mycars.print_car() mycars = Cars() mycars.add_car(name="ford", tires=4, seats=4) mycars.add_car(name="parsche", tires=4, seats=2) print("You have {} cars.".format(len(mycars))) print("=" * 40) for a_car in mycars: a_car.print_car()
true
a9036924ef986718c083163b1dff30880ad8d108
orkunkarag/py-oop-tutorial
/oop-py-code/oop-python-main.py
696
4.15625
4
# Object Oriented Programming ''' def hello(): print("hello") x = 1 print(type(hello)) ''' ''' string = "hello" print(string.upper()) ''' #creating class class Dog: #special method init def __init__(self, name, age): self.name = name #Attribute of the class Dog - unique for every object self.age = age def get_name(self): return self.name def get_age(self): return self.age def set_age(self, age): self.age = age def add_one(self, x): return x + 1 def bark(self): print("bark") d = Dog("Tim", 34) print(d.get_name()) d.set_age(22) print(d.get_age()) d2 = Dog("Bill", 12) print(d2.get_name()) print(d2.get_age()) d.bark() print(d.add_one(5)) print(type(d))
true
714dcc6e135a3103588ce3bcf8a96ac16b61fe5e
ricdtaveira/poo-python-ifce-p7
/aula03/funcionario.py
1,780
4.21875
4
""" Funcionario é uma classe abstrata (Abstract Base Class). Todos os empregados tem um primeiro_nome, ultimo_nome, e um salário. Cada empregado pode calcular o seu salario. Todavia, o mecanismo para calcular o salário depende do tipo de empregado. Assim, cada subtipo deve definir, o modo como calcular o seu salário. """ # Definição de uma Classe Abstrata - (Abstract Base Class). import abc class Funcionario(abc.ABC): # Método Construtor # Atributos Privados def __init__(self, primeiroNome, ultimoNome, salario): self._primeiroNome = primeiroNome self._ultimoNome = ultimoNome self._salario = salario # Método Acessor retorna _primeiroNome def get_primeiroNome(self): return self._primeiroNome # Método Acessor retorna _ultimoNome def get_ultimoNome(self): return self._ultimoNome # Método Acessor retorna _salario def get_salario(self): return self._salario # Método Modificador altera _primeiroNome def set_primeiroNome(self, primeiroNome): self._primeiroNome=primeiroNome # Método Modificador altera _ultimoNome def set_ultimoNome(self, ultimoNome): self._ultimoNome=ultimoNome # Método Modificador altera _salario def set_salario(self, salario): self._salario=salario # Definição de um Método Abstrato. # O Método Abstrato será reescrito na SubClasse @abc.abstractmethod def calcularPagamento(self): pass def imprimirCheckPagamento(self): nomeCompleto = self._ultimoNome + ", " + self._primeiroNome return ("Pagamento= " + nomeCompleto + " R$ " + str(self.calcularPagamento()))
false
f7729652596f8a71a8b172e337a95a10b18435ef
alluong/code
/python/prime.py
510
4.28125
4
def is_prime(num): if num > 1: if len(check_prime_list) == 0: return True return False while 1: num = int(input("please enter a number: ")) # check_prime_list is empty if num is a prime number # otherwise, check_prime_list contains a list of divisors divisible by num check_prime_list = [x for x in range(2, num) if num % x == 0] if is_prime(num): prime = "" else: prime = "not " print(str(num) + " is " + prime + "a prime number")
true
d06da6cf62aa2ac6cc4d915a83ce74e7ac03cfc0
balbachl/CIT228-1
/Chapter10/addition.py
402
4.125
4
def addition(n,d): return n+d quit="" while quit != "q": try: n = int(input("Type an integer")) d = int(input("Type another integer")) except ValueError: print("You entered a non-integer") else: print(n, "+", d, "=", addition(n,d)) finally: print("Thank you for the math problems!") quit=input("Would you like to continue, q to quit?")
true
9c99d10cdd77bb0e433ac2e69bd0b353c469d1b3
balbachl/CIT228-1
/Chapter7/multiplesOfTen.py
235
4.28125
4
number = int(input("Please enter a number and I will tell you if it is a multiple of ten")) if number%10==0: print("The number ", number, " is a multiple of ten") else: print("The number ", number, " is not a multiple of ten")
true
4bb93fb5614fc29bc99632a3103b870995c98b4f
aavinashjha/IamLearning
/Algorithms/Sorting/mergeSort.py
2,049
4.125
4
""" - Divide array into half - Merge in sorted order - Single element is always sorted: Base Case Time Complexity: - MergeSort uses at most NlgN compares and 6NlgN array accesses to sort any array of size N - C(N) <= C(ceil(N/2)) + C(ceil(N/2)) + N for N>1 with C(1) = 0 - A(N) <= A(ceil(N/2)) + A(ceil(N/2)) + 6N for N>1 with A(1) = 0 Improvements: - Use a cutoff value below that use insertion sort (avoid recursive calls) - While merging do nothing if The biggest item in first half is less than or equal to smallest item in second half Already sorted array: - Comapirisons made are: 1/2 nlogn and optimized version a[mid] <= a[mid+1] makes n-1 comparisons """ def merge(a, aux, lo, mid, hi): # a[lo..mid]: Already sorted # a[mid+1..high]: Already sorted # Maintains original copy, a is updated for k in range(lo, hi+1): aux[k] = a[k] #if aux[mid] <= aux[mid+1]: return i, j = lo, mid+1 for k in range(lo, hi+1): if i > mid: # All elements of left half are exhausted a[k] = aux[j] j += 1 elif j > hi: a[k] = aux[i] i += 1 elif aux[i] <= aux[j]: a[k] = aux[i] i += 1 else: # aux[j] < aux[i] a[k] = aux[j] j += 1 def sort(array, aux, lo, hi): if hi <= lo: return mid = lo + (hi-lo)//2 sort(array, aux, lo, mid) sort(array, aux, mid+1, hi) # The biggest item in first half is less than or equal to smallest item in second half merge(array, aux, lo, mid, hi) def mergeSort(array): aux = [-1] * len(array) sort(array, aux, 0, len(array)-1) def bottomUpMergeSort(array): N = len(array) aux = [-1] * N size = 1 while size < N: for lo in range(0, N-size+1, size): mid, hi = lo+size, min(lo+2*size, N-1) merge(array, aux, lo, mid, hi) size += size array = [3, 4, 1, 2, 5] mergeSort(array) print(array) array = [3, 4, 1, 2, 5] bottomUpMergeSort(array) print(array)
true
4ea3a2bc913ad93cb3dad696b9cc9b138ac04309
aavinashjha/IamLearning
/OOPS/Patterns/factory.py
2,921
4.8125
5
""" Problem: - Who should be responsible for creating objects when there are special considerations such as complex creation logic, a desire to separate the creation responsibilites for better cohesion? When you need a factory pattern? - When you don't know ahead of time what class object you need - When all the potential classes are in same subclass hierarchy - To centralize class selection code - When you don't want the user to have to know every subclass - To encapsulate object creation Solution: - Create a Pure Fabrication object called factory that handles the creation NOTES: - When a method returns one of several possible classes that share a common super class > Create a new enemy in game > Random number generator picks a number assigned to a specific enemy > The factory returns the enemy associated with that number > Class is chosen at runtime Client -> EnemyShipFactory -> EnemyShip (Implemented by UFOEnemyShip, RocketEnemyShip)\ The Factory Pattern allows you to create objects without specifying the exact class of object that will be created. """ from abc import ABC, abstractmethod class EnemyShip(ABC): def getName(self): return self.name def setName(self, name): self.name = name def getDamage(self): return self.damage def setDamage(self, damage): self.damage = damage def followHeroShip(self): print("{} is following the hero".format(self.getName())) def displayEnemyShip(self): print("{} is on the screen".format(self.getName())) def enemyShipShoots(self): print("{} attacks and does {}".format(self.getName(), self.getDamage())) class UFOEnemyShip(EnemyShip): def __init__(self): self.setName("UFO Enemy Ship") self.setDamage(20) class RocketEnemyShip(EnemyShip): def __init__(self): self.setName("Rocket Enemy Ship") self.setDamage(10) class BigEnemyShip(EnemyShip): def __init__(self): self.setName("Big Enemy Ship") self.setDamage(40) class EnemyShipFactory: def makeEnemyShip(self, shipType): enemy = None if shipType == "U": enemy = UFOEnemyShip() elif shipType == "R": enemy = RocketEnemyShip() elif shipType == "B": enemy = BigEnemyShip() return enemy def doStuffEnemy(enemyShip): enemyShip.displayEnemyShip() enemyShip.followHeroShip() enemyShip.enemyShipShoots() shipFactory = EnemyShipFactory() while True: shipType = input("Which ship you want: U/R/B") enemy = shipFactory.makeEnemyShip(shipType) doStuffEnemy(enemy) # This bunch of if else is bad, we have a better way by using factory pattern """ while True: shipType = input("Which ship you want: U/R") enemy = None if shipType == "U": enemy = UFOEnemyShip() if shipType == "R": enemy = RocketEnemyShip() doStuffEnemy(enemy) """
true
bbf313aac3b7fb8130c4a3f4503011d5abf59a69
Mohitgola0076/Day6-Internity
/Creating_Arrays.py
1,549
4.15625
4
''' A new ndarray object can be constructed by any of the following array creation routines or using a low-level ndarray constructor. ''' numpy.empty # It creates an uninitialized array of specified shape and dtype. It uses the following constructor − numpy.empty(shape, dtype = float, order = 'C') # Example 1 # The following code shows an example of an empty array. import numpy as np x = np.empty([3,2], dtype = int) print x # The output is as follows − [[22649312 1701344351] [1818321759 1885959276] [16779776 156368896]] ############################################# numpy.zeros # Returns a new array of specified size, filled with zeros. numpy.zeros(shape, dtype = float, order = 'C') # Example 2 # array of five zeros. Default dtype is float import numpy as np x = np.zeros(5) print x # The output is as follows − [ 0. 0. 0. 0. 0.] # Example 3 import numpy as np x = np.zeros((5,), dtype = np.int) print x # Now, the output would be as follows − [0 0 0 0 0] ############################### numpy.ones # Returns a new array of specified size and type, filled with ones. numpy.ones(shape, dtype = None, order = 'C') # Example 4 # array of five ones. Default dtype is float import numpy as np x = np.ones(5) print x The output is as follows − [ 1. 1. 1. 1. 1.] # Example 2 import numpy as np x = np.ones([2,2], dtype = int) print x # Now, the output would be as follows − [[1 1] [1 1]]
true
1adb4807f2a38114e4d317a9ad00a18c08c611a4
vhenrik/AvaliacaoAlgoritmos
/usuario_senha.py
519
4.25
4
'''2) Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.''' n=(input("Informe um nome de usuário: ")) x=(input("Informe uma senha diferente do usuário: ")) b=(1) while b==1: if n==x: print("Usuário informado é igual a senha.") x=(input("Informe uma senha diferente do número de usuário: ")) else: b=b-1 print("Usuário e senha corretos.")
false
f1c88e528da47efcae52ccde723a48ccfc82bed7
shivaq/NetworkPractice
/Python/udemyPython/Python_Basic/文字列/文字列.py
1,167
4.1875
4
# 改行なし # ------------------------------------------------- print("hello", end="") print("World") # ------------------------------------------------- # セパレーター指定 # ------------------------------------------------- print("cats", "Dogs", "Mice", sep=",") # ------------------------------------------------- # 文字列も List 的に扱われる # ------------------------------------------------- name = "Zophie" name[0] name[0:4] for i in name: print("****" + i + "******") # ------------------------------------------------- ▼ 一文字目をチェック ------------------------------------------------- return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y') ------------------------------------------------- ▼ 頭文字が大文字になる ------------------------------------------------- name = "kill bill" print(name.title()) ------------------------------------------------- ▼ ホワイトスペースを削除 ------------------------------------------------- test = "python " test.rstrip() test = " python" test.lstrip() test.strip() -------------------------------------------------
false
443d05d05168aed78d5f0e5b4c04fa4ed76c0faf
shivaq/NetworkPractice
/Python/udemyPython/Python_Basic/Enumerate/enumerate基本.py
728
4.40625
4
enumerate → 列挙型は tuple のリストを返す ------------------------------------------------- list(enumerate('abcde')) ------------------------------------------------- enumerate のインデックスと要素とを出力 ------------------------------------------------- # tuple がアンパックされる for i,letter in enumerate('abcde'): print("At index {} the letter is {}".format(i,letter)) ------------------------------------------------- ▼ ZIP →2つのリストの要素を、tuple ペアのリストに変換 ------------------------------------------------- mylist1 = [1,2,3,4,5] mylist2 = ['a','b','c','d','e'] list(zip(mylist1,mylist2)) -------------------------------------------------
false
fbc8821835083eea2a2002bb3970d740e80cf48b
yavani/pycourse
/merge.py
675
4.21875
4
""" merge module """ def merge ( list1, list2) : # set everything to zero. i = j = k = 0 list3 = [ ] ''' The below method merges two lists in sorted order, returns sorted new list. Prerequisite: all argument lists should eb sorted. ''' while True: if len ( list1 ) == i : list3.extend ( list2[ j: ] ) break elif len(list2) == j : list3.extend(list1[i:]) break if list1[i] < list2[j] : list3.append(list1[i]) i += 1 k += 1 else: list3.append(list2[j]) j += 1 k += 1 return list3
true
9fa852a2e8d7479a8e48fe829ccaae77c646b47c
AhmetGurdal/Guess-Game
/Guess-Game.py
1,914
4.125
4
#-*- coding: cp1254 -*- import random import time print "Name?" ad = raw_input(":") print "OK, ",ad,"! let's play a game I think a number that between 1 and 1000." while True: print "If u can ,guess" num = random.randrange(1,1000) ts = 1 while True: ta = input(":") if num > ta: print "up" ts = ts + 1 elif num < ta: print "down" ts = ts + 1 elif num == ta: print "True Guess" ts = ts + 1 if ts > 10 and ts <= 15: print"U guessed true in" ts,"guesses. Not Bad." elif ts > 15 and ts <= 20: print"U guess true in" ts,"guesses. Really Bad Result." elif ts > 20: print"U guess true in" ts,"guesses. Too Bad for Humanity." else: print"U guess true in" ts,"guesses. Awesome." break print "\nIt's my turn. Now U think a numbet between 1-1000 and i will guess.(press Enter)\n" raw_input("") print "\nIf I have to increase my guess, enter 'i' (press Enter)\n" raw_input() print "\nIf I've to decrease my guess, enter'd' If my guess is True, enter 't' (press Enter)\n" raw_input() print "Think Now!" time.sleep(2) a = 1 b = 1000 ts2 = 1 while True: num2 = random.randrange(a,b) while True: print num2 th = raw_input(":") if th == "i": a = num2 + 1 ts2 = ts2 + 1 break elif th == "d": b = num2 ts2 = ts2 + 1 break elif th == "t": print "I guess true in "ts2," guesses." if ts2 > ts: print "U beat me. Well Done!" elif ts2 < ts: print "I bear u. U loser" elif ts2 == ts: print "It's tie." break else: print "\nIf I have to increase my guess, enter 'i' If I've to decrease my guess, enter'd'\n" print "\nIf my guess is True, enter 't'\n" print "If u wanna play again, enter 'r'" yeni = raw_input(":") if yeni != "r": print "\nNice game. Bye!!\n" time.sleep(3) quit()
true
591d3941a9c5218323cb600c46d81bfce0eb4666
yarnpuppy/Python-the-Hard-Way
/ex6.py
922
4.15625
4
# d is some sort of variable. % allows you define the value x = "There are %d types of people." % 10 # defines binary as a string binary binary = "binary" # defines do_not as the string "don't" do_not = "don't" # Compound variable description for s and s. %(s,s), allows for consecutive variable substitution. y = "Those who know %s and those who %s." % (binary, do_not) print x print y # r is defined as x, which should print I said: 'There are 10 types of people.'. print "I said: %r." % x # s is defined as y, which should print I also said: 'Those who know binary and those who don't.'. print "I also said: '%s'. " % y hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side." #prints This is the left side of...a string with a right side. print w + e m= "Marja is very " a = "very cool" print m + a
true
99be2dd68589f521adffd6594f42cc1b0c95b395
e-walther-rudman/ProjectEulerSolutions
/PE_problem4_Maxime_Emily.py
647
4.125
4
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # #Find the largest palindrome made from the product of two 3-digit numbers. LargestPalindrome = 0 for FirstNumber in range(100,1000): for SecondNumber in range(FirstNumber, 1000): NumberAsList = list(str(FirstNumber*SecondNumber)) NumberAsListOriginal = NumberAsList.copy() NumberAsList.reverse() if NumberAsListOriginal == NumberAsList and FirstNumber*SecondNumber >LargestPalindrome: LargestPalindrome = FirstNumber*SecondNumber print(LargestPalindrome)
true
a7e42c9f2b2ad26b47ba97061729c86bc3b14c87
MarHakopian/Intro-to-Python-HTI-3-Group-2-Marine-Hakobyan
/Homework_3/factorial.py
222
4.15625
4
def factorial_f(n): factorial_n = 1 for i in range(1, int(n) + 1): factorial_n = factorial_n * i return f"The factorial of {n} is {factorial_n}!" n = input("Enter the number: ") print(factorial_f(n))
true
2c88c2ee54597db7130e56c60b7c393d0e3f0ff0
dongrami0425/opentutorials_python_basic
/opentutorials_python2/opentutorials_python2/16_object_and_variable/3_set_get_method.py
655
4.125
4
# < Set/Get method > # 인스턴스 변수를 읽고 쓰는 방식중에서 권장되는 방법. # 메소드에 set, get을 붙이는 것은 관습적인 약속. # 메소드밖(메인코드에서)에서 인스턴스 메소드에 직접적으로 접근한다는 것을 명시하는 방법. class C(object): def __init__(self, v): self.value = v def show(self): print(self.value) def getValue(self): # 값을 받아오는 메소드. return self.value def setValue(self, v): # 값을 설정하는 메소드. self.value = v c1 = C(10) print(c1.getValue()) c1.setValue(20) print(c1.getValue())
false
f50ee5231eaa848d646ffe5aa71ad76a13498c7c
HaykBarca/Python
/tuples.py
457
4.4375
4
# A tuple is an immutable container that stores objects in a specific order my_tuple = tuple() print(my_tuple) my_new_tuple = () print(my_new_tuple) # You should add items when you creating tuple, you can't change, add, remove items from tuple tuple_items = ("Apple", "Orange") print(tuple_items) print(tuple_items[1]) new_tuple_items = tuple_items[0:1] # Slice tuple print(new_tuple_items) print("Orange" in tuple_items) # Check if Orange exists in tuple
true
f1864d27157164507fde1e72b21b10d7a681701f
ashish-netizen/AlgorithmsAndDataStructure
/Python/DataStructure/Stack/stack.py
505
4.40625
4
#here we are using demonstrating stack in python #Initally we take an empty list a then we use append function to push element in the list. #printed [1,2,3] #after that elements poped out in Last In First Out Order a = [] a.append(1) a.append(2) a.append(3) print('Initial stack') print(a) print('\nElements popped out from stack:') print(a.pop()) print(a.pop()) print(a.pop()) print("Stack printed in LIFO Order") print('\nStack after all elements are popped out:') print(a)
true
9f66925e4433ef7a8b6743520e276311fdfa110b
Sincab/city
/s04-anagram.py
449
4.125
4
# def main(): # entered_word_1 = input('enter first word:') # entered_word_2 = input('enter second word:') # # print('They are ', is_anagram(entered_word_1, entered_word_2)) # # # def is_anagram(entered_word_1, entered_word_2): # if sorting_things(entered_word_1) == sorting_things(entered_word_2): # return 'Anagram.' # return 'NOT Anagram.' # # # def sorting_things(string): # return sorted([s for s in string]) #
false
98ac1ee97fbfb2e0b931aee26ba575164ff4d002
crawler4o/Learning_Python
/Hang_Man/hangman.py
2,483
4.375
4
### Hangman ### Exercise 32 (and Solution) ### ### This exercise is Part 3 of 3 of the Hangman exercise series. The other exercises are: Part 1 and Part 2. ### ### You can start your Python journey anywhere, but to finish this exercise you will have to have finished Parts 1 and 2 or use the solutions (Part 1 and Part 2). ### ### In this exercise, we will finish building Hangman. In the game of Hangman, the player only has 6 incorrect guesses (head, body, 2 legs, and 2 arms) before they lose the game. ### ### In Part 1, we loaded a random word list and picked a word from it. In Part 2, we wrote the logic for guessing the letter and displaying that information to the user. In this exercise, we have to put it all together and add logic for handling guesses. ### ### Copy your code from Parts 1 and 2 into a new file as a starting point. Now add the following features: ### ### Only let the user guess 6 times, and tell the user how many guesses they have left. ### Keep track of the letters the user guessed. If the user guesses a letter they already guessed, don’t penalize them - let them guess again. ### ### Optional additions: ### ### When the player wins or loses, let them start a new game. ### Rather than telling the user "You have 4 incorrect guesses left", display some picture art for the Hangman. This is challenging - do the other parts of the exercise first! ### ### Your solution will be a lot cleaner if you make use of functions to help you! import pick_word import guess_letters def game_play(): print('\n \n__________________________________ \n Hello to the new game ! \n') word = pick_word.pick_word() print(word) # to see the word for testing attempts = 0 # means the wrong guesses guesses = 0 guessed_letters = set() guessed_word = '-'*len(word) games = 1 print(guessed_word) while not (guess_letters.game_over(attempts) or guess_letters.game_win(word, guessed_word)): # play while not lose or win [guessed_word, guessed_letters, attempts] = guess_letters.guess(word, guessed_word, guessed_letters, attempts) guesses +=1 print(guessed_word) if guess_letters.new_game(): # if lose or win, offer a new game. games +=1 game_play() else: print('It was a pleasure to play with you! You played %s games' % games) # Say bye if no new game is desired quit() if __name__ == '__main__': games = 1 game_play()
true
528baefe3109452a19479d82a649018bbb35aa3b
terrylovesbird/lecture-w2-d2-OOP-CSV
/classes/animals/dog.py
676
4.34375
4
class Dog: species = "Canis Lupus Familiaris" # example of a *class attribute* sound = "Woof" legs = 4 tail = 1 mammal = True def __init__(self, name, breed): self.name = name # example of an *instance attribute* self.breed = breed def __str__(self): return f"I am a dog named {self.name} and my breed is {self.breed}. I have {self.legs} legs and I say {self.sound}!" def __eq__(self, other_dog): return self.breed == other_dog.breed def __add__(self, other_dog): return Dog(self.name + other_dog.name, self.breed) def speak(self): # example of an *instance method* print(self.sound)
true
4b3d9a9351988f4e9038ed24535be5473fa8b048
jasminegrewal/algos
/algorithms/bubbleSort.py
1,050
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 28 11:14:37 2017 @author: jasmine """ def bubbleSort(arr): for i in range(len(arr)-1): ''' i will go from 0 to second last element last element will be compared at second last position''' for j in range((len(arr)-1)-i): '''j will go from 0 till n-i^th position as largest element will keep taking their right position and unsorted array will keep decreasing to left i.e largest elements will take their position first ''' if(arr[j]>arr[j+1]): arr[j],arr[j+1]=arr[j+1],arr[j] return arr def optimizedSort(arr): isSorted=False lastUnsorted=len(arr)-1 while(not isSorted): isSorted=True for i in range(lastUnsorted): if(arr[i]>arr[i+1]): arr[i],arr[i+1]=arr[i+1],arr[i] isSorted=False lastUnsorted-=1 return arr numbers=[6,4,7,3,9,1,2,8,0] #print(bubbleSort(numbers)) print(optimizedSort(numbers))
true
b2578f87fc2bd326e5f588888a11e7a98ab670c4
Luxura/Learning
/Collatz square.py
328
4.21875
4
# this will try to use the collatz squar # if number even return number // 2, sinon number * 3 +1 # projet en cours def collatz(number): if number % 2 == 0: b = number // 2 print(b) else: b = number * 3 + 1 print(b) b = (int(input("Taper un chiffre: "))) while b != 1: collatz(b)
true
28cfa27fe7bbdf71e75420460511d83264404ec9
yasoob/pybasic
/mathquestions.py
1,452
4.125
4
# Angus Gardner import sys, random print "Welcome to Math Questions.\n" operators = { '*': lambda a, b: a * b, '+': lambda a, b: a + b, '/': lambda a, b: a / b, '-': lambda a, b: a - b } def question(oper): print "You are doing:", typeQ, "\n" numQ = int(raw_input("How many questions do you want to be asked?: ")) lowQ = int(raw_input("What is the lowest value number you want?: ")) highQ = int(raw_input("What is the highest value number you want?: ")) for i in range(numQ): n1Q = random.randint(lowQ, highQ) n2Q = random.randint(lowQ, highQ) nanQ = operators[oper](n1Q, n2Q) while True: print "What is", n1Q, oper, n2Q, "?:" ansQ = float(raw_input("")) if ansQ == nanQ: print "That's right!", ansQ, "is the right answer." again = str(raw_input("Again?: ")) if again.lower() in ('yes', 'y'): question(oper) elif again.lower() in ('no', 'n'): sys.exit(1) else: print "Exiting." sys.exit(1) elif ansQ > nanQ: print "Too high." continue elif ansQ < nanQ: print "Too low." continue while True: typeQ = str(raw_input("What type of questions do you want to be asked?: (Multiplication, Addition, Subtraction, Division) ")) if typeQ.lower() == 'multiplication': question('*') elif typeQ.lower() == 'addition': question('+') elif typeQ.lower() == 'division': question('/') elif typeQ.lower() == 'subtraction': question('-') else: print "Try again." continue
false
c912b89f7c1035ef84282a4fcc7f6fd2f30aa8f2
ITianerU/algorithm
/剑指offer/16_数值的整数次方/python.py
977
4.28125
4
""" #### 题目描述 给定一个 double 类型的浮点数 base 和 int 类型的整数 exponent,求 base 的 exponent 次方。 #### 解题思路 下面的讨论中 x 代表 base,n 代表 exponent。 """ import math def Power(base, exponent): # return math.pow(base, exponent) if exponent == 0: return 1 m = base n = exponent if exponent < 0: exponent = -exponent for i in range(exponent-1): base = base * m if n < 0: base = 1 / base return base def Power2(base, exponent): if exponent == 0: return 1 elif exponent == 1: return base n = exponent if exponent < 0: exponent = -exponent if exponent % 2 == 0: base = Power2(base * base, exponent // 2) else: base = base * base * Power2(base, exponent // 2) if n < 0: return 1 / base return base if __name__ == '__main__': print(Power(2, -2)) print(Power2(2, -2))
false
c1908b0f6d34e8d9eca3b8b3d1a5df2543e3862e
ITianerU/algorithm
/剑指offer/9_矩形覆盖/python.py
927
4.3125
4
""" #### Ŀ ǿ 2\*1 СκŻȥǸľΡ n 2\*1 Сصظһ 2\*n ĴΣܹжַ #### ˼· n Ϊ 1 ʱֻһָǷ n Ϊ 2 ʱָǷ Ҫ 2\*n ĴΣȸ 2\*1 ľΣٸ 2\*(n-1) ľΣȸ 2\*2 ľΣٸ 2\*(n-2) ľΡ 2\*(n-1) 2\*(n-2) ľοԿ⡣ĵƹʽ£ f(n): 1 n=1 2 n=2 f(n-1)+f(n-2) n>1 """ def rectCover(number): if number <= 0: return number rects = [0 for i in range(number+1)] rects[0] = 1 rects[1] = 2 for i in range(2, number): rects[i] = rects[i-1] + rects[i-2] return rects[number-1] if __name__ == '__main__': print(rectCover(1))
false
d154538bbd361e62ce04c5211f2c14e13b0ae335
ITianerU/algorithm
/剑指offer/4_从尾到头打印链表/python.py
1,966
4.28125
4
""" #### 题目描述 从尾到头反过来打印出每个结点的值。 #### 解题思路 ##### 使用递归 要逆序打印链表 1->2->3(3,2,1),可以先逆序打印链表 2->3(3,2),最后再打印第一个节点 1。而链表 2->3 可以看成一个新的链表,要逆序打印该链表可以继续使用求解函数,也就是在求解函数中调用自己,这就是递归函数。 """ class listNode(): def __init__(self, x): self.value = x self.next = None def printListFromTailToHead1(listNode): nlist = list() if listNode != None: nlist.extend(printListFromTailToHead1(listNode.next)) nlist.append(listNode.value) return nlist """ 结点和第一个节点的区别: - 头结点是在头插法中使用的一个额外节点,这个节点不存储值; - 第一个节点就是链表的第一个真正存储值的节点。 """ def printListFromTailToHead2(lNode): head = listNode(-1) while lNode != None: nextNode = lNode.next lNode.next = head.next head.next = lNode lNode = nextNode nlist = list() head = head.next while head != None: nlist.append(head.value) head = head.next return nlist """ 使用栈 栈具有后进先出的特点,在遍历链表时将值按顺序放入栈中,最后出栈的顺序即为逆序。 """ # def printListFromTailToHead3(lNode): # nlist = list() # while lNode != None: # nlist.append(lNode.value) # lNode = lNode.next # # nlist2 = list() # while len(nlist)>0: # nlist2.append(nlist.pop()) # # return nlist2 if __name__ == '__main__': L1 = listNode(1) L2 = listNode(2) L3 = listNode(3) L4 = listNode(4) L5 = listNode(5) L4.next = L5 L3.next = L4 L2.next = L3 L1.next = L2 # print(printListFromTailToHead3(L1)) print(printListFromTailToHead1(L1)) print(printListFromTailToHead2(L1))
false
2134f63f8ee05108164dbcf12cb19d1aede12bd1
MrAbhaySharma/Calculator
/t.py
779
4.1875
4
choice = raw_input(" What do you want to do? \n Enter:- \n \"add\" for addition \n \"sub\" for substraction \n \"multi\" for multiplication \n \"divide\" for division \n ") def input_number(): x1 = input(" Enter two number (in this form \"2\"):- \n ") x2 = input(" ") return(x1,x2) if(choice=="add"): n1,n2 = input_number() s = n1 + n2 print(" the sum is " + str(s)) elif(choice=="sub"): n1,n2 = input_number() r = n1 - n2 print(" the diffrence is " + str(r)) elif(choice=="multi"): n1,n2 = input_number() e = n1 * n2 print(" the product is " + str(e)) elif(choice=="divide"): n1,n2 = input_number() y = float(n1) / n2 print(" the quotient is " + str(y)) else: print(" Wrong Choice.")
false
2e78052fa41caae51f1d583fb025bef7d21bab67
navill/algorithm_coding_interview
/chapter_3/animal_shelter.py
2,675
4.15625
4
""" 먼저 들어온 동물(개 또는 고양이)이 먼저 나가는 동물 보호소 사람들은 가장 오래된 동물부터 입양할 수 있다. class Aniaml - Dog(Animal): dogs Queue에 저장된다 - Cat(Animal): cats Queue에 저장된다. AnimalQueue: 두 개의 큐를 이용해 각각 고양이와 강아지를 저장한다. - cats - dogs """ from queue import Queue class Animal: def __init__(self, name=None): self.name = name self.order = 0 def is_older_than(self, a): return self.order < a.order class Dog(Animal): def __init__(self, name=None): super().__init__(name) class Cat(Animal): def __init__(self, name=None): super().__init__(name) class AnimalQueue: dogs = Queue() cats = Queue() order = 0 # 오래된 동물을 판단하기 위해 사용될 order def enqueue(self, animal): animal.order = self.order self.order += 1 if isinstance(animal, Dog): self.dogs.put(animal) else: self.cats.put(animal) def dequeue_any(self): if self.dogs.qsize() == 0: return self.dequeue_cats() elif self.cats.qsize() == 0: return self.dequeue_dogs() dog = self.dogs.queue[0] cat = self.cats.queue[0] # 고양이와 강아지 중 더 오래된 동물은? if dog.is_older_than(cat): return self.dequeue_dogs() else: return self.dequeue_cats() def dequeue_dogs(self): try: return self.dogs.get_nowait() except: # 강아지 큐가 비었을 경우 빈 Dog 객체 전달 return Dog() def dequeue_cats(self): try: # get_nowait: queue가 있을 경우 값을 가져오고 없을 경우 기다리지 않고 task 종료->raise empty error # get: queue가 있을 경우 값을 가져오고 없을 경우 기다림 return self.cats.get_nowait() except: # 고양이 큐가 비었을 경우 빈 Cat 객체 전달 return Cat() animals = AnimalQueue() cat1 = Cat('cat1') cat2 = Cat('cat2') cat3 = Cat('cat3') cat4 = Cat('cat4') dog1 = Dog('dog1') dog2 = Dog('dog2') dog3 = Dog('dog3') dog4 = Dog('dog4') animals.enqueue(cat1) animals.enqueue(cat2) animals.enqueue(dog1) animals.enqueue(cat3) animals.enqueue(dog2) animals.enqueue(cat4) animals.enqueue(dog3) animals.enqueue(dog4) print(animals.dequeue_any().name) print(animals.dequeue_dogs().name) print(animals.dequeue_dogs().name) print(animals.dequeue_dogs().name) print(animals.dequeue_dogs().name) print(animals.dequeue_dogs().name)
false
aed710442c5cf49a03b9c8e2d21eec260d75ef75
vvek475/Competetive_Programming
/Competitive/comp_8/Q2_LION_squad.py
687
4.28125
4
def reverse_num(inp): #this line converts number to positive if negative num=abs(inp) strn=str(num) nums=int(strn[::-1]) #these above lines converts num to string and is reversed if inp>0: print(nums) else: #if input was negative this converts to negative again after above process nums*=-1 print(nums) def Input_validator(): while True: num=input('Enter string to be reversed: \n') if num.isdigit() or (num[0]=='-' and num[1:].isdigit()): reverse_num(int(num)) break print('Please enter a valid number \n') if __name__=='__main__': Input_validator()
true
7cb9e0723aee588e621ea4c66477f20a769b5b60
raonifduarte/Estruturas_Controle
/if_else_RAONI.py
664
4.1875
4
#!/usr/local/bin;python3 nota = float(input('Insira a Nota do Aluno:')) if __name__ == '__main__': if nota >= 9.1: print('A') elif nota >= 8.1: print('A-') elif nota >= 7.1: print('B') elif nota >= 6.1: print('B-') elif nota >= 5.1: print('C') elif nota >= 4.1: print('C-') elif nota >= 3.1: print('D') elif nota >= 2.1: print('D-') elif nota >= 1.1: print('E') elif nota >= 0.0: print('E-') elif nota >= 10.1: print('Nota Inválida!') else: print('Nota Inválida"')
false