blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
326e404d03568049e1667422f555773ecb2c1cd7
AthaG/Kata-Tasks
/6kyu/VasyaClerk_6kyu.py
1,295
4.15625
4
'''The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollar bill. An "Avengers" ticket costs 25 dollars. Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line. Can Vasya sell a ticket to every person and give change if he initially has no money and sells the tickets strictly in the order people queue? Return YES, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Otherwise return NO. Examples: tickets([25, 25, 50]) # => YES tickets([25, 100]) # => NO. Vasya will not have enough money to give change to 100 dollars tickets([25, 25, 50, 50, 100]) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)''' def tickets(people): tw = fi = hu = 0 for c in people: if c == 25: tw += 1 elif c == 50: tw -= 1 fi += 1 elif c == 100 and fi > 0: tw -= 1 fi -= 1 elif c == 100 and fi == 0: tw -= 3 if tw < 0 or fi < 0: return 'NO' return 'YES'
true
50bfe95cf2fe7023477c7d1905f33b8ba556d552
AthaG/Kata-Tasks
/5kyu/Rot13_5kyu.py
1,258
4.75
5
'''ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher. Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation". Please note that using encode is considered cheating.''' #First solution def rot13(message): return ''.join(chr((65 if char.isupper() else 97) + ((ord(char) - (65 if char.isupper() else 97)) + 13) % 26) if char.isalpha() else char for char in message) #Second solution def rot13(message): res = [] for char in message: if char not in map(chr, range(97, 123)) and char not in map(chr, range(65, 91)): res.append(char) else: if char.islower() and ord(char) + 13 > 122: res.append(chr(((ord(char) + 13) - 122) + 96)) elif char.isupper() and ord(char) + 13 > 90: res.append(chr(((ord(char) + 13) - 90) + 64)) else: res.append(chr((ord(char))+13)) return ''.join(res)
true
14516ff1d60fb951f12fbf86ecb8723ed3f0a88e
Tanveer132/Python-basics
/FST_03_list.py
890
4.21875
4
#LIST # l=[1,3,4,5,6] # #nesting list # l2=[1,3,4,5,6.6,"hello",t] # #accessing nesting list # print(t2[6][2]) # #list operations # # 1. list.append(value) # l=["milk","eggs","sugar","Oil"] # l.append(7) # print(l) # #2. list.remove(value) # l.remove(7) # print(l) # #3. list.pop(value) # item=l.pop() # print(l) # print(item) # #4. list.insert(index,value) # l.insert(2,"ice-cream") # print(l) # for i in l: # print(i) # for i in range(len(l)): # print(i,"=>",l[i]) # n=int(input("Enter the number of students: ")) # student=[] # for i in range(n): # name=input("Enter the name of the student: ") # student.append(name) # print(student) n=int(input("Enter the number of students: ")) student=[] for i in range(n): name=input("Enter the name of the student :") marks=int(input("Enter the marks :")) student.append([name,marks]) print(student)
false
dc3a319dc4cef21360ac1c9a61f93b39205ee072
Tanveer132/Python-basics
/FST_04_dict.py
765
4.375
4
#--------------DICTIONARY-------------- # It is an important datatype used in machine learning #key:value d={1:"Tanveer", 2:"Akshay" ,3:"Shaheem",1:"Kiran"} #print dictionary print(d) #print type of d print(type(d)) #access the dictionary using key value print(d[3]) #update the dictionary d[4]="Snjana" print(d) #pop the item in the dictionary #it pops the last item in the dictionary d.popitem() print(d) #pop the item in the dictionary #it pops the item at given index d.pop(2) print(d) #TO get the list of the keys, values s print(d.keys()) #to access the dictionary using for loop for i in d: print(i," => ",d[i]) #to get items in the dictionary. for item in d.items(): print(item) for key,value in d.items(): print(key,"=>", value)
true
f82fd283e547e2a829e7a5027b17d87c867a05e2
EmIErO/Programming-Puzzles
/inverse_captcha_part_2.py
821
4.15625
4
# Program reviews a sequence of digits (a txt file) # and find the sum of all digits that match the digit halfway around in the list. import inverse_captcha def add_matching_digits(list_of_digits): """Calculates the sum of all digits that match the digit halfway around the circular list.""" half_of_list = int(len(list_of_digits) / 2) sum_of_digits = 0 for i in range(half_of_list): if list_of_digits[i] == list_of_digits[i + half_of_list]: sum_of_digits += list_of_digits[i] sum_of_digits += list_of_digits[i + half_of_list] return sum_of_digits def main(): list_of_digits = inverse_captcha.convert_captcha_to_list("my_capcha.txt") sum_of_digits = add_matching_digits(list_of_digits) print(sum_of_digits) if __name__ == '__main__': main()
true
e2a3b42c92a3bee0577c37c825cca6989e4fb694
EmIErO/Programming-Puzzles
/corruption_checksum.py
1,042
4.4375
4
# Program converts txt file with data to a table (list of lists). # It calculates the difference between the largest value and the smallest value for each row; # then it calculates the sum of all of these differences. def convert_data_to_table(file_name): """ Converts txt file with data to a table (list of lists) of int. """ with open(file_name, "r") as file: lines = file.readlines() table_of_data = [line.replace("\n", "").split("\t") for line in lines] for row in table_of_data: for i in range(len(row)): row[i] = int(row[i]) return table_of_data def calculate_range(table): """ Calculates the difference between the largest value and the smallest value for each row. """ list_of_ranges = [max(row) - min(row) for row in table] return list_of_ranges def main(): table = convert_data_to_table("corruption_checksum.txt") list_of_ranges = calculate_range(table) checksum = sum(list_of_ranges) print(checksum) if __name__ == '__main__': main()
true
f881c10bcc85560274ffbe2870ba498542b0165e
MerinGeorge1987/PES_PYTHON_Assignment_SET-1
/ass1Q16.py
918
4.1875
4
#!/usr/bin/python #Title: Assignment1---Question16 #Author:Merin #Version:1 #DateTime:02/12/2018 5:30pm #Summary:Write program to perform following: # i) Check whether given number is prime or not. # ii) Generate all the prime numbers between 1 to N where N is given number. #i) Check whether given number is prime or not. num1=input ("Enter a number:") x=2;flag=0 while x<=num1/2: if num1%x==0: flag=flag+1 x=x+1 if flag==0: print num1," is a prime number" else: print num1," is not a prime number" #ii) Generate all the prime numbers between 1 to N where N is given number. N=input ("Enter a number: ") print "Prime numbers between 1 to %d :"%N, for y in range(2,N,1): x=2;flag=0 while x<=y/2: if y%x==0: flag=flag+1 break x=x+1 if flag==0: print y,",",
true
da69991eeb394b938db82b5bba25ff87e2240cf8
MerinGeorge1987/PES_PYTHON_Assignment_SET-1
/ass1Q10.py
769
4.1875
4
#!/usr/bin/python #Title: Assignment1---Question10 #Author:Merin #Version:1 #DateTime:02/12/2018 3:10pm #Summary:Using assignment operators, perform following operations # Addition, Substation, Multiplication, Division, Modulus, Exponent and Floor division operations a=40 b=3 #Addition res=a+b print "Sum of ",a,"&",b,"=",res #Subtraction res=a-b print "Difference of ",b,"from",a,"=",res #Multiplication res=a*b print "On multiplying ",a,"with",b,"=",res #Division res=a/b print "On dividing ",a,"by",b,"=",res #Modulus res=a%b print "Reminder on dividing ",a,"by",b,"=",res #Exponent res=a**b print "Exponent ",a,"to",b,"=",res #Floor division res=a//b print "On dividing(floor division) ",a,"by",b,"=",res
true
1dad42d021d6502da9e9aaa70f073ff2d629bce8
mindful-ai/oracle-june20
/day_02/code/11_understanding_functions_and_modules/project_a_new.py
508
4.28125
4
# Project A # Function based approach # Program to determine if a number is prime or not def checkprime(num): for i in range(2, num): if(num % i == 0): return False return True # ------------------------------ print("Name: ", __name__) if __name__ == "__main__": n = int(input('Enter a number: ')) prime = checkprime(n) if(prime == True): print('The number is prime') else: print('The number is not prime')
true
cdc2055c0b0027bc5a660cb082ebcce0d0062931
rogos01/Practica_11
/ejercicio4.py
477
4.15625
4
#estrategia descendente o top-down memoria = {1:1, 2:1, 3:2} def fibonacci(numero): a = 1 b = 1 for i in range(1, numero-1): a, b = b, a + b return b def fibonacci_top_down(numero): if numero in memoria: return memoria[numero] f = fibonacci(numero-1)+ fibonacci(numero-2) memoria[numero] = f return memoria[numero] print(fibonacci_top_down(5)) print(memoria) print(fibonacci_top_down(4)) print(memoria)
false
bf4ed5e7f04c6e502737a0acb578da4c8bc23120
Yumingyuan/algorithm_lab
/merge_sort_new.py
980
4.15625
4
def merge(need_sort_list,low,mid,high): after_sort=[] index1=low index2=mid+1 for k in range(low,high+1): if index1>mid: after_sort.append(need_sort_list[index2]) index2=index2+1 elif index2>high: after_sort.append(need_sort_list[index1]) index1=index1+1 elif need_sort_list[index1]<need_sort_list[index2]: after_sort.append(need_sort_list[index1]) index1=index1+1 elif need_sort_list[index1]>need_sort_list[index2]: after_sort.append(need_sort_list[index2]) index2=index2+1 else: pass print("After merge:",after_sort) def sort(need_sort_list,low,high): if high<=low: return mid=int(low+int((high-low)/2)) print('current sort data:',need_sort_list[low:high+1],"low mid and high:",low,mid,high) sort(need_sort_list,low,mid) sort(need_sort_list,mid+1,high) merge(need_sort_list,low,mid,high) if __name__=='__main__': list_unsort=[2,10,13,18,19,1,3,5,7,9] print("before_sort:",list_unsort) sort(list_unsort,0,len(list_unsort)-1)
false
58aec9aef681275f1b0e9af6ca1d2471051ec55b
Yumingyuan/algorithm_lab
/queue_simulate_stack.py
1,732
4.28125
4
# -*- coding: utf-8 -*- #插入函数insertinqueue确保只有一个队列中有元素 def insertinqueue(queue1,queue2,item): #当queue1为空,则往queue2的队尾加入东西 if len(queue1)==0: #加入新加入元素 queue2.append(item)#item相当于栈顶元素 else:#反之queue2为空,则往queue1的队尾加入东西 queue1.append(item)#item相当于栈顶元素 #删除队尾元素函数delete_tail,把非空队列的0-(len-1)元素放入空队列 def delete_tail(queue1,queue2): if len(queue1)==0 and len(queue2)==0:#当栈为空 return #当队列1中无元素时将queue2中的元素从队首移除len(queue2)-1个,并输出queue2中的剩下的元素 if len(queue1)==0: while len(queue2)!=1: data=queue2.pop(0)#获得队首元素 queue1.append(data) print("item pop",queue2.pop(0))#将移除len-1个队首元素的queue2中剩下的元素输出 #当队列2中无元素时将queue1中的元素从队首移除len(queue1)-1个,并输出queue1中的剩下的元素 elif len(queue2)==0: while len(queue1)!=1: data=queue1.pop(0)#获得队首元素 queue2.append(data) print("item pop",queue1.pop(0))#将移除len-1个队首元素的queue1中剩下的元素输出 else: pass if __name__=="__main__": queue1=["a","b","c","d","e"] queue2=[] #删除尾部节点函数调用 delete_tail(queue1,queue2) insertinqueue(queue1,queue2,"f") delete_tail(queue1,queue2) delete_tail(queue1,queue2) delete_tail(queue1,queue2) delete_tail(queue1,queue2) insertinqueue(queue1,queue2,"g") insertinqueue(queue1,queue2,"h") delete_tail(queue1,queue2) delete_tail(queue1,queue2)#正常弹出 delete_tail(queue1,queue2)#正常弹出 delete_tail(queue1,queue2)#此时栈为空,无效
false
2272d7a3bff348eb8dbee45d842cdcb94424fafe
pricelesspatato/Python-Tutoring
/overview.py
2,317
4.21875
4
import math def function(): return def helloWorld(): print("Hello, world!") def declareVariables(): integerValue = 1 floatValue = 3.999 stringValue= 'abc' booleanValue = True return integerValue, floatValue, stringValue, booleanValue def returnOne(): one = 1 return one def doMath(): addValue = 1 + 2 subtractValue = 12.97 - 3.5 multiplyValue = addValue * subtractValue divideValue = multiplyValue / 2 #These are equivalent statements addValue = addValue + 1 addValue += 1 squaredValue = divideValue ** 2 cubedValue = 4 ** 3 modulusValue = 10 % 3 return def learnLists(): blankList = [] nonBlankList = [1,2,3,4] firstElement = nonBlankList[0] nonBlankList.append(5) statesList = ["Minnesota", "Wisconsin"] valuesList = [addValue, subtractValue, multiplyValue] randomList = ["string", 4, blankList] def conditionals(): if addValue == 14: addValue -= 2 #notice that == is used to check whether a statement is true #and = is used to set a variable to a value if squaredValue > cubedValue and squaredValue is not 0: newVariable = 2 elif squaredValue < cubedValue or squaredValue == 0: newVariable = 1 else: newVariable = -1 def loops(): #which values will be printed here? value = 1 while value < 10: print(value) value += value #which values will be printed here? value = 22 while value >= 0: if value % 6 == 0: print(value) value -= 2 for x in range(1, 11, 2): print(x) for y in range(5): print(y) numbers = [1, 3, 6, 14, 23] for number in numbers: print(number) def passVariable(variable): print(variable) def passVariable(number): newnumber = number * 2 print(newnumber) def returnVariable(): value = 4 value += 6 return value if __name__ == "__main__": #comment like this with a hashtag ''' Multi line comments need 3 quotation marks before and after ''' helloWorld() declareVariables() value = returnOne() doMath() learnLists() conditionals() loops() variable = 2 passVariable(variable) value = returnVariable()
false
0b01166508e91c0412f783f80ddafb9a9e2f529c
jenlij/DC-Week2
/py108.py
1,462
4.15625
4
# Reading and writing files! # Reading a file. # Use the built-in `open` function hello_file = open('hello.txt') file_contents = hello_file.read() print file_contents # What if it doesn't exit? boo_error_file = open('no_file_here_buddy.txt') # (Error will print out) # Reading line by line swift = open('swift.txt') swift_lines = swift.readlines() for i in (range(len(swift_lines))): print "Line %d: %s" % (i+1, swift_lines[i]) # Writing to a new file. # You can't use the same syntax. # You need to tell python that you want to write. # Here's the equivalent: hello_file = open('hello.txt', 'r') # 'r' is for read hello_file = open('hello.txt', 'w') # 'w' is for write (OVERWRITES once closed and opened again) hello_file.write('hey!') hello_file.write('hey you!') hello_file.write('over here!') hello_file.write('do you want a chik fil a cookie?') hello_file.close() # These are called "file modes" # Writing to (appending to) a new file. hello_file = open('hello.txt', 'a') # 'a' is for append # Saving more complex stuff # you need to write it as "binary" # and use the pickle module import pickle silly = { 'person': { 'name': 'jethro', 'age': 1000, 'number_of_cats': 22 }, 'cat': { 'name': 'vin disel', 'age': 11 } } silly_file = open('silly.dat', "wb") pickle.dump(silly, silly_file) silly_file.close() # to read it back out file_of_silliness = open('silly.dat', 'rb') silliness = pickle.load(file_of_silliness)
true
0924cf9f8a45104532d6fbe5e68a1ccebe60d69d
gl051/tic-tac-toe
/tic-tac-toe.py
1,871
4.21875
4
#!/usr/bin/python """ Exercise: Implement a Tic-Tac-Toe game """ import grid import random class TicTacToe(object): def __init__(self): self.grid = grid.Grid() self.game_over = False self.players = {0: 'User', 1:'AI'} def user_pick(self): self.grid.show() pos_str = raw_input("Your turn, pick a slot available (1 to 9): ") pos = int(pos_str) self.grid.mark(pos, 'x') def computer_pick(self): #pos = random.sample(self.grid.empty_slots,1)[0] pos = random.choice(self.grid.empty_slots) self.grid.mark(pos, 'o') print 'AI,marked on position {}'.format(pos) def play(self): # randomly start with one of the two players pick = random.randint(0, 1) print "Let's play, {} goeas first".format(self.players[pick]) self.game_over = False; while not self.game_over: self.callPlayer(pick) # toggle next player pick = (pick + 1) % 2 def callPlayer(self, pick): # Check there are still slots available if self.grid.is_full(): print '*** Tie Game ***' self.game_over = True return print '{} play now'.format(self.players[pick]) if pick == 0: self.user_pick() elif pick == 1: self.computer_pick() # check if the player won if self.grid.is_winner(): self.grid.show() if pick == 0: print '*** Congratulation, you won! ***' elif pick == 1: print '*** I am sorry, AI won! ***' self.game_over = True # Gather our code in a main() function def main(): game = TicTacToe(); game.play() # Standard boilerplate to call the main() function to begin # the program. if __name__ == '__main__': main()
false
6a47887ebe2e5d31c6c2051a1963c27ad3b620f7
lucasmbrute2/Blue_mod1
/Extras/Exercicio13_func.py
547
4.125
4
# Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores # inteiros. # Seu programa tem que analisar todos os valores e dizer qual deles é o maior. def maior(num): maior = 0 if num > maior: maior = num return f"O maior valor é {maior}" while True: valor = int(input("Digite o valor: ")) maior(valor) continuar = input("Você quer continuar informando valores: ").upper()[0] if continuar in ['S']: continue else: break print(maior(valor))
false
cc55a2975dfd94f3990b64deefba9696999bda10
lucasmbrute2/Blue_mod1
/Aula09/Exercicio01.py
608
4.1875
4
# #01 - Crie um programa onde o usuário possa digitar vários valores numéricos e # cadastre-os em uma lista. Caso o número já esteja lá dentro, ele não será # adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem # crescente. l = [] while True: valor = int(input("Digite o valor aqui: ")) if valor in l: print("Valor já informado, digite outro.") else: l.append(valor) resposta = input("Você quer continuar? [SIM / NÃO] ") if resposta == 'sim' or resposta == 's': continue else: break l.sort() print(l)
false
e525cba83c896a374ee7554def4c9829abd85ad4
Indolent-Idiot/All-Assignments-of-Python-for-Everybody-bunch-of-courses-
/Assignment 8.4.py
1,131
4.65625
5
#8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. fname = raw_input("Enter file name: ") fh = open(fname) lst = list() # list for the desired output for line in fh: # to read every line of file romeo.txt word= line.rstrip().split() # to eliminate the unwanted blanks and turn the line into a list of words for element in word: # check every element in word if element in lst: # if element is repeated continue # do nothing else : # else if element is not in the list lst.append(element) # append lst.sort() # sort the list (de-indent indicates that you sort when the loop ends) print(lst) # print the list
true
59667e5fb7abff4a718cd8c61c20dd392b52ebd1
ahmadghabar/hangman-game
/hangman.py
1,733
4.28125
4
#I used random import random #I made list of words listofwords = ["python", "turtle", "class", "bored" , "school"] #This randomly picks one of the words out secretword = random.choice(listofwords) #my function def get_guess(): # this is to make the dashes in the beginning and then be able to update them dashes = "-" * len(secretword) # This is to give the number of guesses left guesses_left = 10 # I used a while loop to keep repeating until there are no guesses left while guesses_left > -1 and dashes != secretword: print(dashes) print "Guesses left: " + str(guesses_left) guess = input("Guess a letter:") if len(guess) != 1: print ("Your guess must have exactly one character!") elif guess==guess.upper(): print "That letter has to be lowercase." elif guess in secretword: print ("That letter is in the secret word!") dashes = update_dashes(secretword, dashes, guess) guesses_left = guesses_left - 1 else: print ("That letter is not in the secret word!") guesses_left = guesses_left - 1 if guesses_left < 0: print ("You lose! The secret word is: " + str(secretword)) else: print ("You win! The secret word is: " + str(secretword)) #This is the function to update the dashes def update_dashes(secret, thedashes, letterguess): thedashes for i in range(len(secret)): if secret[i] == letterguess: # I make result equal only to where the dash I am going to replace is and put the letter there. Then I also add the rest of the dashes. thedashes = thedashes[ :i] + letterguess + thedashes[i+1:] return thedashes get_guess()
true
6cb903321858e364f88275f741520172c27bb2b2
Pratik-Sanghani/Python-Tutorial
/Strings/stringindetail.py
1,724
4.46875
4
# A string is created by entering text between two single or double quotation marks. # e.g. create a string with single and double quotes. string1='python is fun!' print(string1) string2="I am programmer" print(string2) # python provides an easy way to avoid manually writing "\n" to escape newlines in a string. # 'customer: good morning.\n owner : good morning ,sir.welcome to the xyz shop.' # create string with three sets of quotes and newlines that are created by pressing enter are automatically escaped for you. string3=""" customer: good morning. owner : good morning ,sir.welcome to the xyz shop.""" print(string3) # in python individual characters of a string can be accessed by using the method of indexing. string4="helloworld" print(string4[0]) # o/p: s print(string4[-1]) # o/p: d # slicing in a string is done by using slicing operator(colon). # printing 2nd to 9th character print(string4[2:9]) # strings are immutable , hence elements of a string cannot be changed once it has been assigned. # updation of entire string is possible. string4="goodafternoon" print(string4) # deletion of entire string is possible with the use of del keyword . #del string4 print(string4) # string can be formatted with the use of format() method . string="{} {} {}".format( 'show ','your','code') print(string) #o/p: show your code # formatting of integer number="{0:b}".format(8) print(number) #o/p:1000 no="{0:e}".format(786.66) print(no) #o/p:7866600e+02 # as with integers and floats,string in python can be added, using a process called concatenation. print("self" + "respect") # o/p: selfrespect # string can also be multiplied by integers print("amazing" * 3) # o/p:amazingamazingamazing
true
e6f68a02dc5d9ccbc6207a038e8f2874706bb9d2
shaneleblanc/kickstartcoding
/3.2-functions/activities/3_parameters.py
2,850
4.15625
4
# REMINDER: Only do one challenge at a time! Save and test after every one. print('Challenge 1 -------------') # Challenge 1: # Write the code to "invoke" the function named challenge_1, providing a name. def challenge_1(name=None): print('Hello', name, '!') challenge_1(name='Jack') print('Challenge 2 -------------') # Challenge 2: # Uncomment the following code. Many of these functions and invocation have # typos or mistakes. Fix all the mistakes and typos to get the code running. # When running correctly, it should print dialog from a popular movie. def func_1(name=None): print(name, ':', "I can't feel my body") def func_2(name=None, other_name=None): print(name, ':', other_name, ', listen to me!') def func_3(quality='best', item='burrito'): print('Winning that', item, 'was the', quality, 'thing.') def func_4(name=None, phrase=None): print(name, ':', 'I promise.', phrase, ', Jack.', phrase) func_1(name='Rose') func_2(name='Jack', other_name='Rose') func_3(item='ticket') func_4(name='Rose', phrase="I'll never let go") print('Challenge 3 -------------') # Challenge 3: # Examine the function written that performs addition. Uncomment the code to # invoke it. Write another invocation to test it out. Use a similar pattern for # 5 other operations (subtraction, multiplication, division, exponentiation, # and modulus) def addition(a=0, b=0): print(a + b) def multiplication(a=0, b=0): print(a * b) def division(a=0, b=0): print(a / b) def exponentiation(a=0, b=0): print(a ** b) def modulus(a=0, b=0): print(a % b) addition(a=10, b=15) multiplication(a=10, b=15) division(a=10, b=15) exponentiation(a=10, b=15) modulus(a=10, b=15) print('Challenge 4 -------------') # Challenge 4: # Write a function that has a parameter that accepts a list. Have it keep on # asking for user input UNTIL that input is something within that list. # HINT: You'll use "while", "input", and "in" or possibly "not in" (for # checking inclusion within the list) def accepts_listo(x=['last', 'of', 'strings']): response = None while response not in x: response = input("are you sure?") accepts_listo() #PEP 8 print('-------------') # Bonus Challenge: # Write a function that has a dict parameter that is a "menu" of options. This # dict should have keys that consist of the text that can be entered, and # values that consist of functions. When the person selects an item from the # menu, it should execute that function. # def menu(options={}): response = None while response not in options.keys(): print("Choose from your options: ", options.keys()) response = input("? ") func = options[response] func() def func1(): print("we did func1!") def func2(): print("we did func2!") menu({'thing1': func1, 'thing2': func2})
true
4d6e8c435b308a2a729175425acb252062e4c865
Alexander-AJ-Berman/password_strength_detector
/main.py
1,410
4.375
4
#!/usr/bin/env python3 """Strong Password Detector This script allows the user to input a password and validate its strength. The criteria for a strong password are as follows: 1. At least 7 characters long 2. Contains both uppercase and lowercase letters 3. Contains at least one digit (0-9) 4. Contains at least one special character (!, @, $) There are no additional dependencies for the script other then Python3. """ #### Begin Script #### import getpass import re pwd = getpass.getpass('Password: ') # Can adjust requirements HERE reqs = { 'chars': 7, 'upper': 1, 'lower': 1, 'digit': 1, 'special': 1 } found = { 'chars': 0, 'upper': 0, 'lower': 0, 'digit': 0, 'special': 0 } for char in pwd: # Increment total chars found['chars'] += 1 # Increment alphabet chars if char.isalpha(): # Increment upper if char.isupper(): found['upper'] += 1 # Increment lower else: found['lower'] += 1 # Increment digits elif char.isdigit(): found['digit'] += 1 # Increment special chars else: found['special'] += 1 strong = True # Check if conditions are met for attr in found: if reqs[attr] > found[attr]: strong = False if strong: print("Password is STRONG") else: print("Password is WEAK")
true
a192df6516708dfba48f342e95668abd5b03913e
wizardcalidad/ClassWork
/venv/Cousera/practice.py
858
4.25
4
# x=-2 # # if x == 6 : # # print('Is 6') # # print('Is Still 6') # # print('Third 6') # # x = 0 # # if x < 2 : # # print('Small') # # elif x < 10 : # # print('Medium') # # else : # # print('LARGE') # # print('All done') # if x < 2 : # print('Below 2') # elif x >= 2 : # print('Two or more') # else : # print('Something else') # astr = 'Hello Bob' # istr = int(astr) # print('First', istr) # astr = '123' # istr = int(astr) # print('Second', istr) # astr = 'Hello Bob' # istr = 0 # try: # istr = int(astr) # except: # istr = -1 hrs = input("Enter Hours:") rate = input("Enter rate per hours:") try: h = float(hrs) r = float(rate) except: print("please,put numeric values") quit() if h <= 40: pay = h * r print(pay) elif h>=40: excess = h - 40 pay = excess * r * 1.5 + 40 * r print(pay)
false
1d9d32d24151fe50f28e878e2971d0a796f17f71
Iongtao/learning-python3
/learning/class/demo1.py
1,542
4.375
4
# !/usr/bin/env python3 # coding=utf-8 ''' 什么是类? 类一个用于模拟生活现实场景的抽象的方法 也是编程中用于面向对象编程的最有效的编程方式 根据类创建的对象称之为实例化 类的概念需要慢慢理解 ''' ''' 使用 class 关键字 跟上 类名(首字母需大写): 类的内容 由许多函数 和 属性(变量)构成 在类里面定义的函数 又被称为 方法 类中有一个特殊的方法 名为 __init__() 用于构建实例时传递属性值 self 关键字 指 当前类的实例对象 让构建的实例 可以访问当前类的 属性和方法 类的方法的第一个形参必须是self 但在调用方法的时候 不需要传递self 内部将默认关联self class Dog(): __init__(self, name, age): ''' # 例1 class Dog(): high = 10 # 类变量 # 创建时会执行 # 将 创建时 传入的 name 和 age 赋值给 创建的实例的name和age相关联 def __init__(self, name, age): # name age 都是实例属性(实例变量) self.name = name self.age = age # 对狗狗的描述 def desc(self): print('狗狗的名字叫' + self.name + ',今年已经' + str(self.age) + '周岁了') # 让狗狗坐下 def sit(self): print(self.name.title() + '坐下了') # 创建了一直名为旺财,年龄1岁的狗狗 dog_1 = Dog('旺财', 1) dog_1.desc() dog_1.sit() # 你可以使用Dog类 创建多个实例对象 dog_2 = Dog('汪汪', 2) dog_2.desc() print(Dog.high)
false
ad1fe2b895f91daf1a374f67b7537d38987bc108
dhimanmonika/PythonCode
/MISC/ArgsKwargs.py
834
4.8125
5
"""The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list.""" def testify(arg1, *argv): print("first argument :", arg1) for arg in argv: print("Next argument through *argv :", arg) testify('Hello', 'Welcome', 'to', 'GeeksforGeeks') """The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them).""" def hello(**kwargs): if kwargs is not None: for key, value in kwargs.items(): print ("%s == %s" %(key, value)) hello(name="GeeksforGeeks")
true
6e87b4af460b3ff05ac2b17091ec6838b677d308
dhimanmonika/PythonCode
/Regex/FloatNumber.py
1,136
4.34375
4
"""You are given a string . Your task is to verify that is a floating point number. In this task, a valid float number must satisfy all of the following requirements: Number can start with +, - or . symbol. You are given a string . Your task is to verify that is a floating point number. In this task, a valid float number must satisfy all of the following requirements: Number can start with +, - or . symbol. For example: ✔+4.50 ✔-1.0 ✔.5 ✔-.7 ✔+.4 ✖ -+4.5 Number must contain at least decimal value. For example: ✖ 12. ✔12.0 Number must have exactly one . symbol. Number must not give any exceptions when converted using . Number must contain at least decimal value. For example: ✖ 12. ✔12.0 Number must have exactly one . symbol. Number must not give any exceptions when converted using .""" import re T=int(input()) for i in range (T): N=str(input()) match=re.search(r'[-+]?[0-9]*\.+?[0-9]+',N) if(match): s=match.start() e=match.end() if (s==0 and e==len(N)): print("True") else : print("False") else : print("False")
true
06d564c2345c3e98843868714ae240798fa705d5
Rynxiao/python3-learn
/basic/dict.py
528
4.25
4
#!/usr/bin/env python3 # dict/map d = { 'Michael': 95, 'Bob': 75, 'Tracy': 85 } print('dict Michael', d['Michael']) # insert d['Adam'] = 78 print('after append', d) # overwrite d['Jack'] = 90 print('before overwrite', d) d['Jack'] = 88 print('after overwrite', d) # is In dict print('Thomas is in dict?', 'Thomas' in d) # get print('get Thomas None', d.get('Thomas')) print('get Thomas -1', d.get('Thomas', -1)) # delete print('before delete', d) d.pop('Bob') print('after delete', d) print('list can not be a dict key')
false
2da803123991c041b313d2b768498a081ca50a09
ajaysharma12799/Learning-Python
/Control Flow/app2.py
1,203
4.65625
5
#################################################### # Loops """ Note :- There are 3 Type of Loop 1. For Loop 2. Nested Loop 3. While Loop Note :- There are Another Variant of Each Loop's With Else Statement Also. """ # 1. For Loop for number in range(3): # By Default Start From 0 and Exclude Last Index print("Attempt", number + 1) """ range(start, end, steps) => { start : starting index end : ending index steps : number of steps or jump range function will be doing } """ """ Note :- We Have Jump Statement in Python 1. break => Will Terminate Loop 2. continue => Will Continue Iterating Loop ( Force Loop to Continue its Iteration ) 3. pass => Will Do Nothing, Simply Ignore ( Mostly Used To Place Future Code ) """ # 2. Nested Loop for i in range(5): # Outer Loop for j in range(3): # Inner Loop print( f"${i} : {j}" ) print( type(range(5)) ) # Will Return Iterable Object """ Note :- We Have Some of Complex Types 1. range 2. string 3. list Note :- We Can Iterate over Iteratable """ # 3. While Loop numbers = 100 while number > 0: print(numbers) numbers //= 2 ####################################################
true
3759298271ba14be498fc9c68bc8bde2326f5e8b
ManasveeMittal/dropbox
/Python/Python_by_udacity/renaming_files.py
772
4.3125
4
#--------PSEUDO CODE________// #define directory(s) name and path #define selection criteria for files #point to the directory(s) #specify renaming criteria #enclose file names into a list #specify replacemnt criteria into a function #loop over the file names #execution the name changes #again add the changes into a list and sort list #zip a dictionary of new file name to old file #forgot backup creation # from os import listdir # from string import translate import string import os def rename_files(): file_list = os.listdir(r"/home/triloq/manasvee/prank/") print(file_list) saved_path = os.getcwd() os.chdir((r"/home/triloq/manasvee/prank") for f in file_list: os.rename(file, file.translate("1234567890")) os.chdir(saved_path) rename_files()
true
57d939f3223a18365ed4428d759156408e2860af
ManasveeMittal/dropbox
/Python/Python_by_udacity/regEx.py
310
4.15625
4
import re str = 'an example word:cat!!' match = re.search(r'word:\w\w\w',str) print (match) # match = re.search(r'word:\w\w\w', str) # # If-statement after search() tests if it succeeded # if match: print ('found', match.group()) ## 'found word:cat' # else:print( 'did not find')
false
25f06472a39a3a3000f07a2e574d89336dec11a8
ManasveeMittal/dropbox
/DataStructures/DataStructureAndAlgorithmicThinkingWithPython-master/chapter06trees/BSTToDLLWithDivideAndConquer.py
2,507
4.125
4
# Copyright (c) Dec 22, 2014 CareerMonk Publications and others. # E-Mail : info@careermonk.com # Creation Date : 2014-01-10 06:15:46 # Last modification : 2008-10-31 # by : Narasimha Karumanchi # Book Title : Data Structures And Algorithmic Thinking With Python # Warranty : This software is provided "as is" without any # warranty; without even the implied warranty of # merchantability or fitness for a particular purpose. class Node: ''' class to represent a Node of BST/ linked list''' def __init__(self, data): self.data = data self.left = self self.right = self def printBST(root): '''prints the BST in an inorder sequence''' if root.left == root or root.right == root: print root.data, " ", else: printBST(root.left) print root.data, " ", printBST(root.right) def printList(head): '''prints the linked list in both directions to test whether both the 'next' and 'previous' pointers are fine''' # print forward direction h = head print '[%d]' % (h.data), h = h.right while h != head: print '[%d]' % (h.data), h = h.right print "" # print in reverse direction h = head.left print '[%d]' % (h.data), h = h.left while h != head.left: print '[%d]' % (h.data), h = h.left def BSTToDLL(root): ''' main function to take the root of the BST and return the head of the doubly linked list ''' # for leaf Node return itself if root.left == root and root.right == root: return root elif root.left == root: # no left subtree exist h2 = BSTToDLL(root.right) root.right = h2 h2.left.right = root root.left = h2.left h2.left = root return root elif root.right == root: # no right subtree exist h1 = BSTToDLL(root.left) root.left = h1.left h1.left.right = root root.right = h1 h1.left = root return h1 else: # both left and right subtrees exist h1 = BSTToDLL(root.left) h2 = BSTToDLL(root.right) l1 = h1.left # find last nodes of the lists l2 = h2.left h1.left = l2 l2.right = h1 l1.right = root root.left = l1 root.right = h2 h2.left = root return h1 if __name__ == "__main__": # create the sample BST root = a = Node(5) b = Node(3) c = Node(6) d = Node(2) e = Node(4) f = Node(7) a.left, a.right = b, c b.left, b.right = d, e c.right = f printBST(root) print "\ncreating to double linked list" head = BSTToDLL(root); printList(head)
true
c0225a37853adb520d9bd9487733599e3a2c3ed3
ManasveeMittal/dropbox
/Python/python_algo_implement/picking_numbers.py
1,761
4.15625
4
''' Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is <= 1. Input Format The first line contains a single integer, n, denoting the size of the array. The second line contains space-separated integers describing the respective values of a(0), .... ,a(n-1). Constraints 2<= n <= 100 0<a(i)<100 The answer will be .>= 2 Output Format A single integer denoting the maximum number of integers you can choose from the array such that the absolute difference between any two of the chosen integers is <= 1. Sample Input 0 6 4 6 5 3 3 1 Sample Output 0 3 Explanation 0 We choose the following multiset of integers from the array:{4,3,3} . Each pair in the multiset has an absolute difference <=1 (i.e., |4-3| =1 and |3-3| =0 ), so we print the number of chosen integers, 3, as our answer. Sample Input 1 6 1 2 2 3 1 2 Sample Output 1 5 Explanation 1 We choose the following multiset of integers from the array:{1,2,2,1,2} . Each pair in the multiset has an absolute difference <=1 (i.e.,|1-2| =1 ,|1-1|=0 , and |2-2| =0), so we print the number of chosen integers, 5, as our answer. ''' #!/bin/python import sys from operator import itemgetter #n = int(raw_input().strip()) #a = map(int,raw_input().strip().split(' ')) a=[4,6,6,5,3,8,4,3,1] unique_a = list(set(a)) count_a = [a.count(_) for _ in unique_a] len_set = len(count_a)-1 pair_a = [[unique_a[i], unique_a[i+1], count_a[i]*count_a[i+1]] for i in range(len_set) if (unique_a[i+1]-unique_a[i])==1] max_pair = print unique_a print count_a print pair_a print result_a #for i in range(len_set): # print unique_a(i), unique_a(i+1), count_a(i)*count_a(i+1)
true
3bb73de814a44708f6b12cb5ce294c9545b04201
dsoloha/py
/Lab04/sdrawkcab-dsoloha.py
322
4.3125
4
# Backwards-izer # Dan Soloha # 9/12/2019 word = input("Welcome to the Backwards-izer! Enter the word you would like to make backwards. Press \"enter\" at any time to exit. ") while word != "": reversed_word = list(reversed(word)) reversed_word = "".join(reversed_word) word = input(f"{reversed_word} ")
true
1cbf888fa258e090228375c88eb20e504d1df0fe
akshatakulkarni98/ProblemSolving
/DataStructures/adhoc/employee_importance.py
1,934
4.28125
4
""" You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id. For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct. Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates. Example 1: Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 Output: 11 Explanation: Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11. TC:O(N) SC:O(N) Use queue and do BFS """ """ # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ from collections import deque class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: if not employees: return -1 emp_map=dict() for i in range(len(employees)): emp=employees[i] emp_map[emp.id]=emp interested_emp=emp_map[id] result=0 queue=deque() queue.append(interested_emp) while queue: emp_node=queue.popleft() result+=emp_node.importance for sub in emp_node.subordinates: queue.append(emp_map[sub]) return result
true
519a13c91aaa73900cd8ce09e618848e8d089fef
Hadiyaqoobi/NYUx
/evennumbers.py
398
4.3125
4
""" Description Write a program that reads a positive integer n, and prints the first n even numbers. For example, one execution would look like this: Please enter a positive integer: 3 2 4 6 """ import math print("Please enter a positive integer: ") number = int(input()) for x in range (number + (number+1)): y = (x) if (y % 2 == 0) and x != 0: print(y)
true
c4daced112e6845e3a7a6ca529dfd8b06a4a2f2b
Hadiyaqoobi/NYUx
/maxabsinlst.py
616
4.28125
4
""" Implement function max_abs_val(lst), which returns the maximum absolute value of the elements in list. For example, given a list lst: [-19, -3, 20, -1, 0, -25], the function should return 25. The name of the method should be max_abs_val and the method should take one parameter which is the list of values to test. Here is an example call to the function print(max_abs_val([-19, -3, 20, -1, 0, -25])) """ import math def max_abs_val(lst): z = abs(lst[0]) x: int for x in lst: if abs(x) > z: z = abs(x) return z #print(max_abs_val([-19, -3, 20, -1, 0, -25]))
true
086fe78bd37a92f327e10430caf6635d3f474d5e
skykdg12/Inflean-Python
/chapter03_02.py
1,224
4.34375
4
# chapter03_02 # special method(magic method) # 파이썬 핵심 -> 시퀀스(sezuence), 반복(iterator), 함수(functions), class # 클래스안에 정의할 수 있는 특별한(built in) 메소드 # 클래스 예제2 # 벡터(x,y) (5,2) # (10,3) * 5 = (50,15) class Vector(object): def __init__(self, *args): ''' Create a vector, example : v = Vector(5, 10) ''' if len(args) == 0: self._x, self._y = 0, 0 else: self._x, self._y = args def __repr__(self): '''Return the vector informations''' return 'Vector(%r, %r)' % (self._x, self._y) def __add__(self, other): '''Return the vector add self and other''' return Vector(self._x + other._x, self._y + other._y) def __mul__(self, y): return Vector(self._x * y, self._y * y) def __bool__(self): return bool(max(self._x, self._y)) # Vector 인스턴스 생성 v1 = Vector(5, 7) v2 = Vector(23, 35) v3 = Vector() # 매직메소드 출력 print(Vector.__init__.__doc__) print(Vector.__repr__.__doc__) print(Vector.__add__.__doc__) print(v1, v2, v3) print(v1 + v2) print(v1 * 3) print(v2 * 10) print(bool(v1), bool(v2)) print(bool(v3))
false
800882163959ab906f62318b269f18a2f12e4e5c
gitcodes/SortingAlgorithms
/Bubblesort/BubbleSort.py
571
4.1875
4
#--------------------------------------------------- # # Bubble Sort In python # #--------------------------------------------------- def bubble_sort(collection): length = len(collection) for i in range(length-1, -1, -1):#range(length-1, -1, -1) for j in range(i):#range(1, i) if collection[j] > collection[j+1]: collection[j], collection[j+1] = collection[j+1], collection[j] return collection if __name__ == '__main__': import sys unsorted = [15,11,20,14,12,13,17,16,18,19] print(bubble_sort(unsorted))
false
39d6c64e73affacc14c0ec0f87f33c547d3f80ed
twitu/bot_programming
/movement_cost.py
2,858
4.28125
4
import random import math def linear_cost(scale=1): """ Manhattan distance, only linear movement is allowed Args: start (int, int): x and y coordinates of start point end (int, int): x and y coordinates of end point scale (int): scale of one step Returns: Returns linear cost function between start and end point """ def cost(start, end): delta_x = abs(start.x - end.x) delta_y = abs(start.y - end.y) return (delta_x + delta_y) * scale return cost def euclidean_cost(scale=1): """ Euclidean distance, linear and diagonal movement is allowed, cost of diagonal movement is calculated using square root method Args: start (int, int): x and y coordinates of start point end (int, int): x and y coordinates of end point scale (int): scale of one step Returns: Returns euclidean cost function between start and end point """ def cost(start, end): delta_x = abs(start.x - end.x) delta_y = abs(start.y - end.y) return math.sqrt(delta_x * delta_x + delta_y * delta_y) * scale return cost def diagonal_cost(lin=1, diag=1): """ Diagonal distance, 8 directions. Linear and diagonal movement is allowed at same cost For lin = 1 and diag = 1, gives octile distance For lin = 1 and diag = root 2, gives triangle distance Args: start (int, int): x and y coordinates of start point end (int, int): x and y coordinates of end point lin int: scale of one linear step diag int: scale of one diagonal step Returns: Returns diagonal cost function between start and end point """ def cost(start, end): delta_x = abs(start.x - end.x) delta_y = abs(start.y - end.y) return (delta_x + delta_y) * lin + min(delta_x, delta_y) * (diag - 2 * lin) return cost def scaled_cost(h_func, p_scale): """ Scales cost function based on given parameter Args: h_func: cost function p_scale: scales cost function multiple times Returns: Scaled cost function """ def cost(start, end): return h_func(start, end) * p_scale return cost def randomized_cost(sigma, mu, h_func): """ Generates random number with normal distribution based on given sigma and mu. Scales cost function by generated random number. Suggested values are mu = 1 and 0.2 < mu < 0.3, for realistic paths. Args: sigma: standard deviation in normal distribution mu: average value in normal distribution h_func: cost function Returns: Randomly scaled cost function """ def cost(start, end): return h_func(start, end) * random.normalvariate(mu, sigma) return cost
true
75e29eca8678e26edc74b1fb6046214a89d666ca
farhana13/python
/tup.py
1,848
4.375
4
#tuples are unmodified lists x = ('john', 'sally', 'bob') print ( x[2]) #constant syntax y = (1, 9, 2) print (y) print (max(y)) for iter in y: print (iter) # unlike lists once you create a tuple, you cannt alter its contents-similar to a string. x = [9,8,7] x[2] = 6 print (x) #things not to do with tuples # x = (3,2,1) # x.sort() # x.append(5) # x.reverse() # tuple on the left hand side (x, y) = (4, 'fred') print (y) (a, b) = (99, 98) print (a) # tuples and dictionaries # items() method in dict returns a list of key, value tuples. d = dict() d ['john'] = 2 d ['bob'] = 4 for (k,v) in d.items() : print (k,v) tups = d.items() print (tups) # tuples are comparable t = (0,1,2) < (5, 1,2) print (t) tup = (0,1,2000000) < (0,3,4) print (t) tupl= ( 'jenny', 'zob') > ('adams', 'silvi') print (tupl) #sorting lists of tuples, keys d = {'a' : 10, 'b' : 1, 'c' : 22} p = d.items() print (p) pp = sorted (d.items()) print (pp) #using sorted, key order d = {'a' : 10, 'b' : 1, 'c' : 22} tp = sorted(d.items()) print (tp) for k,v in sorted(d.items()) : print (k,v) #key value tuples- value key c = {'a' : 10, 'b' : 1, 'c' : 22} tmp = list() for k,v in c.items(): tmp.append( (v, k) ) print (tmp) tmp = sorted(tmp, reverse=True) print(tmp) # solve a problem, find ten most common words fhand = open ('intro.txt') counts = dict() for line in fhand : words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 lst = list() for key,val in counts.items(): newtup = (val,key) lst.append(newtup) lst = sorted(lst, reverse=True) for val,key in lst[:10]: print (key, val) #do this in only one line #list comprehension c = {'a': 10, 'b':1, 'c':22} print (sorted ( [ (v , k) for k, v in c.items() ] ) )
true
926e88c0edd8d8d3a29f528fba82efc0fd1c838e
jambellops/redxpo
/mitx6.00/creditcode.py
2,643
4.28125
4
## ## Title: Credit statement ## Author: James Bellagio ## Description: Calculation of Credit Statement assignment for edx mit 6.00 week 2 ## ## ## ## ## ## # def balance_unpaid(balance, payment): # """ function of remaining balance after payment # parameter: balance = initial balance # parameter: payment = payment # return: balance leftover after payment (can be negative)""" # return balance - payment # def bal_w_interest(unpaid_balance, mo_interest): # """ function of balance after interest is applied # parameter: unpaid_balance = balance left after last payment (can be negative) # parameter: mo_interest = monthly percentage rate as a decimal # return: new balance after adding interest accrued (will not accrue interest if negative)""" # if (unpaid_balance < 0): # return 0 # else: # return unpaid_balance + (mo_interest * unpaid_balance) # monthlyPaymentRate # annualInterestRate # balance def interest_mo(annualInterestRate): """ function to convert Annual percentage rate to monthly interest parameter: interest as a decimal return: interest rate for one month""" return interest/12.0 def minimo_payment(minim_rate, last_balance): """ function to determine minimum monthly payment parameter: minim_rate = decimal value of payment rate. equivalent to percentage balance paid parameter: last_balance = balance after last payment return: minimum amount to pay (should never go negative; if last_balance is negative return zero""" if (last_balance < 0): return 0 else: return minim_rate * last_balance def mon_unpaid_bal(last_balance, payment): """ function to determine upaid portion of balance paremeter: last_balance = balance after last payment parameter: payment = current payment return: unpaid balance after payment is applied""" return last_balance - payment def unpaid_w_interest(unpaid, interest): """function to determine balance after interest is applied parameter: unpaid = balance after payment is applied parameter: interest = monthly interest as a decimal return: new balance with interest""" return unpaid + unpaid*interest monInterest = interest_mo(annualInterestRate) print('balance = '+str(balance)) print('annualInterestRate = '+str(annualInterestRate)) print('monthlyPaymentRate = '+str(monthlyPaymentRate)) for i in range(12): pay = minimo_payment(monthlyPaymentRate, balance) print(pay) newbalance = unpaid_w_interest(mon_unpaid_bal(balance, pay), monInterest) print(newbalance) balance = newbalance
true
535d4cbb8a14c2b1d5b03d8cd2791a875b3b1c6b
Hacklad/Mygame
/quizgame.py
1,093
4.1875
4
print("Welcome to my computer quiz!") playing = input("Do you want to play, Yes or No? ") if playing.lower() != "yes": quit() print("Okay! Let's play :)") score, scored = 0, 0 answer = input("What does CPU stand for? ") scored += 1 if answer.lower() == "central processing unit": print('Correct!') score += 1 print('Your score is currently ', score, 'out of', scored ) else: print("Incorrect!") answer = input("What does GPU stand for? ") scored += 1 if answer.lower() == "graphics processing unit": print('Correct!') score += 1 print('Your score is currently ', score, 'out of', scored ) else: print("Incorrect!") answer = input("What does RAM stand for? ") scored += 1 if answer.lower() == "random access memory": print('Correct!') score += 1 print('Your score is currently ', score, 'out of', scored ) else: print("Incorrect!") answer = input("What does PSU stand for? ") scored += 1 if answer.lower() == "power supply": print('Correct!') score += 1 print("You scored ",score, "out of 4") else: print("Incorrect!")
true
a864a339df5ff230eca56cda8829395e77e28a37
angela97lin/Sophomore-Year
/hw29-<Lin Angela>/hw29.py
2,569
4.21875
4
#Angela Lin ##pd 06 ##HW29 ##05=06=13 ##Write a Python script that will read in a literary work of appreciable length and print its 30 most frequently occurring words. ## ##General guidelines: ##Place your files in a folder named “hw29-<Last First>”, then compress this folder into a ZIP archive. (no RAR!) ##Upload to the homework server. ##Include heading and descriptive in-line comments. ## ##Outline of approach: ##Download a TXT file (from gutenberg.org or other source for public domain works) ##Manually curate text (remove intro & end text) ##Create list of “words” separated by whtspc ##Automate some curating: ##Convert words to lowercase ( s.lower() ) ##Strip words of their punctuation ##Create a dictionary key for each word, with its value being that word's frequency in text ##Print top 30 most frequently occurring words along with each's frequency ## ##Deliverables: ##<chosen work of lit>.txt ##freq30.py def textextract(): retString="" FINALStr="" retList=[] d={} numofVal=0 for line in open("myths.txt").readlines(): retString+=line retString=retString.replace("(","") retString=retString.replace(")","") retString=retString.replace(".","") retString=retString.replace(",","") retString=retString.replace(";","") retString=retString.replace('"','') #Couldn't get strip to work, so I used replace retString=retString.replace("'","")#for each punctuation. retString=retString.replace("_","") retString=retString.replace("-"," ") retString=retString.lower() retString=retString.strip() retString=retString.replace("\n"," ") retList=retString.split(" ") print retList for a in retList: if d.has_key(a)==False: d[a]=0 ##if a is not a key in d, make it a key with an assigned value of 0 #print d.values() #print d.keys() for a in retList: #2nd runthrough! This time, every time the same word is encountered, return add to the value of d[a] by 1 d[a]+=1 #print d.values() freqL=d.values() freqCorrespond=d.keys() while numofVal<=30: maxV=max(freqL) #print maxV #print freqL FINALStr+=str(maxV)+" "+str(freqCorrespond[freqL.index(maxV)])+"\n" #appends the freq, the word, and \n freqCorrespond=freqCorrespond[:freqL.index(maxV)]+freqCorrespond[(freqL.index(maxV)+1):] #slices lists to delete the previous max values freqL=freqL[:freqL.index(maxV)]+freqL[freqL.index(maxV)+1:] numofVal+=1 return FINALStr print textextract()
true
3889d29dae8dcf030513efa784bd87e19ad6737b
wolf2000/fastcampus
/AhReum_Han.py
621
4.25
4
#글자 수 세기 #특정 문자열을 매개변수로 넣기 매개변수로 넣으면 길이를 반환 #a = 'python is too hard' #print(a.count('')) def word_count(word): word_cnt=word.split(" ") return len(word_cnt) print(word_count('python is too hard')) ##search def search(string,word): if type(string)==str: new_string= string.split(" ") elif type(string)== tuple: new_string= string.split(" ") elif type(string)== list: new_string= string.split(" ") return True else: return False string = 'i wanna something to eat' word = ({'A':'a','B':'b','C':'c'}) print(search('A'))
false
7a35a83576f488ce9f1f1e239b0d741b6f782ee5
ofs8421/MachineLearning
/SimpleChat/SimpleChat.py
2,182
4.125
4
import re prompts = { "what": "What is a video game?", "use": "What are video games used for?", "companies": "what companies make video games?", "long": "how long have video games been out?" } responses = { "what": "A video game is an electronic game that involves interaction with a user interface to generate visual feedback on a two- or three-dimensional video display device such as a TV screen, virtual reality headset or computer monitor.", "use": "video games are used for entertainment purpouses.", "who": "Xbox, PlayStation, and Ninteno are the three major companies that make video games.", "long": "the earliest video gamea Cathode ray tube Amusement Device was filed for a patent on 25 January 1947, by Thomas T. Goldsmith Jr. and Estle Ray Mann, and issued on 14 December 1948, as U.S. Patent 2455992." } def processInput(userInput): userInput = re.sub(r'[^\w\s]', '', userInput) words = userInput.split(" ") #print(words) matchingKeys = [] for word in words: if word in responses.keys(): matchingKeys.append(word) if len(matchingKeys) == 0: return "I do not know that" elif len(matchingKeys) == 1: return responses[matchingKeys[0]] else: print("I am not sure what you mean. Did you mean: ") index = 1 for key in matchingKeys: print(str(index) + ": " + prompts[key]) index += 1 valid = False while not valid: selected = int(input("#: ")) if selected <= len(matchingKeys) and selected > 0: valid = True else: print("Please enter one of above") return responses[matchingKeys[selected - 1]] def main(): print("Welcome to video game facts! I can tell you about vidio games!\n") print("Ask me a question or type in quit\n") userInput = "" while userInput != "quit": userInput = input("what is your question? ").lower() #print(userInput) if userInput != "quit": response = processInput(userInput) print(response) print("It was nice talking to you. Bye!") main()
true
1490abf534ed1dd6c45ecbd2bac1d092c53c6690
RaihanHeggi/pythonProgramChallenge_40
/Second Challenge (Miles Per Hour Conversion App)/Miles Per Hour Conversion App.py
303
4.125
4
print("Welcome to the MPH and MPS Conversion App\n") #getting MPH value milesPerHour = float(input('What is your speed in miles per hour: ')) #conversion MPH to MPS and Print it conversionToMPS = milesPerHour * 0.4474 print("Your speed in meter per second is "+str(round(conversionToMPS, 2)))
true
f80bb349a818334a93e74cbc13eb9966f1ab0acb
RaihanHeggi/pythonProgramChallenge_40
/Fourth Challenge (Right Triangle Problem)/Right Triangle Solver.py
642
4.3125
4
import math print("Welcome to the Right Triangle Solver App\n") firstLeg = float(input("What is the first leg of the triangle: ")) secondLeg = float(input("What is the second leg of the triangle: ")) #calculate third leg with pythagorean theorem c^2 = a^2+b^2 thirdLeg = round(math.sqrt(firstLeg**2 + secondLeg**2),3) #calculate triangle area area = round((1/2)*firstLeg*secondLeg, 3) #Print the result print("\nFor a triangle with legs of "+str(firstLeg)+" and "+str(secondLeg)+" the hypotenuse is "+str(thirdLeg)) print("For a triangle with legs of "+str(firstLeg)+" and "+str(secondLeg)+" the area is "+str(area))
true
d23932c4063ca81ce95f25d8fcf758948f33dbee
iproduct/intro-python
/01-sdp-intro/hello_python.py
612
4.3125
4
def hello_python(name): """ simple function demo using name as argument """ print(f'Hello, {name}!') def conditional_print(number): # conditional print demo if number > 2: print(f"{number} is greater than two!") elif number == 2: print(f"{number} is equal to two!") else: print(f"{number} is less than two!") if __name__ == '__main__': hello_python('Python Programmer') conditional_print(5) quantity = 3 itemno = 567 price = 49.95 my_order = f"I want {quantity} pieces of item {itemno} for {price} dollars." print(my_order)
true
da6baa041385da08cea4f5c3fcd2e65726eda81a
iproduct/intro-python
/07-up-2021/animals.py
1,488
4.125
4
class Animal(object): def __init__(self, animalName): print(animalName, 'is a animal.') def make_sound(self): pass class Mammal(Animal): def __init__(self, mammalName): # super(Mammal, self).__init__(mammalName) super().__init__(mammalName) print(mammalName, 'is a warm-blooded.') # method overriding def make_sound(self): print("Sound: Some mammal sound") class Terrrestrial(Animal): def __init__(self, terrestrialName): super().__init__(terrestrialName) print(terrestrialName, 'can walk.') # method overriding def make_sound(self): print("Sound: Walking sound") class Cat(Mammal): def __init__(self): super().__init__('Cat') print('Im a Cat with four legs') # method overriding def make_sound(self): print("Sound: Miao, Miao") class Dog(Mammal, Terrrestrial): def __init__(self): super().__init__('Dog') print('I am Dog with four legs') # method overriding # def make_sound(self): # print("Sound: Bao, Bao") class Mouse(Mammal): def __init__(self): super().__init__("Mouse") print('I am Mouse with four legs') # method overriding def make_sound(self): print("Sound: Cirr, Cirr") def orchestra(animals): for animal in animals: animal.make_sound() # polymorphism if __name__ == "__main__": d1 = Dog() c1 = Cat() orchestra([d1,c1, Mouse()])
false
87ce4989653a6f39744ae712ea68ed9d63ef4e77
iproduct/intro-python
/01-python-academy-intro-lab/examples.py
686
4.40625
4
"""Python intro examples""" def square(x): """Squares the argument""" print(__name__) return x * x if __name__ == "__main__": m = map(square, range(1,5)) m2 = map(square, range(1,5)) for item in m: print(item) print(list(m2)) print([it * it for it in map(square, range(1,5)) if it % 2 == 0]) print(tuple(it * it for it in map(square, range(1, 5)) if it % 2 == 0)) print({it * it for it in map(square, range(1, 5)) if it % 2 == 0}) d = {it: it * it for it in map(square, range(1, 5)) if it % 2 == 0} lkv = list(d.items()) print (lkv) print(list(d.keys())) print(list(d.values())) print(*(e for e in lkv))
false
ed35cd88762201402e889eb925cff52126b562f2
Jock2018/LeetCode_Notes
/LeetCode/基础数据结构/剑指offer/LeetCode剑指Offer10-11青蛙跳台阶问题.py
1,387
4.21875
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ 时间:2021/9/12 22:08 LeetCode原题链接:https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof/ """ # import functools import functools from typing import List # class Solution: # """解法一:递归""" # # def numWays(self, n: int) -> int: # if n == 0: # return 1 # if n == 1: # return 1 # return self.numWays(n - 1) + self.numWays(n - 2) # class Solution: # """解法二:递归 + lru 缓存""" # # @functools.lru_cache # def numWays(self, n: int) -> int: # if n == 0: # return 1 # if n == 1: # return 1 # return self.numWays(n - 1) + self.numWays(n - 2) class Solution: """解法三:递归 + 缓存""" def numWays(self, n: int) -> int: memo = [-1] * (n + 1) return self._jump(n, memo) def _jump(self, n: int, memo: List[int]) -> int: if n in (0, 1): return 1 if n == 2: return 2 if memo[n] > -1: return memo[n] memo[n] = (self._jump(n - 1, memo) + self._jump(n - 2, memo)) % (10 ** 9 + 7) return memo[n] # if __name__ == "__main__": # solution = Solution() # assert solution.numWays(2) == 2 # assert solution.numWays(0) == 1 # assert solution.numWays(7) == 21
false
b356a833d21fb1db87a254dfb8f243fff94ba7a5
Jock2018/LeetCode_Notes
/LeetCode/基础数据结构/递归/LeetCode70爬楼梯.py
1,342
4.34375
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ 时间:2021/9/12 21:35 LeetCode原题链接:https://leetcode-cn.com/problems/climbing-stairs/submissions/ """ # import functools from typing import List # class Solution: # """解法一:递归""" # # def climbStairs(self, n: int) -> int: # if n == 1: # return n # if n == 2: # return n # return self.climbStairs(n - 1) + self.climbStairs(n - 2) # class Solution: # """解法二:递归 + lru 缓存""" # # @functools.lru_cache # def climbStairs(self, n: int) -> int: # if n == 1: # return n # if n == 2: # return n # return self.climbStairs(n - 1) + self.climbStairs(n - 2) class Solution: """解法三:递归 + 缓存""" def climbStairs(self, n: int) -> int: memo = [0] * (n + 1) return self._climb(n, memo) def _climb(self, n: int, memo: List[int]) -> int: if n == 1: return n if n == 2: return n if memo[n] > 0: return memo[n] memo[n] = self._climb(n - 1, memo) + self._climb(n - 2, memo) return memo[n] # # if __name__ == "__main__": # solution = Solution() # assert solution.climbStairs(2) == 2 # assert solution.climbStairs(3) == 3
false
f1b2372df97f341cee90b42b78653a97aa2d0214
Jock2018/LeetCode_Notes
/LeetCode/基础数据结构/剑指offer/LeetCode剑指 Offer59I滑动窗口的最大值.py
2,045
4.15625
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ 时间:2021/4/25 22:38 LeetCode原题链接:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/ """ from typing import List class Solution1: """暴力解""" def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: if not nums or k == 1: return nums left, right, result = 0, k, [] while right <= len(nums): max_num = max(nums[left: right]) result.append(max_num) left += 1 right += 1 return result class Solution: """暴力解""" def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: if len(nums) <= 1 or k == 1: return nums left, right, = 1, k max_num, result = max(nums[:k]), [] result.append(max_num) while right < len(nums): if nums[right] > max_num: max_num = nums[right] elif nums[left] == max_num: max_num = max(nums[left:right]) result.append(max_num) right += 1 left += 1 return result if __name__ == "__main__": # nums = [1, 3, -1, -3, 5, 3, 6, 7] # k = 3 # solution = Solution() # print(f"预期:[3, 3, 5, 5, 6, 7]") # print(f"实际:{solution.maxSlidingWindow(nums, k)}") # # # 为空 # nums = [] # k = 0 # solution = Solution() # print(f"预期:[]") # print(f"实际:{solution.maxSlidingWindow(nums, k)}") # # # 为 1 # nums = [1] # k = 1 # solution = Solution() # print(f"预期:[1]") # print(f"实际:{solution.maxSlidingWindow(nums, k)}") # # # 为 2 # nums = [1, -1] # k = 1 # solution = Solution() # print(f"预期:[1, -1]") # print(f"实际:{solution.maxSlidingWindow(nums, k)}") # 为 3 nums = [7, 2, 4] k = 2 solution = Solution() print(f"预期:[7, 4]") print(f"实际:{solution.maxSlidingWindow(nums, k)}")
false
78f22d692251e798a4ef6485381b86609140dfe9
JonArmen/Python_kurtsoa
/07-ejercicios/ejercicio1.py
437
4.34375
4
""" Ejercicio1. - Crear variables: una "pais" y otra "continente" - Mostrar su valor por pantalla (imprimir) - Poner un comentario diciendo el tipo de dato """ pais = "España" # string continente = "Europa" # string year = 2021 #integer print(f"El país que vamos a mostrar es {pais}") print(f"El continente a mostar es {continente}") print(f"{pais} - {continente} - {str(year)}") print(type(pais)) print(type(continente))
false
269ebcd1231bbfc25e64ec016931a8b35fba0715
engrishmuffin/LPTHW
/ex15.py
775
4.15625
4
from sys import argv # prompts user to name the file they would like opened. script, filename = argv # defines txt by opening the file(name) defined in the argv txt = open(filename) # prints the name of the file, and reads the opened txt. print "Here's your file %r:" % filename print txt.read() # closes txt, which was defined by opening the file. txt.close(); # runs user through same process, # this time asking for the filename within the program print "type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read() # closes the opened file which was used to define txt_again. txt_again.close(); # the next line should cause an error, because txt_again is closed. # print txt_again.read() # it DID, it DID cause an error!!!
true
804c3808c9655e4af4b869a393eef7735b2a096a
dylanjackman/cp1404practicals
/Prac_05/hex_colours.py
523
4.15625
4
hex_colours = {"AliceBlue": '#f0f8ff', "Beige": '#f5f5dc', "Brown": '#a52a2a', 'Black': '#000000', 'Coral': '#ff7f50'} hex_colour = input('Please input either AliceBlue, Beige, Brown, Black or Coral: ') hex_colour = hex_colour.capitalize() while hex_colour != "": if hex_colour in hex_colours: print(hex_colour, 'is', hex_colours[hex_colour]) else: print("Invalid Choice") hex_colour = input('Please input either AliceBlue, Beige, Brown, Black or Coral') hex_colour = hex_colour.capitalize()
false
ee63085a5fd07e4515d7271b8aad5a3238a085bc
Marist-CMPT120-FA19/Patrick-Sach-Lab-5
/Sentence Statistics.py
505
4.25
4
def sentencestatistics (): words = input("Please enter a sentance: ").lower() #Input a sentence number = len(words) #Counts the length of the sentance print("The number of characters in your sentance is: ", number) count=len(words.split())#Splits the sentence and counts the words print("The number of words is: ", count) average= float(number/count) # divides the number of characters by the number of words print("The average word length is: ", average) sentencestatistics()
true
de0442782a4904785f306d3059d1666e8428a4d6
soumyaevan/PythonProgramming
/CSV/FindUser.py
911
4.3125
4
''' find user For this exercise, you'll be working with a file called users. csv user's last name. Implement the following function: Each row of data consists of two columns: a user's first name, and a Takes in a first name and a last name and searches for a user with that first and last name in the file. If the user is find user users. csv found, find_user returns the index where the user is found. Otherwise it returns a message stating that the user wasn't found. ''' ''' find_user("Colt", "Steele") # 1 find_user("Alan", "Turing") # 3 find_user("Not", "Here") # 'Not Here not found.' ''' import csv def find_user(fname, lname): with open("users.csv") as file: csv_reader = csv.reader(file) data = list(csv_reader) for item in data: if fname in item and lname in item: return data.index(item) return "{} {} not found".format(fname, lname)
true
c300973f6439df6f9027265f1558d78790b8cfbe
blafuente/self_taught_programmer_lesson
/loop.py
2,057
4.5625
5
# Loops # There's two different kinds of loops # - For loops # - used for iterating: one by one through an iterable like a list or a string # example: name = "Brian" for character in name: print(character) shows = ["GOT", "Narcos", "Vice"] for show in shows: print(show) coms = ("A. Developemnt", "Friends", "Always Sunny") for show in coms: print(show) people = { "G. Blurth II" : "A. Development", "Barney" : "HIMYM", "Dennis" : "Always Sunny" } for character in people: print(character) tv = ["GOT", "Narcos", "Vice"] i = 0 for show in tv: new = tv[i] new = new.upper() tv[i] = new i += 1 print(tv) all_shows = [] for show in tv: all_shows.append(show.upper()) for show in coms: all_shows.append(show.upper()) print(all_shows) # Print each item in the list ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"] and it's # index. Makre sure to print its index first. Then, print the movie name. shows = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"] for i in shows: print(str(shows.index(i)) + " " + i) # solution they wanted print(shows.index(i)) print(i) ################################################################################################################ # While Loops # Executes code as long as an expression evaluates to True. x = 10 while x > 0: print('{}'.format(x)) x -= 1 print("Happy New Year!") # With an expression that always evalutes to True is called an Infinite Loop qs = [ "What is your name? ", "what is your fav. color? ", "What is your quest? " ] n = 0 while True: print("Type q to quit.") a = input(qs[n]) if a == "q": break n = (n + 1) % 3 # Multiply all the numbers in the list [8, 19, 4] with all the numbers in the list [9, 1, 33], and # append each result to a third list and print the third list. list1 = [8, 19, 4] list2 = [9, 1, 33] results = [] for i in list1: for j in list2: x = i * j results.append(x) print(results)
true
94e89ffb4dfbfec8b632051d9dcb37a822014930
freshklauser/_Repos_HandyNotes
/_CommonMethod/ClassDefineBase/IterDefined/squares.py
1,197
4.25
4
# -*- coding: utf-8 -*- # @Author: KlausLyu # @Date: 2020-04-09 08:55:08 # @Last Modified by: KlausLyu # @Last Modified time: 2020-04-09 09:43:54 '''{自定义迭代器} 实现自动迭代平方运算 Tips: __iter__机制中,__iter__只循环一次,一次循环之后就会变为空 比如,下列测试代码中,如果执行了 print(list(iter_nums)) 之后, list(iter_nusm)就变为空 ''' class Squares: def __init__(self, nums): self.nums = nums self.offset = 0 def __iter__(self): return self def __next__(self): if self.offset >= len(self.nums): raise StopIteration else: item = self.nums[self.offset] self.offset += 1 return item ** 2 if __name__ == '__main__': nums = [1,4,2,6,8,10] iter_nums = Squares(nums) print(type(iter_nums)) # [1, 16, 4, 36, 64, 100] print(list(iter_nums)) # [1, 16, 4, 36, 64, 100] print(len(list(iter_nums))) print(type(iter_nums)) # 上面两行执行后就无法执行该for循环了,why?? for i in iter_nums: print('i --> ', i)
false
ce710998b400ffec9c8f66db8fa3958b3a42174d
bronwyn-w/my_python_code
/dictionaries4.py
1,704
4.4375
4
# Third lesson using python dictionaries #define a few dictionaries containing information about pets pet_1 = { 'ownername':'bianca', 'petname':'nemo', 'breed':'clownfish', 'type':'fish', } pet_2 = { 'ownername':'xenia', 'petname':'wilson', 'breed':'mutt', 'type':'dog', } pet_3 = { 'ownername':'fikret', 'petname':'honey badger', 'breed':'grey tabby', 'type':'cat', } pet_4 = { 'ownername':'bronwyn', 'petname':'gaston', 'breed':'brittany', 'type':'dog', } pets=[pet_1,pet_2,pet_3,pet_4] for pet in pets: print(f"\n{pet['ownername'].title()} has a pet {pet['type']}. \ The breed is a {pet['breed']} and its name is {pet['petname'].title()}.") # Example of lists within dictionaries vacationspots = { 'bianca':['antarctica','morroco'], 'xenia':['australia','new zealand', 'bahamas'], 'zephyr':['ecuador','argentina','bahamas'], } for name in vacationspots.keys(): print(f"\n{name.title()} wants to go to:") for spot in vacationspots[name]: print(f"\t{spot.title()}") #Example of dictionary within dictionary cities = { 'atlanta':{ 'state':'georgia', 'population':'6 million', 'growth':'increasing', }, 'san diego':{ 'state':'california', 'population':'3.3 million', 'growth':'stable', }, 'davenport':{ 'state':'iowa', 'population':'100,000', 'growth':'decreasing', }, } for city, info in cities.items(): print(f"\n{city.title()} is located in {info['state'].title()},") print(f"Its population is {info['population']} and {info['growth']}.")
false
cb65f759b04a644983e34e0988ab7e84ba40a76a
kiriyan1989/Pythonlearn
/17 - expo fun.py
469
4.3125
4
#print(2**3) ## power (expo) def raise_to_power (base_num, pow_num): result = 1 for i in range (pow_num): result = result * base_num return result print(raise_to_power(2, 4)) ############# Same as above but without the loop######### def raise_to_power_2 (base_num, pow_num): ## base_num & pow_num are local to the function return base_num**pow_num ## power (expo) is easy in python print(raise_to_power_2(2, 4))
true
7427f0e0101c39d1f6397855326f694c3c78d0ff
CalicheCas/IS211_Assignment10
/load_pets.py
2,432
4.375
4
#! src/bin/python3 # -*- coding: utf-8 -*- import sqlite3 def load_data(conn, data): try: cur = conn.cursor() cur.execute('SELECT SQLITE_VERSION()') v = cur.fetchone()[0] print("SQLite version: {}".format(v)) cur.execute("CREATE TABLE person(id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, age INTEGER)") cur.execute("CREATE TABLE pet(id INTEGER PRIMARY KEY, name TEXT, breed TEXT, age INTEGER, dead INTEGER)") cur.execute("CREATE TABLE person_pet(person_id INTEGER, pet_id INTEGER)") # Execute insert statements for schema, values in data.items(): if schema == "Person": sql = "INSERT INTO person VALUES (?, ?, ?, ?)" cur.executemany(sql, values) elif schema == "Pet": sql = "INSERT INTO pet VALUES (?, ?, ?, ?, ?)" cur.executemany(sql, values) else: sql = "INSERT INTO person_pet VALUES (?, ?)" cur.executemany(sql, values) conn.commit() # Test query cur.execute("SELECT * from person") d = cur.fetchall() for row in d: print(row) except sqlite3.Error as error: print("Failed to load data. Error: {}".format(error)) # 2 What is the purpose of the person_pet table? # To connect/join person table with pet table def get_data(): d = { "Person": [(1, 'James', 'Smith', 41), (2, 'Diana', 'Greene', 23), (3, 'Sara', 'White', 27), (4, 'William', 'Gibson', 23)], "Pet": [(1, 'Rusty', 'Dalmation', 4, 1), (2, 'Bella', 'AlaskanMalamute', 3, 0), (3, 'Max', 'CockerSpaniel', 1, 0), (4, 'Rocky', 'Beagle', 7, 0), (5, 'Rufus', 'CockerSpaniel', 1, 0), (6, 'Spot', 'Bloodhound', 2, 1)], "Person_Pet": [(1, 1), (1, 2), (2, 3), (2, 4), (3, 5), (4, 6)] } return d if __name__ == '__main__': conn = None try: conn = sqlite3.connect('pets.db') except sqlite3.Error as error: print("Failed to establish database connection. Error: {}".format(error)) values = get_data() load_data(conn, values) if conn: conn.close()
false
d67901e609311c9f6a2f190f9884adfa183f8429
mdfaizan7/google-foobar
/solar_doomsday.py
2,051
4.25
4
# Solar Doomsday # ============== # Who would've guessed? Doomsday devices take a LOT of power. # Commander Lambda wants to supplement the LAMBCHOP's quantum antimatter reactor core with solar arrays, # and she's tasked you with setting up the solar panels. # Due to the nature of the space station's outer paneling, all of its solar panels must be squares. # Fortunately, you have one very large and flat area of solar material, # a pair of industrial-strength scissors, and enough MegaCorp Solar Tape(TM) to piece together # any excess panel material into more squares. # For example, if you had a total area of 12 square yards of solar material, # you would be able to make one 3x3 square panel (with a total area of 9). # That would leave 3 square yards, so you can turn those into three 1x1 square solar panels. # Write a function solution(area) that takes as its input a single unit of measure representing # the total area of solar panels you have (between 1 and 1000000 inclusive) and returns a list of # the areas of the largest squares you could make out of those panels, starting with the largest squares first. # So, following the example above, solution(12) would return [9, 1, 1, 1]. # Languages # ========= # To provide a Python solution, edit solution.py # To provide a Java solution, edit Solution.java # Test cases # ========== # Your code should pass the following test cases. # Note that it may also be run against hidden test cases not shown here. # -- Python cases -- # Input: # solution.solution(15324) # Output: # 15129,169,25,1 # Input: # solution.solution(12) # Output: # 9,1,1,1 # -- Java cases -- # Input: # Solution.solution(12) # Output: # 9,1,1,1 # Input: # Solution.solution(15324) # Output: # 15129,169,25,1 def solution(area): # Your code here ans = [] while area > 0 : biggestSize = int(area ** .5) biggestArea = biggestSize ** 2 area -= biggestArea ans.append(biggestArea) return ans print(solution(15324)) print(solution(12))
true
9d9022808b3c02c0da9a84804ca8746f9724ceb7
Ze1598/Programming-challenges
/programming_challenges/anagram.py
2,300
4.375
4
#codeacademy challenge #https://discuss.codecademy.com/t/challenge-anagram-detector/83127 string1 = input('Enter the first expression:') #string input 1 string2 = input('Enter the second expression:') #string input 2 #calculate factorial def result_fact(x): fact = 1 for x in range(x,0,-1): fact *= x return fact #this list is used to make sure only letters are counted as characters contained in the inputs alphabet_caps=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] string1_letters=[] #list to contain all letters used in string1 string2_letters = [] #list to contain all letters used in string2 #getting all the characters in the first string for char in string1: if char in alphabet: #only letters matter for this string1_letters.append(char) #getting all the characters in the second string for char in string2: if char in alphabet: #only letters matter for this string2_letters.append(char) if sorted(string1_letters) != sorted(string2_letters): print('The expressions you entered aren\'t anagrams because the same letters aren\'t used in equal proportion in each expression.') else: #if the expressions are an anagram print('The expressions you\'ve entered are an anagram.') anagrams_divisor = 1 used_letters =[] for char in string1_letters: if char not in used_letters: used_letters.append(char) count = string1.count(char) letter_fact = result_fact(count) anagrams_divisor *= result_fact(string1.count(char)) anagram_dividend = result_fact(len(set(string1_letters))) print('With the expression you\'ve entered you can create', anagram_dividend / anagrams_divisor,'anagrams.') ''' what_to_do = input('What do you want to do? Test the number of possible anagrams to do with 2 expressions or test if 2 expressions are an anagram?') if 'test' in what_to_do.lower(): string1 = input('Enter the first expression:') #string input 1 string2 = input('Enter the second expression:') #string input 2 anagram(string1,string2) else: x = int(input('Enter a positive integer:')) '''
true
e252b4dd9558d7c010daa745f546fb7fefd8f411
endrewu/Coursework
/INF3331/INF3331-Endre/week3/flexcircle.py
1,148
4.15625
4
#!/usr/bin/env python from math import pi, sqrt class FlexCircle(object): def __init__(self, radius): self.radius = radius def set_radius(self, r): if r < 0: print "An error occured, a circle can not have a negative radius" self.radius = 0 return self._radius = r self._area = pi*self.radius*self.radius self._perimeter = 2*pi*self.radius def set_area(self, a): if a < 0: print "An error occured, a circle can not have a negative area" self.radius = 0 return self._area = a self._radius = sqrt(self.area/pi) self._perimeter = 2*pi*self.radius def set_perimeter(self, p): if p < 0: print "An error occured, a circle can not have a negative perimeter" self.radius = 0 return self._perimeter = p self._radius = self.perimeter/(2*pi) self._area = pi*self.radius*self.radius def get_radius(self): return self._radius def get_area(self): return self._area def get_perimeter(self): return self._perimeter radius = property(fget = get_radius, fset = set_radius) area = property(fget = get_area, fset = set_area) perimeter = property(fget = get_perimeter, fset = set_perimeter)
true
c094d81e6696ed07fa7fa205d5ec234341983497
wuxu1019/leetcode_sophia
/medium/math/test_866_Prime_Palindrome.py
973
4.3125
4
""" Find the smallest prime palindrome greater than or equal to N. Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1. For example, 2,3,5,7,11 and 13 are primes. Recall that a number is a palindrome if it reads the same from left to right as it does from right to left. For example, 12321 is a palindrome. Example 1: Input: 6 Output: 7 Example 2: Input: 8 Output: 11 Example 3: Input: 13 Output: 101 Note: 1 <= N <= 10^8 The answer is guaranteed to exist and be less than 2 * 10^8. """ class Solution(object): def primePalindrome(self, N): """ :type N: int :rtype: int """ def isPrime(n): return n > 1 and all(n % i != 0 for i in range(2, int(n ** 0.5) + 1)) if 8 <= N <= 11: return 11 for x in xrange(10 ** (len(str(N)) / 2), 10 ** 5): y = int(str(x) + str(x)[-2::-1]) if y >= N and isPrime(y): return y
true
7dcac48ffa685cf54d1cba6c294fd826b40877fd
wuxu1019/leetcode_sophia
/medium/tree/test_114_Flatten_Binary_Tree_to_Linked_List.py
1,354
4.28125
4
""" Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 click to show hints. Hints: If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. """ class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return self.flatten(root.left) self.flatten(root.right) if root.left: r, l = root.right, root.left while l.right: l = l.right l.right = r root.right = root.left root.left = None prev = None def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return self.prev = root self.flatten(root.left) temp = root.right root.left, root.right = None, root.left self.prev.right = temp self.flatten(temp)
true
0b48aef0261b71afc265826b3678885bc37ac1a3
wuxu1019/leetcode_sophia
/easy/focus/479_Largest_Palindrome_Product.py
887
4.125
4
""" Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example: Input: 2 Output: 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 Note: The range of n is [1,8]. """ ass Solution(object): def largestPalindrome(self, n): if n==1: return 9 upper = 10 ** n-1 lower = upper/10 maxProduct = upper ** 2 firstHalf = maxProduct/(10 ** n) while 1: candi = int(str(firstHalf)[::-1]) + firstHalf * (10 ** n) firstHalf -= 1 if candi > maxProduct: continue for i in xrange(upper, lower, -1): if candi/i > upper: continue if candi % i == 0: return candi% 1337
true
ddd52432f09dc65f5365b40d21ad3792c49db924
wuxu1019/leetcode_sophia
/dailycoding_problem/encode_decode_string.py
1,178
4.28125
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Amazon. Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid. """ import itertools def encode(s): rt = '' for k, v in itertools.groupby(s): rt += str(len(list(v))) rt += k return rt def decode(s): rt = '' times = 0 for c in s: if c.isalpha(): rt += c * times times = 0 else: times = times * 10 + int(c) return rt if __name__ == '__main__': s = 'AAAABBBCCDAAAAAAAAAAAAA' rt = encode(s) if rt == "4A3B2C1D13A": print True else: print False s = "4A3B2C1D13A" rt = decode(s) if rt == 'AAAABBBCCDAAAAAAAAAAAAA': print True else: print False
true
cfd4ee6cfdc320df10f790871394c1e2fc5196d8
wuxu1019/leetcode_sophia
/medium/dp/test_376_Wiggle_Subsequence.py
2,097
4.125
4
""" A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero. Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order. Examples: Input: [1,7,4,9,2,5] Output: 6 The entire sequence is a wiggle sequence. Input: [1,17,5,10,13,15,10,5,16,8] Output: 7 There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. Input: [1,2,3,4,5,6,7,8,9] Output: 2 """ class Solution(object): def wiggleMaxLength_dp(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) <= 1: return len(nums) up, down = 1, 1 for i in range(1, len(nums)): if nums[i] > nums[i-1]: up = down + 1 elif nums[i] < nums[i-1]: down = up + 1 return max(up, down) def wiggleMaxLength_greedy(self, nums): if len(nums) < 2: return len(nums) prediff = nums[1] - nums[0] ct = 1 if prediff == 0 else 2 for i in range(2, len(nums)): diff = nums[i] - nums[i-1] if diff > 0 and prediff <= 0 or diff < 0 and prediff >= 0: ct += 1 return ct if __name__ == '__main__': s = Solution() nums = [4, 4, 6, 6, 1, 1] rt1 = s.wiggleMaxLength_greedy(nums) rt2 = s.wiggleMaxLength_dp(nums) print rt1 print rt2
true
ba514039dc374ed5c25908eeba8070664d912c3f
guyhill/ellipses
/ellipses.py
2,564
4.21875
4
import math import matplotlib.pyplot as plt import sys x=0 y=1 dt = 0.0001 # small time interval # mode selection if len(sys.argv) < 2: mode = "3d" else: mode = sys.argv[1] if mode == "3d": pow = 3 max_orbits = 1 vmin = 5 vmax = 13 elif mode == "2d": pow = 2 max_orbits = 5 vmin = 5 vmax = 5 elif mode == "1d": pow = 1 max_orbits = 5 vmin = 5 vmax = 5 elif mode == "constant": pow = 0 max_orbits = 1 vmin = 5 vmax = 13 else: print("unknown mode {}. Valid modes are '1d', '2d', '3d' and 'constant'".format(mode)) quit(1) # loop over different orbits for vy in range(vmin, vmax + 1): # Note that r, v and a are 2 dimensional. We ignore the z coordinate here because # planetary orbits lie inside a plane r = [1, 0] # initial position of planet v = [0, float(vy) / 10.0] # initial velocity of planet a = [0, 0] # acceleration of planet (placeholder only) result = [r[:]] # resulting list of positions of the planet over time status = 0 # Used to detect when we have calculated the required number of orbits # loop over successive time intervals of length dt while True: # calculate acceleration lenr = math.sqrt(r[x] ** 2 + r[y] ** 2) # Calculate length of vector r using Pythagoras a[x] = -r[x] / lenr ** pow # Acceleration from 2nd law of motion and Newton's law of gravitation a[y] = -r[y] / lenr ** pow # Update position # From the definition of velocity as the rate of change of position r[x] += v[x] * dt r[y] += v[y] * dt # Update velocity # From the definition of acceleration as the rate of change of velocity v[x] += a[x] * dt v[y] += a[y] * dt # Store position for later result.append(r[:]) # increase status whenever the orbit crosses the x axis. Two x axis crossings constitute 1 orbit # Even status means that the planet is above the x axis, odd status means below. if status % 2 == 0 and r[y] < 0: status += 1 elif status % 2 == 1 and r[y] > 0: status += 1 elif status == max_orbits * 2: break plt.plot( [ r[x] for r in result ], [ r[y] for r in result ] ) plt.plot(0, 0, 'ko') # Plot sun in the center axes = plt.gca() axes.set_aspect('equal', 'box') # Make axes square, so that a circle is recognizable as such axes.axhline(y=0, color='k') # Plot the axes themselves axes.axvline(x=0, color='k') plt.show()
true
afbabf9a36378f280dd5e1136227d4e84ba9e62a
Arnaav-Singh/Beginner-code
/Upper case- lower case.py
292
4.4375
4
# To enter any character and print it's upper case and lower case x = input("Enter the symbol to be checked: ") if x >= 'A' and x <= 'Z': print(x ," is an Uppercase character") elif x >= 'a' and x <= 'z': print(x , "is an lower case character") else: ("Invalid Input")
true
a63a965abf66c2845ca93c5cddf2aa9fa927c1ba
Goodmanv4108/cti110
/P4HW2_BasicMath_Goodman.py
1,508
4.25
4
#CTI-110 #P4HW2 - BasicMath #Veronica Goodman #3/12/2020 # ans=True while ans: #Number One Choice Number1 = int(input('Enter your first number: ')) #Number Two Choice Number2 = int(input('Enter your second number: ')) #The sum of the two numbers added, multiplied, and subtration add_sum = Number1 + Number2 multi_sum = Number1 * Number2 sub_sum = Number1 - Number2 #Printing the menu print (""" 1.Add Numbers 2.Multiply Numbers 3.Subtract Numbers 4.Exit/Quit """) #Choosing what to do to the numbers. Add them, Multiply them or subtract them. ans=input("Enter your choice: ") if ans=="1": print("\n The numbers added together equals:" , add_sum) elif ans=="2": print("\n The numbers multiplied equals:" , multi_sum) elif ans=="3": print("\n The numbers subtracted equals:" , sub_sum) elif ans=="4": print("\n Exit") elif ans !="": #Telling the user to choose a proper option ans=input("Enter your choice from the menu(1-4):" ) if ans=="1": print("\n The numbers added together equals:" , add_sum) elif ans=="2": print("\n The numbers multiplied equals:" , multi_sum) elif ans=="3": print("\n The numbers subtracted equals:" , sub_sum) elif ans=="4": print("\n Exit") elif ans !="": #Telling the user to choose a proper option ans=input("Enter your choice from the menu(1-4):" )
true
dcc90fcfe45c01c426371832fdafcf8c83664cdc
igorsorokin66/CareerCup
/FindIslandInMatrix.py
1,532
4.125
4
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Completed in O(n)' ''' Problem: Given a boolean matrix, write a code to find if an island of 0's is completely surrounded by 1's. Source: http://www.careercup.com/question?id=5192952047468544 ''' def search(x, y, data): data[x][y] = "1" found_island = not (x == 0 or x == len(data)-1 or y == 0 or y == len(data[0])-1) if x - 1 >= 0 and data[x - 1][y] == "0": # up found_island &= search(x - 1, y, data) if y + 1 <= len(data[x])-1 and data[x][y + 1] == "0": # right found_island &= search(x, y + 1, data) if x + 1 <= len(data)-1 and data[x + 1][y] == "0": # down found_island &= search(x + 1, y, data) if y - 1 >= 0 and data[x][y - 1] == "0": # left found_island &= search(x, y - 1, data) return found_island def test(data): for d in data: print("".join(d)) for x in range(len(data)): for y in range(len(data[x])): if data[x][y] is "0": if search(x, y, data): return True return False data = [ list("11111"), list("11011"), list("10001"), list("11011") ] print("Result: " + str(test(data))) print("Expect: False\n") data = [ list("11111"), list("10001"), list("10101"), list("10001"), list("11111") ] print("Result: " + str(test(data))) print("Expect: True\n") data = [ list("01"), list("11"), ] print("Result: " + str(test(data))) print("Expect: False\n")
false
11febde5b888da054e2af1788fafe6f301ccc0f1
adwaitmathkari/pythonSampleCodes
/nQueens_lc.py
2,590
4.15625
4
from typing import List class Solution: """ 1) Start in the leftmost column 2) If all queens are placed return true 3) Try all rows in the current column. Do following for every tried row. a) If the queen can be placed safely in this row then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution. b) If placing the queen in [row, column] leads to a solution then return true. c) If placing queen doesn't lead to a solution then unmark this [row, column] (Backtrack) and go to step (a) to try other rows. 3) If all rows have been tried and nothing worked, return false to trigger backtracking. """ def solveNQueens(self, n: int) -> List[List[str]]: # fresh # place in the first row # List[List[str]] result=[] def placeQueen(board, rownum): for i in range(1,n+1): board[rownum]= '.'*(i-1)+'Q'+'.'*(n-i) # print(board) if self.isLegalBoard(board): board1=[row for row in board] if rownum==n-1: result.append(board1) else: placeQueen(board1, rownum+1) board[rownum]='.'*n board=['.'*n for j in range(n)] # print(board) placeQueen(board, 0) return result def isLegalBoard(self, board): n=len(board) rows, cols,d1s, d2s=[],[],[],[] for row in range(n): for col in range(n): if board[row][col]=='Q': # the serial no of the diagonals-- d1, d2 d1 = row + col #0,0 is on diagonal 0, (1,0),(0,1) is on diagonal 1, (2,0),(1,1), (0,2) are on diagonal 2 and so on. d2 = row-col if row in rows or col in cols or d1 in d1s or d2 in d2s: return False else: rows.append(row) cols.append(col) d1s.append(d1) d2s.append(d2) return True # b1=[[0,1,0,0],[0,0,0,1],[1,0,0,0],[0,0,1,0]] # b1=['.Q..','...Q','Q...','Q...'] s=Solution() # print(s.isLegalBoard(b1)) inp=int(input()) results=s.solveNQueens(inp) # for result in results: # for row in result: # print(row) # print("----") print(len(results))
true
0296a00b6c6c326eb7d83b4a3a15034726180c8d
Cvam27/PyLearn_final
/venv/Programs/functin_new.py
362
4.125
4
# function to add two numbers def add_numbers(num1, num2): return num1 + num2 # function to multiply two numbers def multiply_numbers(num1, num2): return num1 * num2 number1 = 5 number2 = 30 sum_result = add_numbers(number1, number2) print("Sum is", sum_result) product_result = multiply_numbers(number1, number2) print("Product is", product_result)
true
4954ee3cdefb1c9ee3e9cde7ce4391b2b7b7ad9a
naghashzade/my-python-journey
/day3-rollercoaster.py
331
4.125
4
print("Wellcome to the Rollercoaster.") if int(input("Height in cm: ")) >= 120: age = int(input("Age: ")) if age >= 18: print("your ticket costs 7$") elif age < 12: print("your ticket costs 3$") else: print("your ticket costs 5$") else: print("you are not allowed to use rollercoaster.")
true
2d0cd4ec7a29b666dd1911a35315b5452caaa7fe
stephsorandom/PythonJourney
/BasicFoundations/Operators/IfElseStatments.py
1,432
4.21875
4
If, Elif, Else Statements ~ Control Flow Syntax in Python use of colons, indentation and whitespace • This is VERY important and sets Python apart from other programming languages. if some_condition : # execute some code else : # do something else elif some_other_condition : #do something different elif ----> for a completely different condition..You can use as many elif statements Ex1: if True: print('ITS TRUE!') if 3 > 2: print('Yes it is true') -----> 'Yes it is true' hungry = True ===> declaring variable if hungry: ====> arguement print('Feed me') ====> what it prints if True else: print('Im not hungry') Ex2: loc = 'Bank' if loc == 'Auto Shop' : print('Cars are cool!') else: print('I don not know much.') Ex using elif: loc = 'Store' if loc == 'Auto Shop' : print('Cars are cool!') elif loc == 'Bank' : print('Money is cool!') elif loc == "Store" : print('Publix is cool!') else: print('Where am I?') ===> 'Publix is cool!' ##because we declared loc = 'Store' Ex: name = 'Steph' if name == 'Nat': print('Hey Nat!') elif name == 'Steph': print('Whats up Steph!') else : print('What is your name?') ====> "Whats up Steph!"
true
4ab5c52abe748650d998199c83a049176ed51472
saregos/ssw567homework2
/TestTriangle.py
2,426
4.1875
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestTriangles(unittest.TestCase): # define multiple sets of tests as functions with names that begin def testInvalidInputA(self): self.assertEqual(classifyTriangle('a',1,1),'InvalidInput','\'a\',1,1 should be invalid') def testInvalidInputB(self): self.assertEqual(classifyTriangle(1,-1,1),'InvalidInput','1,-1,1 should be invalid') def testInvalidInputC(self): self.assertEqual(classifyTriangle(1,1,'a'),'InvalidInput','1,1,\'a\' should be invalid') def testRightTriangleA(self): self.assertEqual(classifyTriangle(3,4,5),'Right','3,4,5 is a Right triangle') def testRightTriangleB(self): self.assertEqual(classifyTriangle(5,3,4),'Right','5,3,4 is a Right triangle') def testRightTriangleC(self): self.assertEqual(classifyTriangle(4,5,3),'Right','4,5,3 is a Right triangle') def testNotTriangleA(self): self.assertEqual(classifyTriangle(1,1,2),'NotATriangle','1,1,2 should be Not a Triangle') def testNotTriangleB(self): self.assertEqual(classifyTriangle(1,2,1),'NotATriangle','1,2,1 should be Not a Triangle') def testNotTriangleC(self): self.assertEqual(classifyTriangle(2,1,1),'NotATriangle','2,1,1 should be Not a Triangle') def testScaleneTriangle(self): self.assertEqual(classifyTriangle(2,3,4),'Scalene','2,3,4 should be Scalene') def testIsocelesTriangleA(self): self.assertEqual(classifyTriangle(2,2,3),'Isoceles','2,2,3 should be Isoceles') def testIsocelesTriangleB(self): self.assertEqual(classifyTriangle(2,3,2),'Isoceles','2,3,2 should be Isoceles') def testIsocelesTriangleC(self): self.assertEqual(classifyTriangle(3,2,2),'Isoceles','3,2,2 should be Isoceles') def testEquilateralTriangles(self): self.assertEqual(classifyTriangle(1,1,1),'Equilateral','1,1,1 should be equilateral') if __name__ == '__main__': print('Running unit tests') unittest.main()
true
cbed95572fe0f679c0639b10720e1f0726837e43
suboice114/FirstPythonDemo
/AlgorithmsAndDataStructures/MergeSort.py
1,510
4.1875
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- # @Time : 2019/9/2 11:09 # @Author : su # @File : MergeSort.py """归并排序""" class Person(object): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'{self.name}: {self.age}' def __repr__(self): return self.__str__() def merge_sort(items, comp=lambda x, y: x <= y): if len(items) < 2: return items[:] mid = len(items) // 2 left = merge_sort(items[:mid], comp) right = merge_sort(items[mid:], comp) return merge(left, right, comp) def merge(items1, items2, comp=lambda x, y: x <= y): """合并(将两个有序列表合并成一个新的有序列表)""" items = [] index1, index2 = 0, 0 while index1 < len(items1) and index2 < len(items2): if comp(items1[index1], items2[index2]): items.append(items1[index1]) index1 += 1 else: items.append(items2[index2]) index2 += 1 items += items1[index1:] items += items2[index2:] return items def main(): items = [35, 97, 12, 68, 55, 73, 81, 40] print(merge_sort(items)) items2 = [ Person('Wang', 25), Person('Luo', 39), Person('Zhang', 50), Person('He', 20) ] print(merge_sort(items2, comp=lambda p1, p2: p1.age <= p2.age)) items3 = ['apple', 'orange', 'watermelon', 'durian', 'pear'] print(merge_sort(items3)) if __name__ == '__main__': main()
false
3bcbe55a3a14754f0622f23f29d6fa2d4233a049
suboice114/FirstPythonDemo
/AdvancedTutorial/advancedExample1.py
932
4.34375
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- # python 面向对象1:类的创建 与 对象 class Employee: """所有员工的基类""" empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def display_employee(self): print('Name:', self.name, ", Salary:", self.salary) # 创建 Employee 类的第1 个对象 emp1 = Employee('Zara', 2000) # 创建 Employee 类的第2 个对象 emp2 = Employee('Tom', 5000) # 访问属性 emp1.display_employee() emp2.display_employee() print("Total Employee %d" % Employee.empCount) # Python 内置类属性 print('Employee.__doc__:', Employee.__doc__) print('Employee.__name__:', Employee.__name__) print('Employee.__module__:', Employee.__module__) # module__: 类定义所在的模块 print('Employee.__bases__:', Employee.__bases__) print('Employee.__dict__:', Employee.__dict__)
false
aeda4fb358498be512c17e84198fd9f28ec15155
philipteu/Philpython
/The guessing game.py
978
4.375
4
#The Guessing Game #Step-by-step to develop a program. #The guessing game program will do the following: #• The player only gets five turns. #• The program tells the player after each guess if the number is higher or lower. #• The program prints appropriate messages for when the player wins and loses. import random def guessgame(): n = random.randint(1,100) for i in reversed (range(5)): N = int(input('Enter your guess(1-100):')) if N < n: print('HIGHER.', i,'gueses left.') elif N > n: print('LOWER.',i,'guesses left.') else: print('Yes. The correct number is', n) break if i == 0: print('You lose. The correct number is', n) break R = str(input('Do you want to restart the game?(y/n):')) if R == 'y': guessgame() elif R == 'n': print('Goodbye!') guessgame()
true
a9b0e555dc61e276f652b8884fc36fd504b2cc5b
BhagyashreeKarale/list
/palindrome.py
1,283
4.21875
4
# Code likho jo check kare ki kya list palindrome hai ya nahi. # Aur print karo “Haan! palindrome hai” agar hai. Aur “nahi! Palindrome nahi hai” agar nahi hai. #Abhi ke liye iss list ko use kar ke code likh sakte ho: # name=[ 'n', 'i', 't', 'i', 'n' ] # rev=name[::-1] # if rev==name: # print("It's a palidrome") # else: # print("It isn't a palidrome ") # Apni list ko change kar ke alag alag values ke saath test out karo aur fir finally theek code ko upload karo. # Inn values ke liye aap test kar sakte hai # nayan => true naina => false anamana => true ainaania => true ainabnia => false #using slicing #with user input: name=list(input("Enter a word\n")) rev=name[::-1] if rev==name: print("It's a palidrome") else: print("It isn't a palidrome") #without using slicing original=list(input("Enter a word:\n")) reverse=[] index=len(original)-1 while index >= 0 : reverse.append((original[index])) index=index-1 if original == reverse : print("It is a palidrome") else: print("It isn't a palidrome") string=list(input("Enter a word:\n")) for i in range (len(string)): for k in range(i+1): if k == 0 : print((string[i]).upper(),end="") else: print(string[i],end="") print("_",end="")
false
35bdab241a0abbf63592bb2047d3a081cdd8dd2f
Penzragon/CipherFile
/file.py
2,403
4.21875
4
alphabet = "abcdefghijklmnopqrstuvwxyz" symbol = "~`!@#$%^&*()_-+=;:'\",.? " def vigenere(message, keyword): """This is a function for decrypting a message Args: message (string): message that going to be decrypted keyword (string): a keyword for decrypting the message Returns: string: decrypted message """ pointer = 0 keyworded = "" decoded = "" for i in range(len(message)): if not message[i] in symbol: keyworded += keyword[pointer] pointer = (pointer + 1) % len(keyword) else: keyworded += message[i] for i in range(len(message)): if not message[i] in symbol: lenght = alphabet.find(message[i]) - alphabet.find(keyworded[i]) decoded += alphabet[lenght % 26] else: decoded += message[i] return decoded def vigenere_coder(message, keyword): """This is a function for encrypting a message Args: message (string): message that going to be encrypted keyword (string): a keyword for encrypting the message Returns: string: encrypted message """ pointer = 0 keyworded = "" coded = "" for i in range(len(message)): if not message[i] in symbol: keyworded += keyword[pointer] pointer = (pointer + 1) % len(keyword) else: keyworded += message[i] for i in range(len(message)): if not message[i] in symbol: length = alphabet.find(message[i]) + alphabet.find(keyworded[i]) coded += alphabet[length % 26] else: coded += message[i] return coded def text_cleaner(list): clean_list = [] for line in list: clean_list.append(line.strip("\n")) return clean_list with open('text.txt') as text: list_text = text.readlines() enc = text_cleaner(list_text) with open('encrypted.txt', "w") as encrypted: for line in enc: encrypted.write(vigenere(line, "penzragon")) encrypted.write("\n") with open("encrypted.txt") as text: enc_list = text.readlines() dec = text_cleaner(enc_list) with open("decrypted.txt", "w") as decrypted: for line in dec: decrypted.write(vigenere_coder(line, "penzragon")) decrypted.write("\n")
true
7ae2df6791de10590a2bffb773fae99fd9ad2824
caroling2015/excise_2018
/test/learn/charpter 1/charpter 1.py
551
4.1875
4
# -*- encoding: utf-8 -*- # 正则表达式 regular expression import re # Match literal string value literal n = re.match('foo','foo') if n is not None: print n.group() # Match regular expressions re1 or re2 bt = 'bat|bet|bit' m = re.match(bt,'bat') if m is not None: print m.group() l = re.match(bt,'he bit me') if l is not None: print l.group() print '====' # search() looks for the first occurrence of the pattern within the string, it evaluates a string strictly from left to right z = re.search(bt,'he bit me') print z.group()
true
1a21c454f2956a9ca01a8e9df52ec6eb058543da
lcodesignx/pythontools
/lists/names.py
208
4.4375
4
#!/usr/local/bin/python3 # Store a few names in a list then print each name # by accessing each element in the list, one at a time names = ['python', 'c++', 'c', 'java'] for name in names: print(name)
true
1c382bc5797fd633b81fe46c8dee98141b4b631d
Yoann-CH/git-tutorial
/guessing.game.py
1,096
4.375
4
#! /usr/bin/python3 # The random package is needed to choose a random number import random #Define the game in a function def guess_loop(): #This is the number the user will have to guess, chosen randomly in betw een 1 and 100 number_to_guess = random.randint (1, 100) print("I have in mind a number in between 1 and 100, can you find it?") print("Choose an username") name = input() print("Now, choose a number") #Replay the question until the user finds the correct number while True: try: #Read the number the user inputs guess = int(input()) # Compare it to the number to guess if guess > number_to_guess: print("The number to guess is lower") elif guess < number_to_guess: print("The number to guess is higher") else: #The user found the number to guess, let's exit print( "Good job",name,",it is the good number" ) return #A ValueError is raised by the int() function if the user inputs something else than a number except ValueError as err: print("Invalid input, pleases enter an integrer") # Launch the game guess_loop()
true
1101b5d2be334ff37d8d893697d62a3dec048b8b
DaveTanton/PythonHomework
/RPS.py
1,340
4.125
4
mport random as r print ("Rock, paper, scissor game") result = "" choices = ("rock","paper","scissors","SHOTGUN") while True: #whats this "error" computer = choices[r.randint (0,3)] user=input("\nRock, Paper or Scissors? make your choice :").lower() if user == "shotgun": result="STOP CHEATING! TRY AGAIN!!" elif user == computer: result = "IT'S A DRAW" elif user == "rock": if computer == "scissors": result = "YOU WIN" if computer == "paper": result = "YOU LOSE" if computer == "SHOTGUN": result ="SHOTGUN!! I WIN! YOU LOSE. HA HA!" elif user == "paper": if computer == "rock": result = "YOU WIN" if computer == "scissors": result = "YOU LOSE" if computer == "SHOTGUN": result ="SHOTGUN!! I WIN! YOU LOSE. HA HA!" elif user == "scissor": if computer == "paper": result = "YOU WIN" if computer == "rock": result = "YOU LOSE" if computer == "SHOTGUN": result ="SHOTGUN!! I WIN! YOU LOSE. HA HA!" else: print("That's not a valid play. Check your spelling!") continue print("you chose: ",user) print("the computer chose: ",computer) print(result) retry=input("\nHave another go Y/N: ") retry=retry.lower() if retry == "y": continue else: break print("\nAll done\nThank you for playing")
false
b61f2572a06fc16a9636e4f7318da88e8781f5b5
MohammedSabith/PythonProgramming
/filescore.py
582
4.21875
4
'''Suppose that a text file contains an unspecified number of scores. Write a program that reads the scores from the file and displays their total and average. Scores are separated by blanks. Your program should prompt the user to enter a filename.''' fname = input("Enter the filename : ") try: fp = open(fname,"r+") l = fp.readlines() fp.close() count = 0 val = 0 for i in l: d = list(map(int,i.split(" "))) count += len(d) val += sum(d) print("Sum = ",val,"\nAvg = ",(val/count)) except FileNotFoundError: print("File not found")
true
7298ebdc56b9306a91f8051def636c9aeb5dc898
dpappo/python-tutorial
/six.py
1,166
4.28125
4
"This is a docstring" # how do objects, classes, and inheritance work in Python? # here's a list of functions that are part of every number object # print(dir(5)) # looking at one of the magic methods aka dunder aka double underscore print(bool(0)) # classes are the blueprints for objects in python print(type('a')) print(type(1)) print(type(True)) # classes are built in and can also be defined, like this: class Car: speed = 0 started = False def start(self): self.started = True print("Car started, let's ride!") def increase_speed(self, delta): if self.started: self.speed = self.speed + delta print("Vroooooom!") else: print("You need to start the car first") def stop(self): self.speed = 0 print("Halting") # now let's create an instance of this class car = Car() car.increase_speed(10) car.start() car.increase_speed(40) # car.stop() # objects have built in id methods print(id(car)) # if we make a new object/instance, it will have a different ID car2 = Car() print(id(car2)) # it has unique properties print(car.speed) print(car2.speed)
true
c512b2098643ec204c7a5114bf79d8fd023b5f68
Psp29onetwo/python
/ch3/greetings.py
702
4.34375
4
names_of_my_friends = ['Hiren','Naman','Saumya','Kundan','Srinath'] message = "How are you?" print(names_of_my_friends[0] +", " + message)#accessing the first element and conctinating the message string variable print(names_of_my_friends[1] +", " + message)#accessing the second element and conctinating the message string variable print(names_of_my_friends[2] +", " + message)#accessing the third elementand conctinating the message string variable print(names_of_my_friends[-2] +", " + message)#accessing the second last element and conctinating the message string variable print(names_of_my_friends[-1] +", " + message)#accessing the last element and conctinating the message string variable
false
7d5b8ea1838103b8bf4c240badad88de7403bed0
Psp29onetwo/python
/multipleof10.py
240
4.34375
4
multiple_of_ten = int(input("Enter the number and i will tell you that entered number is multiple of ten or not: ")) if (multiple_of_ten % 10) == 0: print("Number is multiple of ten") else: print("Number is not multiple of ten")
true
39e4603f2c6224a0c12838bd2809545b8825c43e
Psp29onetwo/python
/ch3/list.py
413
4.46875
4
bicycle = ['trek', 'cannondale', 'redline', 'specialized'] #List declartaion and initialization print(bicycle) #Printing list print(bicycle[0])#Pulling out the first element of list print(bicycle[0].title())#printing very first element in list in form of title '''Indexing the list''' print(bicycle[-1])#returning the last element of list print(bicycle[-2])#returning the second last element of the list
true
55d45ee0242d43654400cc5a3288cfed2c07d11d
bicongwang/lintcode-python3
/40. Implement Queue by Two Stacks.py
992
4.125
4
# Solution 1: # # Comment: push(): push element to self._stack1 # pop(): pop element from self._stack2 # it will adjust stack when we invoke pop() class MyQueue: def __init__(self): # do intialization if necessary self._stack1 = [] self._stack2 = [] """ @param: element: An integer @return: nothing """ def push(self, element): # write your code here self._stack1.append(element) """ @return: An integer """ def pop(self): # write your code here if self._adjust_stack(): return self._stack2.pop() """ @return: An integer """ def top(self): # write your code here if self._adjust_stack(): return self._stack2[-1] def _adjust_stack(self): if not self._stack2: while self._stack1: self._stack2.append(self._stack1.pop(-1)) return bool(self._stack2)
false
15f44b114a85890be057b7b467a3590cc18ef28f
BraysonWheeler/Python-Basics
/Functions.py
821
4.15625
4
#def declares function dont need to declare anynumber def activity(anynumber): if (anynumber == 0): print ("given number is 0") elif (anynumber > 0): print ("given number is pos") else: print("given numbe is negative") number = int(input("Enter any number")) activity(number) activity(number*-2) #nano python5.py ##!usr/bin/python string = str(input("Type any string you want")) def reverse_string(anystring): print(anystring[::-1]) #[::-1] will reverse the order of whats inputed reverse_string(string) number_list =[1,2,3,4,5] def function(anylist): even_list = [] odd_list = [] for i in range(len(anylist)): if (number_list[i]% 2 == 0): even_list.append(anylist[i]) else: odd_list.append(anylist[i]) print (even_list) print (odd_list) function(number_list)
true
623be520ee39be247a5c1327fb1c0a74942d5c96
shivang17/learnPythonTheHardWay
/ex18.py
511
4.15625
4
# this one is like the scripts with argv def print_two(*args): arg1,arg2 = args print(f"arg1 : {arg1}, arg2: {arg2}") # *args is not recommended, instead we can use the following method. def print_two_again(arg1,arg2): print(f"arg1: {arg1}, arg2: {arg2}") # One argument function def print_one(arg1): print(f"arg1: {arg1}") # This one takes no arguments def print_none(): print("I got nothing") print_two("Zed","Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none()
true
d74ad8e8b8c7e04b649401adbb4b2811d9596333
RithvikKasarla/Udacity-Data-Structures-Algorithms-Nanodegree-Program
/Unscramble Computer Science Problems/Task4.py
1,345
4.21875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) if __name__ == '__main__': incomingtext = [] outgoingtext = [] incomingcall = [] outgoingcall = [] telemarketers = set([]) for text in texts: #O(n) outgoingtext.append(text[0]) incomingtext.append(text[1]) for call in calls: #O(n) outgoingcall.append(call[0]) incomingcall.append(call[1]) for x in outgoingcall: #O(n) if(not (x in outgoingtext or x in incomingtext or x in incomingcall)):#O(n) telemarketers.add(x) #O(1) print("These numbers could be telemarketers: ") for y in sorted(telemarketers): #O(n) + O(nlogn) print(y) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """
true
8bae74c76c436768df150474c61e3ce54ec1792e
danrneal/restaurant-menu-app
/models.py
2,357
4.34375
4
"""Model objects used to model data for the db. Attributes: engine: A sqlalchemy Engine object with a connection to the sqlite db Classes: Base() Restaurant() MenuItem() """ from sqlalchemy import Column, ForeignKey, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class Restaurant(Base): """A model representing a restaurant. Attributes: id: An int that serves as the unique identifier for the restaurant name: A str representing the name of the restaurant """ __tablename__ = "restaurants" id = Column(Integer, primary_key=True) name = Column(String(80), nullable=False) @property def serialize(self): """Serializes the restaurant object as a dict. Returns: restaurant: A dict representing the restaurant object """ restaurant = {"id": self.id, "name": self.name} return restaurant class MenuItem(Base): """A model representing a menu item. Attributes: id: An int that serves as the unique identifier for the menu item name: A str representing the name of the menu item course: A str representing the course the menu item belongs to description: A str respresenting a description of the menu item price: A str representing the price of the menu item restaurant_id: The id of the restaurant the menu item belongs to """ __tablename__ = "menu_items" id = Column(Integer, primary_key=True) name = Column(String(80), nullable=False) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey("restaurants.id")) restaurant = relationship(Restaurant) @property def serialize(self): """Serializes the menu item object as a dict. Returns: restaurant: A dict representing the menu item object """ menu_item = { "id": self.id, "name": self.name, "course": self.course, "description": self.description, "price": self.price, } return menu_item engine = create_engine("sqlite:///restaurant_menu.db") Base.metadata.create_all(engine)
true
bebdcd816eb674b3aed82fc98a145ea9858ded06
namhla1986/pythonpractice
/translator_practice.py
714
4.1875
4
def translate(phrase): translation = "" for letter in phrase: if letter.lower() in "aeiou": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" else: translation = translation + letter return translation print(translate(input("Enter your word: "))) # Remember that indentation REALLY matters! This was just a translator to test whether any vowels could be # found in the strings that were inputted by the user. The vowels would be replaced with the letter g.I had # to create a function called translate and use both the for loop and if statement to test the theory
true