blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
01193520f4ca41afc35c5bd4e34b2f1ccaf42527
VireshDoshi/pd_test
/PerspectumDiagnostics.py
2,721
4.5
4
#!/usr/bin/env python import itertools def strings_appear_in_multiple_lists(list_in): """ This method will print out the list of Strings appearing in multiple Lists. Input: List of Lists ( 1..n) Output: String """ # establish the size of the list list_in_len = len(list_in) # set the display_string display_string = '' final_list = [] for b in range(0,list_in_len -1): for a in range(b,list_in_len-1): new_list = [ x for x in list_in[b] if x in list_in[a + 1] ] final_list.append(new_list) # remove unwated empty lists filtered_final_list = [ x for x in final_list if x] for list in filtered_final_list: # display_string = "'".join(map(str,list))[1:-1] display_string = display_string + str(list)[1:-1] + ',' # strip out the last comma display_string = display_string.rstrip(',') # print "Strings appearing in multiple lists: {0}".format(display_string) return display_string def number_of_unique_strings(list_in): """ This method will return the number of unique strings in the list given :param list_in: :return: integer of unique strings """ # lets concatenate all the values into one large list for processing merged_list = list(itertools.chain(*list_in)) # establish the length of items in the set merged_set_len = len(set(merged_list)) # print "number of unique strings: {0}".format(merged_set_len) return merged_set_len def total_number_of_strings_processed(list_in): """ This method will return the number of strings processed :param list_in: :return: integer of strings processed """ # lets concatenate all the values into one large list for processing merged_list = list(itertools.chain(*list_in)) merged_len = len(merged_list) # print "Total number of strings processed {0}".format(merged_len) return merged_len def perspectum_diagnostics_test(list_in): """ This method displays the output to the screen based on the list :param list_in: :return: print output to the screen """ print "Strings appearing in multiple lists: {0}".format(strings_appear_in_multiple_lists(list_in)) print "number of unique strings: {0}".format(number_of_unique_strings(list_in)) print "Total number of strings processed {0}".format(total_number_of_strings_processed(list_in)) if __name__ == '__main__': test_list_1 = [['a','b','c','dh'],['a','d','ha','e'],['f','g','h'],['c'],['dh'],['h','ha'],['e'],['d']] test_list_2 = [['g', 'gh', 'ghj', 'g'], ['j', 'ju', 'gh', 'gk', 'gn']] test_list_3 = [['a'],['f'],['f']] perspectum_diagnostics_test(test_list_3)
true
9f1d61ffab774846d0c465ebe959ba3fe0e93275
RiyazShaikAuxo/datascience_store
/PyhonProgramming/leapYear.py
380
4.1875
4
#If the year divisible by 4, 100 and 400 is a leap year elase not a leap year year=int(input("Enter the year: ")) if (year%4)==0: if(year%100)==0: if(year%400)==0: print(year, "is a leap year") else: print(year, "is not a leap year") else: print(year, "is not a leap year") else: print(year, "is not a leap year")
false
9402dc7956bd81a9f115c27f35dc1bb17e3d8363
RiyazShaikAuxo/datascience_store
/1.python/Datastrutures_in_Python/tupple.py
508
4.28125
4
# tupples once craeted can not be modified at all #Similar to lists tuple=(30,'Riyaz',5.8) print(tuple[0]) tuple1=("Banglore",29.3343,34) print(tuple1) #assigning new variable tuple2=tuple1 print(tuple2) #tupple not allow item assignment will throw error #tuple2(1)="Riyaz" retrieve1=tuple2[:-1] print(retrieve1) #Another way to create a tupple new_tupple=1,2,3 print(new_tupple) #Concatinate tupples cocatinate_tupple=new_tupple,(1,2,3,4,5) print(cocatinate_tupple) print(cocatinate_tupple[0])
true
fd73446ae26bc74f87d35ce6c29b156da1130201
mskyberg/Module7
/fun_with_collections/sort_and_search_array.py
2,712
4.59375
5
""" Program: sort_and_search_array.py Author: Michael Skyberg, mskyberg@dmacc.edu Last date modified: June 2020 Purpose: Demonstrates the use of a basic array sorting and searching """ import array as arr LIST_MAX = 3 def get_input(): """ Description: Gets user input :returns: returns a string of user input :raises keyError: raises an exception """ # prompt user for input return input('Enter an integer value: ') def make_array(sort=False, reverse=False): """ Description: gets 3 user inputs and combines them into a list :param sort: optional bool whether or not to sort the list :param reverse: optional bool sort in reverse order or not :returns: returns an array of 3 values :raises ValueError: raises an exception if input is not numeric """ new_list = [] # asks for 3 user input in a loop by for index in range(LIST_MAX): user_input = get_input() try: # attempt to cast string to an integer user_input = int(user_input) if not 1 <= user_input <= 50: raise ValueError(f'Input is out of range! {user_input}') except ValueError: raise else: # if successful, insert into list new_list.insert(index, user_input) new_array = arr.array('i', new_list) if sort: return sort_array(new_array, reverse) else: return new_array def sort_array(a_arr, rev=False): """ Description: Sort a list in order with optional reverse :param a_arr: an array to sort :param rev: sort order, true if reverse sort :returns: a sorted array """ # convert the array to a list since it is for sure same type arr_as_list = a_arr.tolist() # sort the list accordingly arr_as_list.sort(reverse=rev) # create new array with the integer list sorted # I am creating a new array so going to return the new array return arr.array('i', arr_as_list) def search_array(a_arr, element): """ Description: Search for an element at provided index :param a_arr: array to search :param element: element to find :returns: index of element :raises ValueError: raises an exception if element does not exist """ try: index = a_arr.index(element) except ValueError: return -1 else: return index if __name__ == '__main__': try: test_array = make_array(sort=False, reverse=False) print(test_array) element_index = int(input('Enter element to search:')) print(f'Index: {search_array(test_array, element_index)}') except ValueError as main_error: print(f'failure in main: {main_error}')
true
95a6bdf3d1dfe5cdb2f78a857e494743df0aa0d3
carepack/PycharmProjects
/exercise04.py
566
4.28125
4
# 13.11.2019 # identify divisors of number. ouput as list in_num = int(input("Please enter number: ")) x_ra = range(2, in_num+1) for element in x_ra: res = in_num % element if res == 0: out_num = str(in_num) out_element = str(element) out_divisor = str(in_num / element) print("Your number " + out_num + " is dividable by " + out_element + " result = " + out_divisor) # output as list num_div = [] for element in x_ra: if in_num % element == 0: num_div.append(element) print("Divisors as list: " + str(num_div))
false
8421badfb54ed5238572c619a67f828dff41de39
henry199101/6.00.1x_Files
/Midterm_Exam/Quiz/Problem_5/laceStringsFinished.py
823
4.25
4
def laceStrings(s1, s2): """ s1 and s2 are strings. Returns a new str with elements of s1 and s2 interlaced, beginning with s1. If strings are not of same length, then the extra elements should appear at the end. """ # Your Code Here if len(s1) > len(s2): (s1, remainder) = (s1[0:len(s2)], s1[len(s2):]) elif len(s1) < len(s2): (s2, remainder) = (s2[0:len(s1)], s2[len(s1):]) else: remainder = "" # s1 and s2 now start out as two equal length strings chars = [] for i in range(len(s1)): chars.append(s1[i]) chars.append(s2[i]) result = "".join(chars) + remainder return result # For example, if we lace 'abcd' and 'efghi', we would get the new string: 'aebfcgdhi'. s1 = 'abcd' s2 = 'efghi' print laceStrings(s1, s2)
true
9bcdd2c0696cb4ed65f741fc02cf14f2472468d6
Hari-97/task_py
/num square pattern.py
245
4.1875
4
row=3 for i in range(1,2*row): for j in range(1,2*row): if (i==1) or (i==2*row-1) or ((j==1 or j==2*row-1) and (i>1 and i<2*row-1)): print(row,end=" ") elif(i==3 and j==3): print(1,end=" ") else: print(row-1,end=" ") print()
false
229463b206f7594e56f94825645a236bcb48160b
PrabuddhaBanerjee/Python
/Chapter3/Ch3P9.py
269
4.15625
4
import math def main(): print("This program calculates area of a triangle") a, b, c = eval(input("Please enter 3 sides of triangle a, b, c:")) s = (a + b + c)/2 area = math.sqrt(s * (s - a) * (s - b) * (s - c)) print("Area of the triangle is ", area) main()
true
dca253cfa9ab3a66679770ec8879ca841c8cc616
PrabuddhaBanerjee/Python
/Chapter3/Ch3P6.py
289
4.125
4
def main(): print("This program calculates slope between two points") x1, y1 = eval(input("Please enter x, y coordinates for point 1:")) x2, y2 = eval(input("Please enter x, y coordinates for point 2:")) slope = (y2 - y1)/ (x2 - x1) print("Slope of the line is ", slope) main()
true
ef61b8338e2e3f0678e0b3174068bbeef8301723
PrabuddhaBanerjee/Python
/Chapter3/Ch3P1.py
320
4.28125
4
import math def main(): print("This program is to calculate the volume and surface area of a sphere") radius = int(input("Please enter the radius for sphere:")) vol = (4 / 3)* math.pi * (radius ** 3) area = 4 * math.pi * (radius ** 2) print("The area of the sphere is",area," and the volume is ",vol) main()
true
3c0ca0d28398b31334d052ee7363271aef4efbf3
devsave/docs
/Python实验室/list添加元素/list_append.py
867
4.1875
4
# a = [1, 2] # b = [1, 2] # print('The id of a: %d' % id(a) ) # a += [3] # print('The id of a: %d' % id(a) ) # print('a = %s' % str(a)) # print('The id of b: %d' % id(b) ) # b = b + [3] # print('The id of b: %d' % id(b) ) # print('b = %s' % str(b)) # b = (1, 2) # c = b # print('Before calculation') # print('The id of b: %d' % id(b)) # print('The id of c: %d' % id(c)) # b += (3, ) # print('After calculation') # print('The id of b: %d' % id(b) ) # print('The id of c: %d' % id(c)) # print('b = %s' % str(b)) # print('c = %s' % str(c)) b = (1, 2) c = b print('Before calculation') print('The id of b: %d' % id(b)) print('The id of c: %d' % id(c)) print('b = %s' % str(b)) print('c = %s' % str(c)) b += (3, ) print() print('After calculation') print('The id of b: %d' % id(b) ) print('The id of c: %d' % id(c)) print('b = %s' % str(b)) print('c = %s' % str(c))
false
3d2bcf58c87f8995ddc8974f753a9d6ebc8c79ff
teago83/ExerciciosPython
/Calculadora.py
1,175
4.125
4
class calculadora(): def soma(self, x, y): return x + y def subtracao(self, x, y): return x - y def multiplicacao(self, x, y): return x * y def divisao(self, x, y): return x / y calc = calculadora() def menu(): while True: try: op = int(input("1) Soma" "\n2) Subtração" "\n3) Multiplicação" "\n4) Divisão" "\n5) Vazar" "\nDigite a operação desejada.")) except ValueError: print("Valor inválido.") break xis = int(input("Digite o valor número 1:")) ispu = int(input("Digite o valor número 2:")) if op == 1: print("Resultado da soma: %d" %(calc.soma(xis, ispu))) elif op == 2: print("Resultado da subtração: %d" % (calc.subtracao(xis, ispu))) elif op == 3: print("Resultado da multiplicação: %d" % (calc.multiplicacao(xis, ispu))) elif op == 4: print("Resultado da divisão: %d" % (calc.divisao(xis, ispu))) elif op == 5: exit() while True: menu()
false
fbdc4501fd424d15c0d478286655ce417924b01f
FaatimahM/Analyse-predict
/analysepredict/word_split.py
505
4.28125
4
def word_splitter(df): """ Splits the sentences in a dataframe's column into a list of the separate words. The created lists should be placed in a column named 'Split Tweets' in the original dataframe. parameters ---------- df: Dataframe It should take a pandas dataframe as an input. Returns ------- df: DataFrame The function should return the modified dataframe. """ df['Split Tweets'] = df['Tweets'].str.lower().str.split() return df
true
48f9a0e5b3af6cc743bb3541af4ac6d67bf5fc47
venkatreddymallidi/python
/leapyear.py
350
4.125
4
#program to find leap year or not year=int(input("enter a year")) if year%400==0 or (year%4==0 and year%100!=0):#1996 and 2004 is divisible by 4 and divisible by 100 so leap years 2100 not a leap year but divisible by 4 divisible by 100 so leap year divisible by 4 not divisible by 100 print("leap year") else: print("non leap year ")
false
0fefbee1a8189445eb6acd86da4b4bbdec8f612d
gapigo/CEV_Aulas_Python
/Aulas/Aula 17/Aula 17a.py
279
4.1875
4
num = [2, 5, 9, 1] print(num) num[2] = 3 print(num) num.append(7) print(num) num.sort() print(num) num.sort(reverse=True) num.insert(2, 0) print(num) num.pop(2) print(num) print(f'Essa lista tem {len(num)} elementos.') num.insert(2, 2) print(num) num.remove(2) print(num)
false
47e6d9d3a584db96db9eec5e8541b6d4043a56a5
atena-data/Python-Bootcamp-Codes
/Day 4 - Rock, Paper, Scissors Game/main.py
1,308
4.21875
4
#import random module import random #ASCII arts for game choices rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' print ("Welcome to Rock, Paper, Scissors!\nLets Play!\n") #Ask user for their choice user_choice = int (input ("What do you choose? Type 0 for Rock, 1 for Paper and 2 for Scissors.\n")) #Generate random value as computer's choice computer_choice = random.randint(0,2) #List all possible choices choices = [rock, paper, scissors] #Check user and computer choices against each other if user_choice >= 3 or user_choice < 0: print ("You typed an invalid number. Please try again!") else: print(f"You chose:\n{choices[user_choice]}") print(f"Computer chose:\n{choices[computer_choice]}") if user_choice == 0 and computer_choice == 2: print ("CONGRATULATIONS!\nYou won!") elif user_choice > computer_choice: print ("CONGRATULATIONS!\nYou won!") elif computer_choice > user_choice: print ("SORRY!\nYou lost!\nPlease try again.") elif computer_choice == user_choice: print ("It's a draw!")
false
89a0dad041bb636a7119e958f881d7c95d017346
atena-data/Python-Bootcamp-Codes
/Day 1 - Band Name Generator/main.py
435
4.375
4
#1. Create a greeting for the program. print("Hello there! Welcome to the band name generator :) \n") #2. Ask the user for their favorite color and pet name. favorite_color = input("What is your favorite color?\n") pet_name = input("What is the name of your pet?\n") #4. Combine the names to suggest a band name. print("\nYour suggested band name is " + favorite_color + " " + pet_name + "!") print("\nThanks for using this program!")
true
28085fc4229c92fcaf5f8ba852a8db66389ca5f5
atena-data/Python-Bootcamp-Codes
/Day 12 - Guess a Number Game/main.py
1,131
4.15625
4
from art import logo import random #Function to compare user's guess to the number def compare(user_guess, number): """Compares user's guess to the number and will return result""" if user_guess > number: global attempts attempts -= 1 return "Too high." elif user_guess < number: attempts -= 1 return "Too low." else: return f"Congratulations! The answer was {number}." print(logo) print("Welcome to the number guessing game!") print("I'm thinking of a number between 1 and 100") #Generate a random number between 1 and 100 number = random.randrange(1, 101) #Ask user for their desired difficulty level level = input("Choose a dificulty level. Type 'easy' or 'hard': ") if level == "easy": attempts = 10 else: attempts = 5 #Run the game print(f"You have {attempts} attempts to guess the number") while attempts !=0: for attempt in range(attempts): user_guess = int(input("Make a guess: ")) print(compare(user_guess, number)) if user_guess == number: break if attempts == 0 and user_guess != number: print (f"Sorry! The answer was {number}. You lose.") break
true
1c4a20def81fddff2c3df963a8cf84cc2487a615
kwhit2/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
740
4.53125
5
#!/usr/bin/python3 """ This module contains a function that prints a square with #s """ def print_square(size): """ print_square method Args: size - int (length of a side of the square) Raises: TypeError: if size is not an int, if size is a float and less than 0 ValueError: if size is less than 0 Returns: None """ if type(size) is not int: raise TypeError('size must be an integer') elif size < 0: raise ValueError('size must be >= 0') elif type(size) is float and size < 0: raise TypeError('size must be an integer') else: for x in range(size): for y in range(size): print("#", end="") print()
true
42a554b961de6ca003d11b0a2e7cbb00837486ae
kwhit2/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/9-print_last_digit.py
229
4.375
4
#!/usr/bin/python3 def print_last_digit(number): number = abs(number) # abs value needed for negative numbers print((number % 10), end="") # print the last digit with no \n return (number % 10) # return last digit
true
e19a22d3050519cb0cf86d4abfb867cecf945cb7
13522568615/zhouzx_python
/pythonBase/面向对象实例/po_game.py
1,035
4.1875
4
#面向过程编程 """ 虫子的初始位置 蚂蚁的初始位置 进入循环,条件为蚂蚁和虫子不再同一个位置 依照规则,蚂蚁和虫子移动位置 直到蚂蚁和虫子走到同一位置,程序结束 """ import random #蚂蚁 ant_point = random.randint(0,20) #虫子 worm_point = random.randint(0,20) #输出虫子与蚂蚁的初始位置 print("蚂蚁:", ant_point, "虫子:", worm_point) #指定可以走的步数 step = [-2, +2, -3 ,+3] #进入循环 while ant_point != worm_point: #选择步数 astep = random.choice(step) #判断蚂蚁走的步数是否超出了范围 if 0 <= ant_point + astep <=20: #不超出范围从新修改位置 ant_point += astep # 选择步数 astep = random.choice(step) #判断虫子走的步数是否超出了范围 if 0 <= worm_point +astep <= 20: # 不超出范围从新修改位置 worm_point += astep #输出虫子与蚂蚁现有位置 print("蚂蚁:", ant_point, "虫子:", worm_point)
false
ad0e1c52f13e80b96eeea36d41f4c3d2d3aaab52
ArthurZheng/python_hard_way
/month_list.py
573
4.1875
4
def choose_month(): months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October','November', 'December'] month_input = int(raw_input("Enter a number for the month (1-12)")) print "The month you pick is ", month_input, " month name: ", months[month_input-1] def main(): print "Enter a month number to get your month name." print "How many times do you want to play this game?" times = int(raw_input(">>>")) for i in range(times): print "\nRound number ", i +1 choose_month() print "\nEnd of the Game." main()
true
ce558dd7444d0bf453e7d055db8d869bf912fd27
gasamoma/cracking-code
/Strings/1.3.py
2,226
4.5
4
# URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.) # so Id ask if i have to make the swap from space to url space in place? YES # double space has to be compressed? No, it should be two %20 #Ok so first I was thinking of each space I encounter move the rest of the string to the back so im going to do a quick implementations of that, but that wont be efficient #IDK what means the true length of the str i would suppose that is excluding the extra space at the end so an example would be like # 'asd asd ', 7 so two extra spaces for the extra %20 i need to add def urilify(str1, str_len): # O(n^2) max_len = len(str1) if max_len == str_len: return str1 for ith in range(max_len): if ith == str_len: return str1[:max_len] if str1[ith]== " ": str1=str1[:ith]+"%20"+str1[ith+1:] #if all the string is made of spaces** ith+=2 Return str1[:max_len+1] ##if all the string is spaces then assuming the string is N i have to move n chars N times #means that n^2 # im ignoring that they are givin me the extra space at the end because of some reason def urilify_2(str1,str_len):#O(n) str1 = invert(str1)#this is O(n) ith = 0 jth = len(str1) - str_len while jth < len(str1):#this is O(n) if str1[jth]==" ": str1[ith]="0" str1[ith+1]="2" str1[ith+2]="%" ith+=2 else: str1[ith]=str1[jth] jth+=1 ith+=1 return ''.join(invert(str1))#this is O(2n) def invert(str1):#inverting a list is O(n) str_len = len(str1) str1 = list(str1)#this is O(n) for ith in range(int(str_len/2)):#this is O(n/2) tempo=str1[ith]#space O(n) str1[ith]= str1[str_len-ith-1] str1[str_len-ith-1]=tempo return str1 print(urilify_2("asdasd", 6)) print(urilify_2("asd asd ", 8)) print(urilify_2("asd a sd ", 9)) #so I could improve this solution and as soon as I start inverting the string start checking if its a space and swap with %20 and as soon as i finish i just revert it back
true
ee2339b680fadc5f869e3371dfb98513807fcb8f
gasamoma/cracking-code
/Strings/1.4.py
2,415
4.1875
4
#Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words #EXAMPLE #Input: Tact Coa #Output: True (permutations: "taco cat", "atco cta", etc.) #The spaces do not matter at the palindrom A: No they don't #Do caps matter? am I receiving caps on the imput A:they dont matter in the palindrome but # you will be receiving them # special caracters matter? like hyphens or else? A: No palindrome its just for letters but # you could assume you will be getting them #Can i use any other data structure like hash or classes? A:yes # I would say that a palindrome ignoring spaces has the same amout of chars for the left # and the right side, if is odd then there is a "center" that its char count must be odd # asd ddas for EXAMPLE # count of chars: a=2 d=3 s=2 this means that its permutations of multiple palindromes # another example "counting continue" c=2 o=2 u=2 n=4 t=2 i=2 g=1 e=1 this was so close but it has 2 odd counts so id assume that there is palindrome here def palindrome(str1):#Solution O(n) ith=0 caps_to_lower = ord('a') - ord('A') record=[0]*255 while ith < len(str1):# this is O(n) ith_c = ord(str1[ith]) if not (ith_c < ord('A') or (ith_c > ord('Z') and ith_c < ord('a')) or ith > ord('z')): #this means im interested in this char if ith_c >= ord('A') and ith_c <= ord('Z'): ith_c+=caps_to_lower record[ith_c]+=1 ith+=1 odd_count=0 for char in record:# this is O(n) if char%2 == 1: odd_count+=1 if odd_count>1: return False return True print (palindrome("asd dedas")) print (palindrome("Tact Coa")) # Another solution would be sorting and check letter by letter def palindrome2(str1): new_str=sorted(str1.lower())#this is o(nlogn) ith = 0 odds=0 while ith < len(new_str):#this is O(n) current=new_str[ith] if ord(current) < ord('a') or ord(current) > ord('z'): ith+=1 continue count_current=0 while ith < len(new_str): ith+=1 if new_str[ith]==current: count_current+=1 else: if count_current%2==1: odds+=1 if odds > 1: return False break ith+=1 print (palindrome2("asd dedas")) print (palindrome2("Tact Coa"))
true
9454cb7e1942bb081cb24c502bb71ff0d7007edd
PatrickBrennan92/hangman
/word_file_setup.py
516
4.21875
4
# This module was used to write only the basic words to a new file. # It removed all words that contained numbers or other characters. # Also removed any words starting with a capital letter, such as names and # placed etc. words = [] with open("words.txt", "r") as all_words: for word in all_words: if word.strip().isalpha() and not word.strip()[0].isupper(): words.append(word.strip()) with open("only_words.txt", "w") as only_words: for i in words: print(i, file=only_words)
true
b539fd8ada7794d0233a4ce7d09ef20b827dc180
ShahanKrakirian/Python_Stack
/Python_Fundamentals/Fun_With_Functions.py
988
4.34375
4
#--------------------------- #Odd/Even # def odd_even(): # for i in range(1,2001): # # Even # if i % 2 == 0: # print "Number is:", i, "This is an even number." # else: # print "Number is:", i, "This is an odd number." # odd_even() #--------------------------- #Multiply def multiply(my_list, number): return list(map((lambda x: x*number), my_list)) # print multiply([1,2,3,4,5],2) # Gives [2,4,6,8,10] #Hacker Challenge def layered_multiples(my_list, number): working_list = multiply(my_list, number) final_list = [] for i in range(0, len(working_list)): print working_list print "Working with the value:", working_list[i] current_list = [] for j in range(0, working_list[i]): current_list.append(1) print "Adding this list:", current_list, "to:", final_list final_list.append(current_list) return final_list print(layered_multiples([1,2,3],2))
false
aeecd07aeae8eae5ba81a766d8b8b120b2bc2baa
Sajid305/Python-practice
/Source code/Multithreading/Multithreading.py
2,041
4.28125
4
# [1] multitasking # Executing several task simultaneously is the concept of multitasking # There are 2 types of multitasking # [1] process based multitasking : Executing several task simultaneously where each task is # a seperate independent process # [2] Thread based multitasking : Executing several task simultaneously # where each task is a seperate independent part of same programm and each independent part is called thread # with multitasking # [1] we can reduce Execution time and incris performance # * animation # * multi media graphics # video games # web servers and aplication servrs use this thread base # gmail is from jboss server # the ways of creating Theread Example # [1] : Creating a therad without any class # [2] : Creating a therad by extending therad class # [3] : Creating a therad without extending therad class # [1] creating a therad without any class import threading from threading import * def whoIsthis(): for i in range(3): print('Executing Therad : child') # it will show that it is executing main therad c = Thread(target=whoIsthis) # this will make whoIsthis as a child therad c.start()# now whoIsthis will replace main therad # print(whoIsthis()) print('Executing Therad : main_thread') # [2] : Creating a therad by extending therad class class MyThread(Thread): # MyThread is child class of Therad def run(self):# overwriting for i in range(5): print('Child Thread') t=MyThread() t.start() print('This is ',current_thread().getName()) # [3] Creating a therad without extending therad class class Test: def another_class(self): for i in range(2): print('child thread') obj = Test() thread2= Thread(target=obj.another_class) thread2.start()
true
398300731ca0b213825c12f0227f5fee7f171962
Sajid305/Python-practice
/Source code/so many kind of function , like map,Enumerate,filter etc/any and all function .py
1,877
4.40625
4
# any and all function # finding even number from a list if all of the number # is even then we will print true if one of them are odd then we will return false # i will do it with the help of all function # first with normal way of using all() function # number1 = [2,4,6,8,10] # even_number = [] # for num in number1: # even_number.append(num % 2 == 0) # print(all([True,True,True,True,True])) # -----> True # print(all([True,True,True,False,True])) # ----> if we change value then it will show us false # now with list comprehension of all() function # number1 = [2,4,6,8,10] # print(all([num%2==0 for num in number1])) # same work with any() function # number1 = [2,4,6,8,10] # number2 = [1,3,5,7,9] # even_number = [] # for num in number2: # even_number.append(num%2 == 0) # print(any(even_number)) # -----------> it will return us flase becuse any one of them is not true as given by condition # now with list comprehension of any() function # number1 = [2,4,6,8,10] # print(any([num%2==0 for num in number1])) # in this practice we will be make a function that allow us to sum of int # but is there any string present then it will through us a messsg # def is_int_or_float(*args): # if all([(type(arg) == int or type(arg) == float) for arg in args]): # total = 0 #------------> this block of code will run when input type is right if not then it will show wrong input # for num in args: # total += num # return total # else: # return "wrong input type" # print(is_int_or_float(1,2,3,4,5))
true
52a69f0f6abdd0093187519415589e6279960048
Sajid305/Python-practice
/Source code/so many kind of function , like map,Enumerate,filter etc/function_extra_usefull_stuff.py
505
4.28125
4
# Doc string #''' this is doc string '''' def func(a,b): ''' this is a doc string this function use tow argument and return addition of them''' return a+b print(func(1,3)) print(func.__doc__) # ----> this is how we can check our doc string # We can allso see doc string of built in function with the help of help() function print(help(len)) print(help(max)) # -----> this is how we can use help function print(help(type)) print(help(help))
true
39c210d91f06287ec8dd4220b143a3660bc7d7cb
Sajid305/Python-practice
/Source code/Lambda Expression/Lambda Expression Practice .py
1,045
4.28125
4
# Lambda Expression Practice # def is_even(i): # if i%2 == 0: # return True # else: # return False # print(is_even(5)) # def is_even(s): # return s%2 == 0 # s%2 == 0 ----> true , false # print(is_even(4)) # def return_last_carecter(s): # return s[-1] # print(return_last_carecter("shajid")) # same function with lambda expression # is_even = lambda s : s%2 == 0 # print(is_even(9)) # return_last_carecter = lambda s : s[-1] # print(return_last_carecter("shajid")) # lambda with if else # def function(s): # if len(s) > 5: # return True # else: # return False # print(function("sha")) # def function(s): # return len(s) > 5 # print(function("shajid")) # Same function with if else # function = lambda s : True if len(s)>5 else False # print(function("sha")) # function = lambda s : len(s)>5 # print(function("shajid"))
false
e97c86a58301197e130c6f615853a9491a09c1c2
Sajid305/Python-practice
/Source code/Decoretor/Decorators with arguments .py
916
4.125
4
# Decoretor with argument and nested Decoretor this decoretor will only take string as argument from functools import wraps def only_string_alow(data_type): # ----> this decoretor made for only take str as argument def nested_decoretor(any_function):# ----> this decoretor is for taking function @wraps(any_function) def wrapper(*args,**kwargs): if all([type(arg)== data_type for arg in args]): return any_function(*args,**kwargs) print('only string alowed') return wrapper return nested_decoretor @only_string_alow(str) def string_join(*args): # --> this function one or more argument and joind them together joind = '' for i in args: joind += i return joind var = string_join('shajid',' rayhan') # --> if we pass a int on this this will return out else message print(var)
true
23b43e444e3c4bb55cf56a3bd4f43f16cb9ec2be
Sajid305/Python-practice
/Source code/random practice/dict_summary.py
1,316
4.375
4
# summary dictionary # what is dictionary # unordered collection of data d = {'name' : 'Shajid', 'age' : 23} # or d1 = dict(name = 'Shajid', age = 23) # or d2 = { 'name' : 'Shajid', 'age' : 23, 'fav_movies' : [] } # how to access data from dictionary # you cannot do like # d[0] , because there is no order inside dictionary # syntax # print(dictname[keyname]) # print(d['name']) # add data inside empty dict empty_dict = {} empty_dict['key1'] = 'value1' empty_dict['key2'] = 'value2' # print(empty_dict) # check existence of values inside dict # use in keyword to check for keys # how to iterate over dictionary # most common method # for key , value in d.items(): # print(f' key is {key} and value is {value}') # to print all keys # for i in d: # print(i) # to print all values # for i in d.values(): # print(i) # most common dict methods # get method # to access a key and check existance # print(d.get('name')) # Q - why we use get # A - to get rid of error # example # print(d['names']) # print(d.get('names')) # to delete item # pop ---> take one argument which is keyname # popped = d.pop('name') # print(popped) # print(d) # popitem popped = d.popitem() print(popped) print(d)
false
7be42beca9ceebe90fd285ce02a3c575fe8ca11f
rsairam34/sample
/range.py
251
4.1875
4
#range function print (range(10)) print (range(5,10)) print (range(0,10,3)) print (range(-10,-100,-30) list = ["mary","had","a","little","lamb"] for i in range(len(list)): print i,list[i] print "third edit locally" print "fifth change locally"
false
57f29174db1efe288074c09198d9ece7d3bfc950
bhumphris/Word-Jumble
/Word Jumble.py
651
4.15625
4
import random birds = ["Macaw", "Toucan", "Pheasant", "Painted Bunting", "Cardinal", "Crane", "Flamingo", "Parakeet", "Love Bird", "Mallard", "Finch", "Robin", "Dove", "Hawk", "Eagle"] selection = random.choice(birds) answer = selection jumble = list(selection) for current_index in range(len(jumble)): random_index = random.randrange(0, len(jumble)) temp = jumble[current_index] jumble[current_index] = jumble[random_index] jumble[random_index] = temp for letter in jumble: print letter, guess = raw_input("\nWhat kind of bird is jumbled?") guess = guess.upper() if guess == answer: print("correct") else: print(answer)
true
ba66d8b9d3be607f5a1d710aafe320fa236c1300
purushottamkaushik/DataStructuresUsingPython
/DyammicProgramming/BricksFilling.py
1,067
4.34375
4
def BrickFilling(n): """ This is Problem which fills N*4 wall with 1*4 bricks this is the recursive solution of the problem :param n is the one dimension of the wall may be width or height :return the number of ways you can put bricks on the wall """ if n==0 or n == 1 or n == 2 or n == 3 : return 1 else: return BrickFilling(n-1) + BrickFilling(n-4) if __name__=="__main__": n =5 print("Using recurison" , BrickFilling(n)) def BrickFillingDP(n): """ this is a function to implement brick filling problem using dynamic programming (Using bottom up Approach) :param n: is the one of the dimensions of the wall :return: integer : number of ways to fill the wall with the bricks """ table = [0] *(n+1) # print(table) for i in range(0,4): table[i] = 1 # print(table) for j in range(4,n+1): table[j] = table[j-1] + table[j-4] return table[n] if __name__=="__main__": n =5 print("Using recursive DP approach " , BrickFillingDP(n))
true
c432c895df59851779f957d02f1c9deb77441caa
purushottamkaushik/DataStructuresUsingPython
/ImplementTrieLeetcode208.py
1,809
4.125
4
class Node: def __init__(self,val,isWord=False): self.val = val self.child = {} self.isWord = isWord class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = Node("") def insert(self, word: str) -> None: """ Inserts a word into the trie. """ # Setting current to the root Node current = self.root # Iterating character by character and checking it is not present in the child nodes if present then point to the node else create a new node with the character and point it towards the character. for ch in word: if ch not in current.child: current.child[ch] = Node(ch) current = current.child.get(ch) current.isWord = True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ current = self.root for ch in word: if ch in current.child: current = current.child.get(ch) else: return False return current.isWord def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ current = self.root for ch in prefix: if ch in current.child: current = current.child.get(ch) else: return False return True # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
true
2244144b6ac2656b94a86bc65919def6364dec81
purushottamkaushik/DataStructuresUsingPython
/ArraysProblem/Python/SelectionSort.py
469
4.125
4
def selectionSort(a): for i in range(len(a)): """Traverse through the whole array""" min_index = i # storing the index as the minimum index for j in range(i+1,len(a)): # from index i + 1 to last if a[j] < a[min_index]: min_index = j a[i] , a[min_index ] = a[min_index ] , a[i] # swaping the current element a = [3,2,4,51,1,43] print("Original array" , a) selectionSort(a) print("After sorting " , a)
true
f522b05378e8ff60d3d22de6cbe3d927dceafd3d
rpedraza01/interview-prep
/Python/fizzbuzz_practice_again.py
722
4.40625
4
# print "Fizz" for numbers that are multiples of 3 # print "Buzz" for numbers that are multiples of 5 # print "FizzBuzz" for numbers that are multiples of 3 AND 5 # for num in range(1, 1001): # if num % 3 == 0 and num % 5 == 0: # # if num % 15 == 0: # print("FizzBuzz") # elif num % 3 == 0: # print("Fizz") # elif num % 5 == 0: # print("Buzz") # else: # print(f'{num} is not a multiple of 3 and/or 5') num = int(input('Please pick a number > ')) if num % 15 == 0: print("FizzBuzz, your number is a multiple of 3 and 5") elif num % 3 == 0: print("Fizz, your number is a multiple of 3") elif num % 5 == 0: print("Buzz, your number is a multiple of 5") else: print(f'{num} is not a multiple of 3 and/or 5')
false
93055cb2e17a911765c8d5851f748d21c6772a98
aclogreco/lpthw
/ex20.py
820
4.25
4
# ex20.py """ Exercise 20 -- Learn Python the Hard Way -- Zed A. Shaw A.C. LoGreco """ from sys import argv # unpack cmd line arguments script, input_file = argv # print out the contents of file f def print_all(f): print f.read() # set file cursor position to the begining of file f def rewind(f): f.seek(0) # print a line from file f def print_a_line(line_count, f): print line_count, f.readline() # open the file for reading current_file = open(input_file) print "First, let's print the whole file:\n" print_all(current_file) print "Now, let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file)
true
2d5710d2e041ed64cc1502c61585800d1b25752f
lunettakim/Project
/turtle_game.py
1,849
4.3125
4
# Turtle game using the package 'turtle' # Import relevant modules import turtle import random import time # Setting up a nice screen for our game screen = turtle.Screen() screen.bgcolor('pink') # Background colour # We want two players and that whoever gets to the other sinde wins. # Player one set up player_one = turtle.Turtle() # Colour of player one player_one.color('red') # Make this player a turtle player_one.shape('turtle') # Player two set up player_two = player_one.clone() player_two.color('green') # Let's position our players player_one.penup() # line will be removed player_one.goto(-300,200) player_two.penup() player_two.goto(-300,-200) # Let's draw a finish line player_one.goto(300,-250) player_one.left(90) player_one.pendown() player_one.color('black') player_one.forward(500) player_one.write('Finish', font=24) # go back to the first place player_one.penup() player_one.color('red') player_one.goto(-300,200) player_one.right(90) # We need to make sure both players have their pens down player_one.pendown() player_two.pendown() # Let's create values for the die die = [1,2,3,4,5,6] # Create the game for i in range(30): # put number high enough so turtle reach the finish line if player_one.pos() >= (300,250): print("Player One wins the race!") break elif player_two.pos() >= (300, -250): print("Player Two wins the race!") break else: die_roll = random.choice(die) player_one.forward(30*die_roll) time.sleep(1) #player moves and sleep for one second #to make it a bit slower die_roll2 = random.choice(die) player_two.forward(30 * die_roll2) time.sleep(1) # this keeps the turtle drawing on the screen turtle.done()
true
61c5751ed2815fbbf28de27d166e258c0b06d7ee
Svagtlys/PythonExercises
/PasswordGenerator.py
2,542
4.21875
4
import random import string # Write a password generator in Python. Be creative with how you # generate passwords - strong passwords have a mix of lowercase # letters, uppercase letters, numbers, and symbols. The passwords # should be random, generating a new password every time the user # asks for a new password. Include your run-time code in a main method. # Extra: # Ask the user how strong they want their password to be. # For weak passwords, pick a word or two from a list. def weak(): #pick from word list return random.choice(['strange','disgusting','chivalrous','decide','loud','vivacious','love','toothpaste','steal','defeated','wood','claim']) def passgen(strength): #generator ''' Takes in strength as an int defining how many characters to generate for the password. Returns a result containing the defined number of psuedo-randomly generated characters. ''' password = '' max = 2 for i in range(strength): chartype = random.randint(0,max) #0 = num, 1 = letter, 2 = specialchar if chartype == 0: password += random.choice(string.digits) #this was randint(0,9), but when I was looking for the letters and punctuation, I found this, so elif chartype == 1: password += random.choice(string.ascii_letters) else: password += random.choice(string.punctuation) max = 1 #I got tired of all special chars return password # apparently this is a python main function if __name__ == '__main__': # I looked it up, apparently __name__ is a variable # the file has set to its name, until it's executed, # then its name is '__main__', so this here is asking # if the file is being executed, essentially. Smart stronglength = 16 mediumlength = 8 #first, ask for strength #Two methods, weak and other: # weak will pick from word list # other has random gen, which picks length depending on med or strong strength = input("What strength do you want your password to be? (S)trong, (M)edium, (W)eak\n").lower() while(strength != "s" and strength != "m" and strength != "w"): strength = input("Please type s for strong, m for medium, or w for weak.\n").lower() if(strength == "w"): print("Your weak password is: " + weak()) elif(strength == "m"): print("Your medium password is: " + passgen(mediumlength)) else: print("Your strong password is: " + passgen(stronglength))
true
eff41102ff734ac7ca4579b47549adee5ac6114a
Svagtlys/PythonExercises
/Fibonacci.py
649
4.34375
4
# Write a program that asks the user how many Fibonnaci # numbers to generate and then generates them. Take this # opportunity to think about how you can use functions. # Make sure to ask the user to enter the number of numbers # in the sequence to generate def gen_fib(length, mylist = []): if(len(mylist) < 2): mylist.append(1) else: mylist.append(mylist[len(mylist)-1] + mylist[len(mylist)-2]) if(len(mylist) == length): return mylist else: return gen_fib(length, mylist) print(gen_fib(int(input("How many numbers of the Fibonacci sequence would you like to generate?\n"))))
true
77844a8b6a18dd00e1f2dba0cc8f0b4800d0b927
Svagtlys/PythonExercises
/ElementSearch.py
1,148
4.1875
4
# Write a function that takes an ordered list of numbers (a list where # the elements are in order from smallest to largest) and another number. # The function decides whether or not the given number is inside the list # and returns (then prints) an appropriate boolean. # Extras: # Use binary search. def search(myset, num): ''' Takes in an ordered list or set, and a number to search for Uses binary search to see if the number is in the list Return True if it is or False if it isn't ''' foundnum = None while len(myset) >= 1: #if the halved list is over 1 and we haven't found the number we're searching for, keep searching foundnum = myset[int((len(myset)-1)/2)] if foundnum == num: return True elif(foundnum < num): myset = myset[int((len(myset)-1)/2)+1:len(myset)] else: #foundnum > num myset = myset[0:int((len(myset)-1)/2)] return False if __name__ == "__main__": myseta = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] mysetb = [1, 3, 5, 30, 42, 43, 500, 700] num = 13 print(search(mysetb, num))
true
6f3ecd911dec9a1c3b037b361a851a9f7a38a156
Pravin-N/python-scripts
/pro_movefiletype.py
1,619
4.34375
4
#! Python3 # Write a program that walks through a folder tree and searches for files with a certain file extension # (such as .pdf or .jpg). Copy these files from whatever location they are in to a new folder. #import necessary modules to be used. import os, shutil from pathlib import Path # create function that moves user specified files from the user specified folder to a user specified new folder. def movefile(folder, filetype, newfolder): if not os.path.exists(newfolder): os.mkdir(newfolder) if os.path.exists(folder): for root, subfolder, files in os.walk(folder): print(f"Searching {filetype} in {root}") for file in files: if file.endswith(filetype): print(str(os.path.join(root, file)) + ' moved to ' + (newfolder)) shutil.copy(os.path.join(root, file), newfolder) else: continue # Request input from user from the folder the folders need to be moved. oldfolderpath = input(r'Please enter the full path of the folder to be moved: ') print(oldfolderpath) # Request input from user for the type of files need to moved. typeoffile = '.' + str(input(r'Please enter the extention of the file to be moved (pdf, txt, doc, jpg, docx, py): ')) print(typeoffile) # Request the folder name that would be saved on the desktop. newfoldername = str(Path(r'C:\Users\ACE\Desktop', str(input(r'Enter the name of the folder to where the files will be moved. This will be on the desktop: ')))) print(newfoldername) movefile(oldfolderpath, typeoffile, newfoldername)
true
cf86bea9b198d357c9d02c6d99ecbbbde2654a25
susejzepol/Proyectos_python
/Find.divisors.of a.number.py
637
4.25
4
""" Task... Find the number of divisors of a positive integer n. Random tests go up to n = 500000. Examples divisors(4) = 3 # 1, 2, 4 divisors(5) = 2 # 1, 5 divisors(12) = 6 # 1, 2, 3, 4, 6, 12 divisors(30) = 8 # 1, 2, 3, 5, 6, 10, 15, 30 """ def divisors(n): count = 0 for numer in range(n): var = divmod(n,numer+1) if(var[1] == 0): count += 1 return count print("Calling the function....") print("The divisor function returns : " + str(divisors(4))) """ Created by... Jesus Lopez Mesia (https://www.linkedin.com/in/susejzepol/) At date... 2019-10-14 """
true
666d9427145c035218c161ac7d5a0a31ae26db50
kishanameerali/Coding_Dojo_Python1
/Foo_and_bar.py
753
4.21875
4
#Foo and Bar """ Write a program that prints all the prime numbers and all the perfect squares for all numbers between 100 and 100000. For all numbers between 100 and 100000 test that number for whether it is prime or a perfect square. If it is a prime number print "Foo". If it is a perfect square print "Bar". If it is neither print "FooBar". Do not use the python math library for this exercise. For example, if the number you are evaluating is 25, you will have to figure out if it is a perfect square. It is, so print "Bar". """ for num in range (2,100): for divider in range(2, num/2): if (num % divider is 0): print num print "FooBar" #if (num % i) != 0: #print "foo" #elif num**0.5
true
ceae7932304264bcb33d200039f44dd1c76daf0e
kishanameerali/Coding_Dojo_Python1
/Checkerboard_2.py
283
4.46875
4
#Checkerboard Assignment using nested for loops #Write a program that prints a 'checkerboard' pattern to the console. for row in range(1,9): for col in range(1,9): if (row % 2 is odd and col % 2 is 0): print " " if (row % 2 is 0 and col % 2 is 0):
true
a4e50b4103bdb1bbb9decddaf3042c9f9ae6f82a
schebiwot/Python-class
/lesson_8/lesson_2.py
1,194
4.25
4
#inheritance class Animal:#parent class def __init__(self,name,country): self.name=name self.country=country def printDetails(self): print("The name is :{} and country of origin is:{}".format(self.name,self.country)) class Goat(Animal):#child class #pass #used when you dont want to add any code def __init__(self,name,country,owner): #the child will no longer inherit parent's self.name=name self.country=country self.owner=owner def printDetails(self): print("The name is :{} and country of origin is:{} ,the owner is {}".format(self.name,self.country,self.owner)) #object g1=Goat("gush","kenya" ,"jon") g1.printDetails() g2=Goat("brayo","sudan",'doe') g2.printDetails() class Dog(Animal): def __init__(self,name,country,color): # Animal.__init__(self,name,country) #for a child to inherit from the parent class 'animal' # inhert from parent super().__init__(name,country) self.color=color def printDetails(self): print("name: {} and country : {} and the color is:{}".format(self.name,self.country,self.color)) d1=Dog('smooth',"chiwawa","red") d1.printDetails()
false
ee17f742cf9883dde7031e7caa3b2ac50a8969b7
libra202ma/cc150Python
/chap04 Trees and Graphs/4_5.py
1,015
4.15625
4
""" Implement a function to check if a binary tree is binary search tree. - Search. Modified, in-order DFS and keep track of a global variable last_visited. Check if left branch is binary search tree, if false, return false. Check if current data is less or equal to global min, if yes, retrun false. Update the last_visited. Check if the right branch is balanced. (???) NOTE: check only left.data <= current.data < right.data is not sufficient. The requirement is that ALL left data <= current data < ALL right data. - DFS. Use a range (min, max). When branch left, the max gets updated using current data. When branch right, the min updated using current data. Then the (min, max) passed to the recursion of left or right check. If the current data does not satisfy the passed range, return false. """ def isBST(t, min=float('-inf'), max=float('inf')): if not min <= t.data < max: return False if t.left: isBST(t.left, min, t.data) if t.right: isBST(t.right, t.data, max)
true
12a0da6e4b394d7f570ebded0c4d733c735d32d0
libra202ma/cc150Python
/chap05 Bit Manipulation/5_1.py
984
4.15625
4
""" You are given two 32-bit number, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between 3 and 2. EXAMPLE Input: N = 10000000000, M = 10011, i = 2, j = 6 Output: N = 10001001100 - update Bits. Firstly clear bits [i:j] in N, using AND masks like 1111000111. Then shift M to [i, j], perform an OR operation on N. """ def insert(N, M, i, j): # clear bits from i to j clearmask = 0 for k in range(i, j+1): clearmask += 1 << k clearmask = ~clearmask N &= clearmask # set bits N |= M << i return N def test_insert(): N = 0b10000000000 M = 0b10011 i = 2 j = 6 assert insert(N, M, i, j) == 0b10001001100
true
30dd034601cb0942414a7d6d33931bc114d71a82
libra202ma/cc150Python
/chap03 Stacks and Queues/3_5.py
1,134
4.21875
4
""" Implement a MyQueue class which implements a queue using two stacks. - Naive. For every enqueue operation, just enqueue it onto s1. For every dequeue operation, we first pop all nodes from s1 to s2, then pop from s2 to get the oldest element, then pop all nodes from s2 back to s1. - lasy execuation. Again for enqueue operation, we push it onto s1. But exec dequeue from s2. If s2 is empty, poping all nodes from s1 to s2. If s2 is not empty, the top of s2 is oldest one, just pop it. (WOW) """ class MyQueue: def __init__(self): self.newstack = [] self.oldstack = [] def push(self, data): self.newstack.append(data) def pop(self): if self.oldstack: return self.oldstack.pop() elif self.newstack: # dump newstack to oldstack while self.newstack: self.oldstack.append(self.newstack.pop()) return self.oldstack.pop() else: return None def test_myqueue(): q = MyQueue() q.push(1) q.push(2) assert q.pop() == 1 assert q.pop() == 2 assert q.pop() == None
true
3d2a1ac662fb5fa45415c0d438a8d6b1c91fcda6
libra202ma/cc150Python
/chap03 Stacks and Queues/3_3.py
1,800
4.125
4
""" Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is, pop() should return the same value as it would if there where just a single stack). - naive. use variables/lists to log all stack and current active stack. FOLLOWUP Implement a function popAt(int index) which performs a pop operation on a specific sub-stack. - same as above. """ class Stack(): def __init__(self): self.arrlen = 10 self.data = [] self.narrs = 0 self.addarr() self.top = -1 def addarr(self): self.data.append([-1] * self.arrlen) self.narrs += 1 def push(self, data): if self.top == self.arrlen - 1: self.addarr() self.top = 0 else: self.top += 1 self.data[self.narrs-1][self.top] = data def pop(self): res = self.data[self.narrs-1][self.top] if self.top == 0: self.data.pop() # remove the last empty stack self.narrs -= 1 self.top = self.arrlen - 1 else: self.top -= 1 return res def peek(self): return self.data[self.narrs-1][self.top] def test_stack(): s = Stack() for i in range(15): s.push(i) assert s.peek() == 14 for i in range(5): s.pop() assert s.peek() == 9 for i in range(10): s.pop() s.push(1) assert s.pop() == 1
true
0b65056f2e3025cc5812aa3763c9e6d2fbb9ecd4
libra202ma/cc150Python
/chap09 Recursion and Dynamic Programming/9_09.py
1,138
4.125
4
""" Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them share the same row, column or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board. - classic. Firstly, the queens should be on different rows and columns. That is, for every row or column,there is one queen exactly. Thus from the point of row, the queen just have the freedom of column. Then for-loop or recursion can be applied to find all possible arrangement. """ def eightqueen(n): if n == 1: return [[i] for i in range(1, 9)] arrangements = [] for subarr in eightqueen(n - 1): for c in range(1, 9): # check all possible columns if c in subarr: # column occupied continue for qr, qc in enumerate(subarr): if abs(c - qc) == abs(n - qr - 1): break else: # not on same column and diagonal, Python's special 'for-else' clause arrangements.append(subarr + [c]) return arrangements def test_eightqueen(): assert len(eightqueen(8)) == 92
true
bc71c13906df3fbef02182d3962078664612d798
HareshSankaliya/HareshPython
/HareshPy/HareshPractice/Datetimeformat.py
539
4.21875
4
from datetime import date from datetime import time from datetime import datetime today=date.today() #today date print(today) print(today.strftime("%Y")) # Print only year with yyyy format print(today.strftime("%y")) # Print only year with yy format print(today.strftime("%a")) # Print today week name print(today.strftime("%d")) # Print today date dd format print(today.strftime("%B")) # Print month name print(today.strftime("%a,%d %B,%y")) # Print week,date,month,year print(today.strftime("%x")) # print today date in mm/dd/yy format
true
a94cce2fcc9f305be51aa53edd18b54745182aec
dsmilo/DATA602
/hw2.py
2,525
4.1875
4
# Dan Smilowitz DATA 602 hw2 #1. fill in this class # it will need to provide for what happens below in the # main, so you will at least need a constructor that takes the values as (Brand, Price, Safety Rating), # a function called showEvaluation, and an attribute carCount class CarEvaluation: 'A simple class that represents a car evaluation' #all your logic here carCount = 0 def __init__(self, brand = '', price = '', safety = 0): self.brand = brand self.price = price self.safety = safety CarEvaluation.carCount += 1 def showEvaluation(self): #The Ford has a High price and it's safety is rated a 2 print("The %s has a %s price and its safety is rated a %d" %(self.brand, self.price, self.safety)) #2. fill in this function # it takes a list of CarEvaluation objects for input and either "asc" or "des" # if it gets "asc" return a list of car names order by ascending price # otherwise by descending price def sortbyprice(car_list, order = ""): sorted_cars = [] is_desc = True if order.lower() == "asc": is_desc = False price_num = {'High': 3, 'Med': 2, 'Low': 1} car_list.sort(key= lambda x: price_num[x.price], reverse = is_desc) for i in range(len(car_list)): sorted_cars.append(car_list[i].brand) return sorted_cars #3. fill in this function # it takes a list for input of CarEvaluation objects and a value to search for # it returns true if the value is in the safety attribute of an entry on the list, # otherwise false def searchforsafety(car_list, car_rating): found = False for item in car_list: if item.safety == car_rating: found = True return found # This is the main of the program. Expected outputs are in comments after the function calls. if __name__ == "__main__": eval1 = CarEvaluation("Ford", "High", 2) eval2 = CarEvaluation("GMC", "Med", 4) eval3 = CarEvaluation("Toyota", "Low", 3) print "Car Count = %d" % CarEvaluation.carCount # Car Count = 3 eval1.showEvaluation() #The Ford has a High price and its safety is rated a 2 eval2.showEvaluation() #The GMC has a Med price and its safety is rated a 4 eval3.showEvaluation() #The Toyota has a Low price and its safety is rated a 3 L = [eval1, eval2, eval3] print sortbyprice(L, "asc"); #[Toyota, GMC, Ford] print sortbyprice(L, "des"); #[Ford, GMC, Toyota] print searchforsafety(L, 2); #true print searchforsafety(L, 1); #false
true
98bb48d3f58796ed29294a615af14a314f4c8284
carlgriffin57/python-exercises
/data_types_and_variables.py
2,134
4.21875
4
# You have rented some movies for your kids: The little mermaid (for 3 days), Brother Bear (for 5 days, they # love it), and Hercules (1 day, you don't know yet if they're going to like it). If price for a movie per day # is 3 dollars, how much will you have to pay? num_of_little_mermaid_days = 3 num_of_brother_bear_days = 5 num_of_hercules_days = 1 price_per_day = 3 total_price = (num_of_little_mermaid_days + num_of_brother_bear_days + num_of_hercules_days) * price_per_day print(total_price, "dollars") # Suppose you're working as a contractor for 3 companies: Google, Amazon and Facebook, they pay you a different # rate per hour. Google pays 400 dollars per hour, Amazon 380, and Facebook 350. How much will you receive in # payment for this week? You worked 10 hours for Facebook, 6 hours for Google and 4 hours for Amazon. google_pay_per_hour = 400 amazon_pay_per_hour = 380 facebook_pay_per_hour = 350 total_payment = (google_pay_per_hour * 6) + (amazon_pay_per_hour * 4) + (facebook_pay_per_hour * 10) print(total_payment, "dollars") # A student can be enrolled to a class only if the class is not full and the class schedule does not conflict # with her current schedule. class_full = True conflicting_schedule = True student_enrollment = not class_full or not conflicting_schedule print(student_enrollment) # A product offer can be applied only if people buys more than 2 items, and the offer has not expired. Premium # members do not need to buy a specific amount of products. item_count = 3 offer_expired = False premium_member = True product_offer = (item_count > 2 and not offer_expired) or (premium_member and not offer_expired) print(product_offer) username = 'codeup' password = 'notastrongpassword' # the password must be at least 5 characters password_length = len(password) >= 5 print(password_length) # the username must be no more than 20 characters username_length = len(username) < 21 print(username_length) # the password must not be the same as the username different = password != username print(different) # bonus neither the username or password can start or end with whitespace bonus_answer =
true
babec0f381668c48efa3dec3a386790cd4398241
Geogy-fjq/Python
/Python/Basic/lab4-Array-2.py
432
4.3125
4
""" 用程序实现两个字符串的比较、追加、拷贝。 具体流程如下: Step1:输入两个字符串。 Step2:使用选择语句比较,使用简单符号计算追加、拷贝。 Step3:输出结果。 """ str1=str(input("str1 is:")) str2=str(input("str2 is:")) if str1<str2: print("str1<str2") elif str1>str2: print("str1>str2") else: print("str1=str2") str1+=str2 print(str1) str1=str2 print(str1)
false
bc6b770bb9a073c1794d688cff709c3dba067ea4
Geogy-fjq/Python
/Python/Basic/lab1-Selection-1.py
508
4.15625
4
""" 熟悉RAPTOR算法设计环境。设计一个程序,输出一个提示信息,请求用户输入一个数字, 如果大于0则输出“Positive”,如果小于0则输出“Negative”,如果等于0则输出“Zero”。 基本流程如下: Step1:请求输入一个数字。 Step2:判断输入数字的正负性质,对应输出结果。 """ num = eval(input("Please enter a number.")) if num > 0: print("Positive") elif num < 0: print("Negative") elif num == 0: print("Zero")
false
2e4e4bf90864d841a3ff63b8e42d5ee8c319ff9f
arvindrocky/dataStructures
/trees/binary_search_tree.py
1,228
4.21875
4
class BST: def __init__(self, value: int): self.value: int = value self.left_node: BST = None self.right_node: BST = None def insert_node(self, value: int) -> None: if value < self.value: if self.left_node: self.left_node.insert_node(value) else: self.left_node = BST(value) else: if self.right_node: self.right_node.insert_node(value) else: self.right_node = BST(value) def print_in_order_tree(self) -> None: if self.left_node: self.left_node.print_in_order_tree() print(self.value) if self.right_node: self.right_node.print_in_order_tree() bst = BST(100) print("Printing tree with only root:") bst.print_in_order_tree() bst.insert_node(50) bst.insert_node(150) bst.insert_node(20) bst.insert_node(125) bst.insert_node(130) print("Printing In Order of a tree:") bst.print_in_order_tree() bst1 = BST(1) bst1.insert_node(2) bst1.insert_node(3) bst1.insert_node(4) bst1.insert_node(5) bst1.insert_node(6) bst1.insert_node(7) print("Printing In Order of another tree which is BFT:") bst1.print_in_order_tree()
false
a240a672532d266ab35092738f9a51726a4f5b41
DVEC95/PY4E
/Chapter 5 - Iterations/PY4E_L5_Ex1.py
812
4.1875
4
# Exercise 1: # Write a program which repeatedly reads numbers until the user enters “done”. # Once “done” is entered, print out the total, count, and average of the numbers. # If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number. numbers = [] while True: user_input = input('Enter a number: \n') try: if user_input != 'done': numbers.append(int(user_input)) except: print('Please enter a numeric value or type "done" to exit.') if user_input == 'done': break print('Numbers entered:', len(numbers)) print('Sum of numbers:', sum(numbers)) if len(numbers) > 0: print('Average:', sum(numbers) / len(numbers)) else: print('Average not available.')
true
019feef40b84fc4261d3130d738fc2d44ad64019
DVEC95/PY4E
/Chapter 7 - Files/PY4E_L7_Ex2.py
943
4.3125
4
# Exercise 2: # Write a program to prompt for a file name, and then read through the file and look for lines of the form: # X-DSPAM-Confidence: 0.8475 # When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. # Count these lines and then compute the total of the spam confidence values from these lines. # When you reach the end of the file, print out the average spam confidence. file_name = input('Please enter a file name: \n') try: txt_file = open(file_name, 'r') except: if file_name == 'na na boo boo': print('Grow up.') print('Please enter a valid file name.') exit() num_array = [] for line in txt_file: if line.startswith('X-DSPAM-Confidence:'): num = line[line.find(':') + 2:line.find('\n')] num_array.append(float(num)) print('Average spam confidence:', sum(num_array) / len(num_array))
true
4d12e59d208e7ddcaf9bf6df41c8f7436a4a3f23
orvindemsy/python-practice
/19.08.16 beginner project/letterCapitalizeVer2.py
769
4.21875
4
''' Written by: Orvin Demsy Date: 17 August 2019 Source: https://coderbyte.com/solution/Letter%20Changes#Python I'm rewriting it to get a better understanding Challenge: Have the function LetterCapitalize(str) take the str parameter being passed and capitalize the first letter of each word. Words will be separated by only one space. e.g. Input:"hello world" Output:"Hello World" Input:"i ran there" Output:"I Ran There" ''' def LetterCapitalize(sentence): #Split the sentence into array of words word = sentence.split() for i in range(len(word)): #Create a word with first letter capitalized word[i] = word[i][0].upper() + word[i][1:] return " ".join(word) sentence = "the man who can't be moved" print(LetterCapitalize(sentence))
true
ad82ed794489e9e0326d8b6ffddde41c85f871d0
orvindemsy/python-practice
/CodeWars 8kyu Challenges/isItPalindromeVer2.py
353
4.125
4
''' Written by: Orvin Demsy Date: 19 August 2019 Description: Write function isPalindrome that checks if a given string (case insensitive) is a palindrome. Only one-word input is accepted e.g. madam = True Mom = True walter = False ''' def is_palindrome(word): word = word.lower() return word == word[::-1] word = 'Mom' print(is_palindrome(word))
true
59284127bf0405c4b2e4d14115a38d4e48bcb343
orvindemsy/python-practice
/19.08.16 beginner project/letterChanges.py
1,400
4.34375
4
''' Written by: Orvin Demsy Date: 16 August 2019 Challenge : Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string. e.g. Input:"hello*3" Output:"Ifmmp*3" Input:"fun times!" Output:"gvO Ujnft!" All capitalized letter will be lower-cased ''' import string alphabet = string.ascii_lowercase alphabet = list(alphabet) word = input("Enter a sentence or words : ") word = word.lower() new_word = "" for i in range(len(word)): #check if the character is alphabet if word[i].isalpha(): #check if the character is z if word[i] == "z": new_word = new_word + "A" #check if the character is not z elif word[i] != "z": new_idx = alphabet.index(word[i]) + 1 #check if the new character is alphabet if alphabet[new_idx].lower() in "aiueo": new_word = new_word + alphabet[new_idx].upper() else: #check if the new character is not alphabet new_word = new_word + alphabet[new_idx] #check if the character is not alphabet else: new_word = new_word + word[i] print(new_word)
true
4bc7c98ee2f36bc3bb74268cad48108be82b5f44
orvindemsy/python-practice
/19.08.16 beginner project/reverseString.py
737
4.375
4
''' Written by: Orvin Demsy Date: 16 August 2019 Create a function that takes a string as an argument and spit out that string in reverse e.g: hello -> olleh ''' #The first method extended slice syntax def reverse_word_1(word): return word[::-1] #Return olleH print("The reversed input is = " + reverse_word_1(input("Enter a sentences/ a word : "))) #The second method def reverse_word_2(word): return ''.join(reversed(word)) print("The reversed input is = " + reverse_word_2(input("Enter a sentences/ a word : "))) #Third method using loop def reverse_word_3(word): str = "" for i in word: str = i + str return str print("The reversed input is = " + reverse_word_3(input("Enter a sentences/ a word : ")))
true
3552eb59106c8bcf07113cd7d23c516e179b55b7
muradsamadov/python_learning
/python_exercises_practice_solution/python_basic/part_25.py
238
4.25
4
# Write a Python program to concatenate all elements in a list into a string and return it. def function(list): result = "" for i in list: result = result + str(i) return result print(function([1, 5, 12, 2]))
true
92907bac9ec611f8f5550bfa200d6c9b11d093d7
muradsamadov/python_learning
/python_exercises_practice_solution/python_modules/module_random/part_4.py
927
4.53125
5
# Write a Python program to generate a random integer between 0 and 6 - excluding 6, random integer between 5 and 10 - excluding 10, random integer between 0 and 10, with a step of 3 and random date between two dates. Use random.randrange() import random import datetime print("Generate a random integer between 0 and 6:") print(random.randrange(5)) print("Generate random integer between 5 and 10, excluding 10:") print(random.randrange(start=5, stop=10)) print("Generate random integer between 0 and 10, with a step of 3:") print(random.randrange(start=0, stop=10, step=3)) print("\nRandom date between two dates:") start_dt = datetime.date(2019, 2, 1) end_dt = datetime.date(2019, 3, 1) time_between_dates = end_dt - start_dt days_between_dates = time_between_dates.days random_number_of_days = random.randrange(days_between_dates) random_date = start_dt + datetime.timedelta(days=random_number_of_days) print(random_date)
true
0088dd0024d83b49b2ce07683de3a55b9bb53fd5
muradsamadov/python_learning
/other_advanced_concepts/list_set_dict_compherension.py
566
4.15625
4
#List / Set / Dictionary comprehensions #Instead of... list1 = [] for i in range(10): j = i ** 2 list1.append(j) print(list1) #yuxarida qeyd olunmus misalda sade list uzerinde loop yaziriq #...we can use a list comprehension list2 = [x ** 2 for x in range(10)] #bu misalda ise comprehensions-dan istifade ederek daha qisa sekilde yaziriq list3 = [x ** 2 for x in range(10) if x > 5] #with a conditional statament set1 = {x ** 2 for x in range(10)} #set comprehension dict1 = {x: x * 2 for x in range(10)} #dictionary comprehension
false
0c6b8cb7548695d44b7ed9fecea11395a19ee010
mellab/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
255
4.125
4
#!/usr/bin/python3 def uppercase(str): upper = 0 for up in str: if ord(up) >= ord('a') and ord(up) <= ord('z'): upper = 32 else: upper = 0 print("{:c}".format(ord(up) - upper), end='') print("")
false
fdc453807fbadc53426aa1ec020cd68e8253067f
Stefanos1312/Hello-World
/task 1 section 3.py
384
4.25
4
print ("This program will add 2 different numbers and will find the results") #define numbers as integer number1 = int(input("please enter the first number")) number2 = int(input("please enter the second number")) print ("thank you") #now I will define the results by just adding '+' the numbers together result = number1 + number2 print ("the result is") print (result)
true
97bd113620df5f0f1b70d6be454811cfe743f0ce
SakshiBheda/Apni_Dictionary
/apni_dictionary.py
457
4.125
4
print("This is My own Dictionary : 'Apni Dictionary'") print("key ,"" book "", comb "" ,mouse "" , joey ") dic1={"key":"something which unlocks a lock", "book":"a compiled set of pages which describes a certain topic", "comb":"a plastic item to set hairs", "mouse":"an animal which is afraid of cats", "joey":"kid of a kangroo"} print("Please enter the word whose meaning you want") ax=input() print("It means : " ,dic1[ax])
true
993fd1bcd8d453af376f78ad4357e32e3f38800a
DianaLuca/Algorithms
/Leetcode_WeeklyContests/contest_49/ImplementMagicDictionary676.py
1,964
4.125
4
""" Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built. Example 1: Input: buildDict(["hello", "leetcode"]), Output: Null Input: search("hello"), Output: False Input: search("hhllo"), Output: True Input: search("hell"), Output: False Input: search("leetcoded"), Output: False Note: You may assume that all the inputs are consist of lowercase letters a-z. For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest. Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. """ from collections import defaultdict class MagicDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.dictionary = defaultdict(list) def buildDict(self, dict): """ Build a dictionary through a list of words :param dict: List[str] :return: void """ for word in dict: self.dictionary[len(word)].append(word) def search(self, word): """ Returns if there is any word in the trie that equals to the given word after modifying exactly one character :param word: str :return: bool """ if len(self.dictionary[len(word)]) == 0: return False # word is not in dictionary for eachword in self.dictionary[len(word)]: diff = 0 for i in range(len(word)): if eachword[i] != word[i]: diff += 1 if diff == 1: return True return False
true
5efa072bc226c13308ed74407f0e6c86fcd4c72e
DianaLuca/Algorithms
/Leetcode_WeeklyContests/contest_60/AsteroidCollision735.py
1,306
4.1875
4
""" We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Input: asteroids = [5, 10, -5] Output: [5, 10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Note: The length of asteroids will be at most 10000. Each asteroid will be a non-zero integer in the range [-1000, 1000].. """ class Solution(object): res = [] def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ stk = [] for a in asteroids: if a > 0: stk.append(a) else: while stk and (stk[-1] > 0) and (abs(a) > stk[-1]): stk.pop() if not stk or stk[-1] < 0: stk.append(a) elif stk[-1] == abs(a): stk.pop() return stk
true
70b56e0356fa654b58a288e4de9c01e85d5e6d04
narendra-manchala/GFG-DSA
/bitwise algorithms/power_of_2.py
518
4.53125
5
def power_of_2(n): """Find if the number is power of 2 or not. Arguments: n {int} -- The number to find if it is power of 2 or not. Explanation: 1. In binary a power of 2 has only one 1. So doing a bitwise-and with n-1 will give us 0 if it is power of 2. eg: n = 4 (100) n-1 = 3(011) 4&3 => 000 2. For n is 0, explecitly need to return false. """ if n and not n&n-1: print(True) else: print(False)
true
e9e9b78d7898e71dd2a62962bcde4a206bf13d74
rwisecar/scrabble_cheat
/scrabble.py
1,687
4.15625
4
""" This is a simple python script to take a Scrabble rack of 7 letters and return all possible word iterations, with the associated scores.""" import re # Dictionary of letters and values scores = { "a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10 } # Script to open and read the sowpods.txt word file, and strip of extraneous characters sowpods = [] score = 0 def compile_sowpods(): access_sowpods = open("sowpods.txt", "r+") for i in access_sowpods: i = i.strip(' \n\r') sowpods.append(i) access_sowpods.close() # Get the scrabble rack from the user def intro(): user_name = raw_input("Hello there! I see you want to win at Scrabble. I can help. First, tell me your name.") print "Nice to meet you, %s." % user_name def get_rack(): input = raw_input("Now tell me, what 7 letters are we working with here? ").upper() rack = "" if len(input) < 7 or len(input) > 7: print("I'm sorry, you haven't entered a full rack of 7 letters. Please try again.") exit() else: for i in input: if re.match(r'^[A-Z]', i): rack = rack + i else: print("I'm sorry, that is not a valid Scrabble rack. Please try again.") exit() print "Your rack is: %s" % rack def print_options(): compile_sowpods() intro() get_rack() for word in sowpods: for r in rack:
true
3d1d244bef39869f8192536a369f6124ff594960
ciaranmccormick/advent-of-code-2019
/2/main.py
2,303
4.15625
4
#! /bin/env python3 from argparse import ArgumentParser, Namespace from typing import List, Tuple from computer import Computer STOP = 99 ADD = 1 MULTIPLY = 2 def load_instructions(filename: str) -> List[int]: """Read in a list of comma separated integers""" with open(filename, "r") as f: codes = f.readline().split(",") codes = [int(code) for code in codes] return codes def process_opcodes(opcodes: List[int]) -> List[int]: """ Processes the list of opcodes and applies instructions. Returns the modified opcode list. """ i = 0 inputs = list(opcodes) # make a copy of the list while i < len(inputs): opcode = inputs[i] if opcode == STOP: break pos1, pos2, dest = inputs[i + 1 : i + 4] val1 = inputs[pos1] val2 = inputs[pos2] if opcode == ADD: result = val1 + val2 elif opcode == MULTIPLY: result = val1 * val2 inputs[dest] = result i += 4 return inputs def part_two(intcodes: List[int]) -> Tuple[int, int]: """Get solution to Part Two""" for noun in range(1, 100): for verb in range(1, 100): intcodes[1] = noun intcodes[2] = verb comp = Computer(intcodes) processed = comp.run() if processed[0] == 19690720: return noun, verb def part_one(opcodes: List[int]) -> int: """ Get solution to Part One """ opcodes[1] = 12 opcodes[2] = 2 comp = Computer(opcodes) codes = comp.run() return codes[0] def parse_args() -> Namespace: """Parse arguments.""" parser = ArgumentParser() parser.add_argument("filename", help="File containing problem inputs.", type=str) parser.add_argument( "multiplier", help="The number multiply noun and verb by.", type=int ) args = parser.parse_args() return args def main(): args = parse_args() opcodes = load_instructions(args.filename) zero_value = part_one(opcodes) print(f"Part One: answer={zero_value}") noun, verb = part_two(opcodes) part_two_answer = args.multiplier * noun + verb print(f"Part Two: noun={noun}, verb={verb}, answer={part_two_answer}") if __name__ == "__main__": main()
true
47f34d52f596047310cbf2fa23a934181b81ff12
lucasbpaixao/lista_exercicios_python
/ex09.py
323
4.28125
4
#Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. #C = 5 * ((F-32) / 9). fahrenheit = float(input('Informe a temperatura em Fahrenheit: ')) celsius = 5 * ((fahrenheit - 32) / 9) print('A temperatura em celsius é {celsius:.2f}'.format(celsius = celsius))
false
af45aee1ab6efe5194766784c94439a4c201852f
JaimePazLopes/dailyCodingProblem
/problem086.py
1,561
4.21875
4
# Problem #86 # Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make # the string valid (i.e. each open parenthesis is eventually closed). # # For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, since we # must remove all of them. def parentheses_to_remove(sequence): # number of parentheses to remove count = 0 # number of parentheses already open opened = 0 # for each char in the sequence for char in sequence: # if it is opening, add it to the opened count if char == "(": opened += 1 # if it is closing if char == ")": # and there is opened parentheses, close it by removing it of the opened count if opened > 0: opened -= 1 # if there is no open parentheses, add the number of parentheses to remove else: count += 1 # return the number of parentheses to remove + the number of opened parentheses not closed return count + opened assert (parentheses_to_remove("")) == 0 assert (parentheses_to_remove("()")) == 0 assert (parentheses_to_remove("()())()")) == 1 assert (parentheses_to_remove("()()()()")) == 0 assert (parentheses_to_remove(")(")) == 2 assert (parentheses_to_remove("(((")) == 3 assert (parentheses_to_remove(")))")) == 3 assert (parentheses_to_remove(")))")) == 3 assert (parentheses_to_remove("stuff)in)the)middle")) == 3
true
8c12755934693f84fe28b32352fb780bd773d622
JaimePazLopes/dailyCodingProblem
/problem034.py
2,217
4.25
4
# Problem #34 [Medium] # Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible # anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the # lexicographically earliest one (the first one alphabetically). # # For example, given the string "race", you should return "ecarace", since we can add three letters to it # (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" # by adding three letters, but "ecarace" comes first alphabetically. # # As another example, given the string "google", you should return "elgoogle". def create_palindrome(word): # if word is equal to its reverse, return it if word == word[::-1]: return word # if the first and last char are the same, try to make a palindrome with the middle "word" if word[0] == word[-1]: return word[0] + create_palindrome(word[1:-1]) + word[-1] # if they are not the same, make them the same else: # force the first char to be the last char too, try to make a palindrome with the middle "word" by_first = word[0] + create_palindrome(word[1:]) + word[0] # force the last char to be the first too, try to make a palindrome with the middle "word" by_last = word[-1] + create_palindrome(word[:-1]) + word[-1] # return the answer with less chars if len(by_first) > len(by_last): return by_last elif len(by_first) < len(by_last): return by_first # return the answer in alphabetic order if by_first < by_last: return by_first return by_last assert create_palindrome("arara") == "arara" assert create_palindrome("a") == "a" assert create_palindrome("race") == "ecarace" assert create_palindrome("google") == "elgoogle" # it looked easy at first, but after finding my solution i read again the problem, it says "ANYWHERE in the word", # i did for the beggining or ending only. couldnt think on a solution in time and looked for one online, it still a # little weird will try to come back later
true
e8c505c66a0b152fed47d1c24164095d20d591a8
JaimePazLopes/dailyCodingProblem
/problem083.py
866
4.3125
4
# Problem #83 # Invert a binary tree. # # For example, given the following tree: # # a # / \ # b c # / \ / # d e f # # should become: # # a # / \ # c b # \ / \ # f e d class Node: def __init__(self, value): self.value = value self.left = None self.right = None def invert(node): if not node: return # change left with right node.left, node.right = node.right, node.left # do the same with both sides invert(node.left) invert(node.right) f = Node("f") e = Node("e") d = Node("d") c = Node("c") b = Node("b") a = Node("a") a.left = b a.right = c b.left = d b.right = e c.left = f invert(a) assert a.left == c assert a.right == b assert a.left.right == f assert a.right.left == e assert a.right.right == d
false
c43cc3f44200da29beaf525c92f11ade48fbe515
JaimePazLopes/dailyCodingProblem
/problem046.py
1,091
4.15625
4
# Problem #46 [Hard] # Given a string, find the longest palindromic contiguous substring. # If there are more than one with the maximum length, return any one. # # For example, the longest palindromic substring of "aabcdcb" is "bcdcb". # The longest palindromic substring of "bananas" is "anana". def longest_palindromic(word): if word == word[::-1]: return word without_first = longest_palindromic(word[1:]) without_last = longest_palindromic(word[:-1]) if len(without_first) > len(without_last): return without_first return without_last print(longest_palindromic("aabcdcb")) print(longest_palindromic("bananas")) print(longest_palindromic("")) print(longest_palindromic("a")) print(longest_palindromic("abcde")) print(longest_palindromic("abccccde")) print(longest_palindromic("abcdeeee")) # i think i understood something wrong here, they say that is a hard problem, but this is one of the easiest problem # they sent. i finished in 5 minutes, but spent more 10 to be sure i was doing what i was supposed to do
true
3bd671741d9d5a5f079fcaae9b2a900885912df9
JaimePazLopes/dailyCodingProblem
/problem109.py
814
4.125
4
# Problem #109 # # Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th # bit should be swapped, and so on. # # For example, 10101010 should be 01010101. 11100010 should be 11010001. # # Bonus: Can you do this in one line? def swap_bits(x): return (x & 0b10101010) >> 1 | (x & 0b01010101) << 1 assert swap_bits(0b10101010) == 0b01010101 assert swap_bits(0b11100010) == 0b11010001 # i didnt even understand how to represent a unsigned 8-bit int in python, have to google that. i had some multiple # step ideas on how to do the problem, but no clue on how to do it in one line. after some google i found an # explanation on the daily coding problem oficial site https://www.dailycodingproblem.com/blog/neat-bitwise-trick/
true
5915005ff5af0c7f85f45d9e80eac07f5d6d32cf
JaimePazLopes/dailyCodingProblem
/problem033.py
2,805
4.3125
4
# Problem #33 [Easy] # # Compute the running median of a sequence of numbers. That is, given a stream of numbers, # print out the median of the list so far on each new element. # # Recall that the median of an even-numbered list is the average of the two middle numbers. # # For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out: # # 2 # 1.5 # 2 # 3.5 # 2 # 2 # 2 import statistics import heapq sequence = [2, 1, 5, 7, 2, 0, 5] # my first solution, looked online for a python way to do median def running_median(sequence): for index in range(len(sequence)): print(statistics.median(sequence[:index+1])) print() running_median(sequence) # second solution, made my own median function def median(sequence): sort = sorted(sequence) if len(sort) % 2 == 0: return (sort[int(len(sort)/2-1)] + sort[int(len(sort)/2)]) / 2 else: return sort[int((len(sort)-1)/2)] def running_median2(sequence): for index in range(len(sequence)): print(median(sequence[:index+1])) print() running_median2(sequence) # third solution, using min heap and max heap def running_medians3(arr): if not arr: return None smallest_values = list() # max heap of smallest values, multiply everything for -1 to get this effect biggest_values = list() # min heap of biggest values for x in arr: # put it as a big value, so you can take the smallest value later heapq.heappush(biggest_values, x) # if they are no balanced, take one value of biggest to put on smallest if len(biggest_values) > len(smallest_values) + 1: # take the smallest element of the biggest values and add on the max heap of smallest values heapq.heappush(smallest_values, heapq.heappop(biggest_values) * -1) # if both have the same len if len(biggest_values) == len(smallest_values): # add the smallest element on biggest with the biggest element on smallest, divided by 2 print((biggest_values[0] + (smallest_values[0] * -1)) / 2) else: # the middle element is the smallest element on biggest print(biggest_values[0]) running_medians3([2, 1, 5, 7, 2, 0, 5]) # the first 2 solution were easy and quick, but also quite bad. From the beginning i knew that i could do it in linear # time, but to get there was hard, i got the idea of dividing on two parts but couldnt think in a way of keeping the # lists ordered. Online I found heapq again, but it give only the smallest number, looking online for a max heap I # found the * - 1 trick. It was not hard, but i didnt have to data structure know how. took one hour to finish
true
4919f1c45cb054ba3bab2a99ced47bed8105db1d
bryanyaggi/Coursera-Algorithms
/course1/pa1.py
2,533
4.3125
4
#!/usr/bin/env python3 ''' Programming Assignment 1 In this programming assignment you will implement one or more of the integer multiplication algorithms described in lecture. To get the most out of this assignment, your program should restrict itself to multiplying only pairs of single-digit numbers. You can implement the grade-school algorithm if you want, but to get the most out of the assignment you'll want to implement recursive integer multiplication and/or Karatsuba's algorithm. So: what's the product of the following two 64-digit numbers? 3141592653589793238462643383279502884197169399375105820974944592 2718281828459045235360287471352662497757247093699959574966967627 [TIP: before submitting, first test the correctness of your program on some small test cases of your own devising. Then post your best test cases to the discussion forums to help your fellow students!] [Food for thought: the number of digits in each input number is a power of 2. Does this make your life easier? Does it depend on which algorithm you're implementing?] The numeric answer should be typed in the space below. So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks. (We do not require you to submit your code, so feel free to use any programming language you want --- just type the final numeric answer in the following space.) ''' ''' Implements Karatsuba's algorithm recursively. See https://en.wikipedia.org/wiki/Karatsuba_algorithm for details. intX string representation of first integer intY string representation of second integer returns integer result ''' def karatsuba(intX, intY): digsX = len(intX) digsY = len(intY) # Base case if digsX < 2 or digsY < 2: return int(intX) * int(intY) m = 0 if digsX <= digsY: m = digsX // 2 else: m = digsY // 2 x1 = intX[:(len(intX) - m)] x0 = intX[(len(intX) - m):] y1 = intY[:(len(intY) - m)] y0 = intY[(len(intY) - m):] z2 = karatsuba(x1, y1) z0 = karatsuba(x0, y0) z1 = karatsuba(str(int(x1) + int(x0)), str(int(y0) + int(y1))) - z0 - z2 return z2 * 10 ** (2 * m) + z1 * 10 ** m + z0 def testResult(intX, intY): return int(intX) * int(intY) if __name__ == '__main__': intA = '3141592653589793238462643383279502884197169399375105820974944592' intB = '2718281828459045235360287471352662497757247093699959574966967627' print(testResult(intA, intB)) print(karatsuba(intA, intB))
true
88057b2faecda38326d7a00ffa36b0ae4e5761b5
sibimathews3010/S1-python-programs
/large3.py
233
4.1875
4
print("largest of three numbers") X=int(input("enter first no=")) Y=int(input("enter second no=")) Z=int(input("enter third no=")) if(X>Y): if(X>Z): print("X largest;",X) else: print("Z larget;",Z) else: print("Y largest",Y)
false
9bcc693359ef87094813b860f056ebea87c035e4
sibimathews3010/S1-python-programs
/sum.py
306
4.15625
4
num1=input("enter the 1st number") num1=int(num1) num2=input("enter the 2nd number") num2=int(num2) num3=input("enter the 3rd number") num3=int(num3) sum=int(num1)+int(num2)+int(num3) average=sum/3 print("sum=",sum) print("average=",average) 9 9
false
2944a8ea3698fff6e626881e634b69a3f3ca0fc4
sibimathews3010/S1-python-programs
/28.py
311
4.1875
4
def greatest_three_number(a,b,c): if a>b: if a>c: return a else: return c else: if b>c: return b else: return c a=int(input("enter the number1=")) b=int(input("enter the number2=")) c=int(input("enter the number3=")) G=greatest_three_number(a,b,c) print("greatest of three no is",G)
false
c6ea854dc477ae6d5c0b5cbf226f8f71f1cfbb2a
ximuwang/Python_Crash_Course
/Chap9_Classes/Practice/Restaurant.py
1,288
4.125
4
# A module named restaurant class Restaurant(): '''A class representing a restaurant''' def __init__(self, name, cuisine_type): '''Initialize the restaurant''' self.name = name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): '''Display a summary of the restaurant''' print(f"Welcome to {self.name}!") print(f"We have the following cuisine type: {self.cuisine_type}") def open_restaurant(self): '''Display a message indicates that the restaurant is open.''' print("\nWe are open now!") def set_number_served(self, number_served): '''allow user to set the number of customers that have been served''' if self.number_served >= 0: self.number_served = number_served print('We served ' + str(self.number_served) + ' people today.') def increment_number_served(self, add_customers): '''allow user to increment the number of customers served.''' if add_customers >= 0: self.number_served += add_customers print('We now serve ' + str(self.number_served) + ' person') else: print('Please add a positive number.')
true
daa35e217038a987d89248fa3de548c77ac61e5a
Someshwaran/Python-Basics
/employee_dataSaver.py
2,069
4.5
4
from employee import Employee class employee_data_saver: # to store the all employee objects employee_data = [] def __init__(self): self.employee_d = Employee() # this method for read and store the data for a employee def getting_values(self): self.employee_d.set__name(input('Enter the name of the employee ')) self.employee_d.set__id(input('Enter the id ')) self.employee_d.set__salary(input('Enter the salary ')) self.employee_d.set__mailid(input('Enter the mailid ')) # entering the data of the employee to data list employee_data_saver.employee_data.append(self.employee_d) #this method is used for printing the data of the employee from the list def printing_details_of_employee(self): # iterate through the for loop for employee_object in self.employee_data: print() print('Name : ',employee_object.get__name()) print('Id : ',employee_object.get__id()) print('Salary : ',employee_object.get__salary()) print('Mail_ID : ',employee_object.get__mailid()) print() # to remove the details of the employee # def remove_employee_details(self,id): """ we can add the remove and update method up_coming """ #definition of main method def main(): # here we creating the object for the employee_data_saver while True: choice = input('enter the choice for the \n 1: Enter the data for Emplpoyee \n 2: for printing ') employee_data_save_object = employee_data_saver() if choice == '1': #getting values employee_data_save_object.getting_values() elif choice == '2': #printing all values employee_data_save_object.printing_details_of_employee() else: break #def main if __name__ == '__main__': main()
true
2b2854a5ccee8aebd3b674ea50233464aa77b9ea
MayLSantos/Refor-o-na-programa-o-para-ED
/Q4-Carnes.py
1,290
4.15625
4
print("---- Tabela de carnes ----") print("""File Duplo = [1] Alcatra = [2] Picanha = [3]""") print(" ") print("---- Tipo de pagamentos ----") print("""Á vista = [1] Cartão de crédito = [2] Cartão Tabajara = [3] (5% de Desconto)""") print(" ") tipo= int(input("Tipo da carne: ")) quantidade = float(input("Quantidade de carne:[kg] ")) valor = 0 print(" ") if tipo == 1: print("{}Kg de File Duplo".format(quantidade)) if quantidade <= 5: valor= 4.9 * quantidade if quantidade > 5: valor = 5.8 * quantidade elif tipo == 2: print("{}Kg de Alcantra".format(quantidade)) if quantidade <= 5: valor= 5.9 * quantidade if quantidade > 5: valor = 6.8 * quantidade elif tipo == 3: print("{}Kg de Picanha".format(quantidade)) if quantidade <= 5: valor= 6.9 * quantidade if quantidade > 5: valor = 7.8 * quantidade print ("Preço total: R${:.2f}".format(valor)) pagamento = int(input("Tipo de pagamento: ")) if pagamento == 3: desconto= (valor -(valor * 5/100)) print("5% de Desconto") print("Valor a pagar: R${:.2f}".format(desconto)) print(" ") print("Obrigado(a), volte sempre!")
false
82a0e559c5056ad3f4c8f04819c110f92638fc64
AkshaySingh566/task-1
/reversed string.py
201
4.15625
4
def rev(): word = input("Enter a string: ") length = len(word) s = " " for i in reversed(range(length)): s = s + word[i] print("Reversed String is:", s) rev()
false
65c95e58fb3cdaa31db7ab4ec6626378a376c8b0
K-Ellis/airline_seating_assignment
/Rough work folder/kron_sql_test_file.py
2,225
4.15625
4
import sqlite3 #Connect to the database using sqlite2's .connect() method which returns a #connection object conn = sqlite3.connect("airline_seating_test.db") #From the connection we get a cursor object cur = conn.cursor() #create a database with different name, dimensin, col letters def create_db(rows, col_letters): cur.execute("CREATE TABLE metrics(passengers_refused INT, " "passengers_separated INT)") cur.execute("INSERT INTO metrics VALUES(0,0)") cur.execute("CREATE TABLE rows_cols(nrows INT,seats TEXT)") cur.execute("INSERT INTO rows_cols VALUES(?,?)", (rows, col_letters)) cur.execute("CREATE TABLE seating(row INT, seat TEXT, name TEXT)") cur.execute("INSERT INTO seating VALUES(?,?)", (rows, col_letters)) def print_entries(name): # Prints all of the tables if name == "tables": with conn: #Tables names are stored in sqlite_master cur.execute("SELECT name FROM sqlite_master WHERE type='table'") list_of_tables = cur.fetchall() for table1 in list_of_tables: print(table1[0]) #The tables stored in airline_seating.db are: metrics, row_cols and seating #print out the info in metrics elif name == "metrics": with conn: cur.execute("SELECT * FROM metrics") rows = cur.fetchall() for row in rows: print(row) # print out the info in rows_cols elif name == "rows_cols": with conn: cur.execute("SELECT * FROM rows_cols") rows = cur.fetchall() for row in rows: print(row) else: # print out the info in seating with conn: cur.execute("SELECT * FROM seating") rows = cur.fetchall() print(type(rows[0][0])) print(type(rows[0][1])) print(type(rows[0][2])) # for row in rows: # print(row) print(len(rows)) print(rows) print_entries("seating") #60 entries, two seats taken # 1 A Donald Trump and 1 C Hilary Clinton print_entries("rows_cols") # 15*4 # A C D F # 0 1 2 4 print_entries("metrics") print_entries("tables") conn.close()
true
660abd61196b475b705ea4c63e4f5fef0a5b23df
golkedj/Complete_Python_Masterclass
/ProgramFlowChallenge/challenge.py
2,311
4.46875
4
# Create a program that takes an IP address entered at the keyboard # and prints out the number of segments it contains, and the length of each segment. # # An IP address consists of 4 numbers, separated from each other with a full stop. But # your program should just count however many are entered # Examples of the input you may get are: # 127.0.0.1 # .192.168.0.1 # 10.0.123456.255 # 172.16 # 255 # # So your program should work even with invalid IP Addresses. We're just interested in the # number of segments and how long each one is. # # Once you have a working program, here are some more suggestions for invalid input to test: # .123.45.678.91 # 123.4567.8.9. # 123.156.289.10123456 # 10.10t.10.10 # 12.9.34.6.12.90 # '' - that is, press enter without typing anything # # This challenge is intended to practise for loops and if/else statements, so although # you could use other techniques (such as splitting the string up), that's not the # approach we're looking for here. # My solution # ip_address = input("Please enter an IP address: ") # # segments = 0 # length = 0 # for char in ip_address: # if char == '.': # segments += 1 # print("The length of the segment was {} digits".format(length)) # length = 0 # else: # length += 1 # # if segments == 0: # segments = 1 # # print("The length of the segment was {} digits".format(length)) # print("There were {} segments in the IP address".format(segments)) # Instructor solution input_prompt = ("Please enter an IP address. An IP address consists of 4 numbers, " "separated from each other with a full stop: ") ip_address = input(input_prompt) if ip_address[-1] != '.': ip_address += '.' segment = 1 segment_length = 0 # character = '' for character in ip_address: if character == '.': print("segment {} contains {} characters".format(segment, segment_length)) segment += 1 segment_length = 0 else: segment_length += 1 # else: # print("segment {} contains {} characters".format(segment, segment_length)) # unless the final character in the string was a . then we haven't printed the last segment # if character != '.': # print("segment {} contains {} characters".format(segment, segment_length))
true
0dd7705fb79d54f3343b7fe77c4c267e49e58ca5
DKCisco/Starting_Out_W_Python
/2_7.py
592
4.34375
4
""" 7. Miles-per-Gallon A car's miles-per-gallon (MPG) can be calculated with the following formula: MPG 5 Miles driven 4 Gallons of gas used Write a program that asks the user for the number of miles driven and the gallons of gas used. It should calculate the car's MPG and display the result. """ # Receive input miles_driven = float(input('\nEnter number of miles driven: ')) gallons_of_gas_used = float(input('Enter gallons of gas used: ')) # Calculate MPG mpg = miles_driven / gallons_of_gas_used # Output info print('Miles per gallon = ', format(mpg, ',.2f'))
true
264997cbfa001842a434411ed7743781afdc7a93
DKCisco/Starting_Out_W_Python
/3_1PE.py
502
4.3125
4
""" Write a program that asks the user to enter an integer. The program should display “Positive” if the number is greater than 0, “Negative” if the number is less than 0, and “Zero” if the number is equal to 0. The program should then display “Even” if the number is even, and “Odd” if the number is odd. """ # Input variable x from user x = int(input('Enter a number positive or negative: ')) # Process if x > 0: print('Positive') else: print('Negative')
true
d0e5ab73ec31f809d5db4c820fb91835abe86424
DKCisco/Starting_Out_W_Python
/average_rainfall.py
1,324
4.4375
4
""" 5. Average Rainfall Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period. """ # Get number of years from the user years_total = int(input('Enter the number of years to track: ')) # Assign the number of months in a year months = 12 # Accumulator total = 0.0 for years_rain in range(years_total): print('\nYear Number', years_rain + 1 ) print('------------------------------') for month in range(months): print('How many inches for month ', month + 1, end='') rain = int(input(' Enter rain amount: ')) total += rain number_months = years_total * months average = total / number_months print('The total inches of rain was ', format(total,'.2f')) print('The number of months measured was', number_months) print('The average rainfall was', format(average, '.2f'), 'inches')
true
e0f5e232bfc86a8b66c68aa464ecf980c02c6740
DKCisco/Starting_Out_W_Python
/test_average.py
728
4.25
4
""" This program calculates the average of 3 test scores using decision structure. """ # Assign varibale to score above 95% average. HIGH_AVERAGE = 95 # Get the test scores from user. test1 = int(input('Enter the score for test 1: ' )) test2 = int(input('Enter the score for test 2: ' )) test3 = int(input('Enter the score for test 3: ' )) # Calculate the average test score average = (test1 + test2 + test3) / 3 # Print the average. print("The average score is: %s %%\n" % average) # Congratulate the user based on if the score is above or equal to 95. if average >= HIGH_AVERAGE: print('Congratulations on scoring 95% or better, Einstein would be proud') print('That is a great average!')
true
f659140d86797009dce119565357affb2c41a62f
zhaobf1990/MyPhpDemo
/first/com/zhaobf/test6.py
1,105
4.3125
4
# Python3 函数 # def add(a, b): # return a + b # # # def aera(a, b): # return a * b # # # print(add(1, 2)) # # print(add("1", "3")) # # print( aera("a",8)) # 标题:按值传递参数和按引用传递参数 # 在 Python 中,所有参数(变量)都是按引用传递。如果你在函数里修改了参数,那么在调用这个函数的函数里,原始的参数也被改变了。例如: def changeme(data): "修改传入的列表" data.append([1, 2, 3, 4]); print("函数内取值: ", data) return data # 调用changeme函数 mylist = [10, 20, 30]; c = changeme(mylist); print (c) print ("函数外取值: ", mylist) # # 可写函数说明 # def printinfo(arg1, *vartuple): # "打印任何传入的参数" # print("输出arg1: ", arg1) # # for var in vartuple: # print("vartuple", var) # return; # # # # 调用printinfo 函数 # # printinfo(10); # printinfo(70, 60, 50); # sum1=lambda arg1,arg2:arg1+arg2; # # print("相加后的值为:",sum1(10,20)) # sum() def add(a): a = 2 return a b = 1 c = add(b) print(c) print(b)
false
1b304e5f6ae0a2c208377a15b31189ae990c09e1
fizzywonda/CodingInterview
/Recursion&Dynamic Program/RecursiveMultiply.py
1,549
4.5
4
""" Recursive Multiply: Write a recursive function to multiply two positive integers without using the *operator.You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations. """ """Brute force Approach""" def multiply(x, y): if y == 0: return 0 result = x + multiply(x, y - 1) return result """improved approach""" def multiply2(x, y): # get the bigger number small = x if x < y else y big = y if y > x else x return multiply_helper(small, big) def multiply_helper(small, big): if small == 0: return 0 if small == 1: return big # divide small by 2 s = small >> 1 side1 = multiply2(s, big) side2 = side1 if small % 2 == 1: side2 = (side1 << 1) + big return side1 + side2 return side1 + side2 """ optimized Approach (memoized)""" def multiply3(x, y): small = x if x < y else y big = y if y > x else x memo = [None for i in range(small + 1)] return multiply_helper2(small, big, memo) def multiply_helper2(small, big, memo): if small == 0: return 0 if small == 1: return big if memo[small] is not None: return memo[small] s = small >> 1 side1 = multiply3(s, big) side2 = side1 if small % 2 == 1: side2 = (side1 << 1) + big memo[small] = side1 + side2 memo[small] = side1 + side2 return memo[small] if __name__ == '__main__': x = 2 y = 3 result = multiply3(x, y) print(result)
true
26e3c6573df720de85538db9c86d0f24d469b13a
fizzywonda/CodingInterview
/Recursion&Dynamic Program/RobotInGrid.py
1,727
4.46875
4
""" Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right. """ def find_path1(maze): path = [] if find_path(maze, 0, 0, path): return path return None def find_path(maze, row, col, path): if row > len(maze) - 1 or col > len(maze[0]) - 1 or not maze[row][col]: return False end = row == len(maze) - 1 and col == len(maze[0]) -1 if end or find_path(maze, row + 1, col, path) or find_path(maze, row, col + 1, path): p = [row, col] path.append(p) return True return False """ Dynamic programming approach """ def find_path_2(maze): path = [] visited_point = set() if find_path2(maze, 0, 0, path, visited_point): return path return None def find_path2(maze, row, col, path, visited_point): if row > len(maze) - 1 or col > len(maze[0]) - 1 or not maze[row][col]: return False p = (row, col) if p in visited_point: return False end = row == len(maze) - 1 and col == len(maze[0]) -1 if end or find_path2(maze, row + 1, col, path, visited_point) or find_path2(maze, row, col + 1, path, visited_point): path.append(p) return True visited_point.add(p) return False if __name__ == '__main__': maze = [] maze.append(["s", False, False]) maze.append([True, False, False]) maze.append([True, True, False]) maze.append([False, True, "e"]) path = find_path1(maze) print(path)
true