blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
45f5407c770e494c7d9be2fbcbf1802e56c74e21
rohan-krishna/dsapractice
/arrays/array_rotate.py
533
4.125
4
# for the sake of simplicity, we'll use python list # this is also known as Left Shifting of Arrays def rotateArray(arr, d): # arr = the input array # d = number of rotations shift_elements = arr[0:d] arr[:d] = [] arr.extend(shift_elements) return arr if __name__ == "__main__": print("How many time do you want to shift the array: ") n = int(input()) print("Enter Array (e.g: 1 2 3 == [1,2,3]): ") arr = list(map(int, input().rstrip().split())) res = rotateArray(arr, n) print(res)
true
b6587aace2006e8cca1e4e546b3bc4bb716fcfa0
federicodiazgerstner/sd_excercises_uade
/Ejercicio 4.07.py
542
4.21875
4
#Realizar un programa para ingresar desde el teclado un conjunto de números y #mostrar por pantalla el menor y el mayor de ellos. Finalizar la lectura de datos #con un valor -1. n = int(input("Insertar un número, o -1 para terminar: ")) menor = n mayor = n while n != -1: if n > mayor: mayor = n elif n < menor: menor = n n = int(input("Inserte un número, o -1 para terminar: ")) if menor == -1 and mayor == -1: print ("No se ingresaron valores") else: print("El menor es", menor," y el mayor", mayor)
false
11d53956ee5844db459788f17b93d07b8594243d
bhargav-s-271100/Python-Programs
/Calculator using OOPS concept.py
1,081
4.1875
4
class calculator: def __init__(self,a,b): self.c=a self.d=b def add(self): return self.c+self.d def subtract(self): if self.c>self.d: self.c-self.d else: return self.c-self.d def multiply(self): return self.c*self.d def int_divide(self): return self.c//self.d def float_divide(self): return self.c/self.d def power(self): return self.c**self.d print("Enter $ to exit from the calculator:") a = input("enter the operation to be performed : ") while a!='$': b = a.split(sep=" ") d=b[0] c = b[1] o = calculator(int(d),int(b[2])) if c=='+': print (o.add()) elif c=='-': print(o.subtract()) elif c=='*': print(o.multiply()) elif c=='/': print(o.float_divide()) elif c=='//': print(o.int_divide()) elif c=='**': print(o.power()) print("Enter $ to exit from the calculator:") a = input("enter the operation to be performed : ")
false
bba98a339cc3fe159b5db7a6979f37a1e6467eee
shridharkute/sk_learn_practice
/recursion.py
668
4.375
4
#!/usr/bin/python3 ''' This is recursion example. recursion is method to call itself while running. Below is the example which will create addition till we get 1. Eg. If we below funcation as "tri_resolution(6)" the result will be Rcursion example result 1 1 2 3 3 6 4 10 5 15 6 21 But in the background it will execute below code. >>> 6 + 5 + 4 + 3 + 2 + 1 21 >>> 5 + 4 + 3 + 2 + 1 15 >>> 4 + 3 + 2 + 1 10 >>> 3 + 2 + 1 6 >>> 2 + 1 3 >>> 1 1 >>> ''' def tri_resolution(k): if (k>0): result = k+tri_resolution(k-1) print(k, result) else: result = 0 return result print("\n\nRcursion example result") tri_resolution(6)
true
521b61d372e351a005221c1919dc4bacf070fe51
shridharkute/sk_learn_practice
/if_else.py
432
4.15625
4
#/usr/bin/python3 a = int(input("Please type number :")) b = int(input("Please type number :")) if a < b: print("%d is smaller than %d" % (a,b)) elif a < b: print("%d is grater than %d" % (a,b)) else: print("%d is equal to %d" %(a,b)) if a < b or a == b: print("%d is smaller or equal to %d" %(a,b)) elif b < a or a == b: print("%d is smaller or equal to %d " %(b,a)) else: print("unknwon %d %d" %(a ,b))
false
600409d5897e5a6a2a8fa5900a8ca197abf294f7
DAVIDCRUZ0202/cs-module-project-recursive-sorting
/src/searching/searching.py
798
4.34375
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): if len(arr) == 0: return -1 low = start high = end middle = (low+high)//2 if arr[middle] == target: return middle if arr[middle] > target: return binary_search(arr, target, low, middle-1) if arr[middle] < target: return binary_search(arr, target, middle+1, high) return -1 # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively # def agnostic_binary_search(arr, target): # Your code here
true
1e4ecc5c66f4f79c0f912313acd769edb3a92008
harshal-jain/Python_Core
/22-Lists.py
1,980
4.375
4
list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] """ print ("list1[0]: ", list1[0]) #Offsets start at zero print ("list2[1:5]: ", list2[1:5]) #Slicing fetches sections print ("list1[-2]: ", list1[-2]) #Negative: count from the right print ("Value available at index 2 : ", list1[2]) list1[2] = 2001 print ("New value available at index 2 : ", list1[2]) del list1[2] print ("After deleting value at index 2 : ", list1) print(list1+list2) print(list1*3) print(2000 in list1) for x in [1,2,3] : print (x,end = ' ') #Gives the total length of the list. print (len(list1)) #Returns item from the list with max value. all data type should be same to calculate max print (max(list2)) #Returns item from the list with min value. all data type should be same to calculate max print (min(list2)) #The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list. aTuple = (123, 'C++', 'Java', 'Python') list3 = list(aTuple) print ("List elements : ", list3) str = "Hello World" list4 = list(str) print ("List elements : ", list4) """ #Python includes the following list methods − #Appends object obj to list list1.append('C#') print(list1) #Returns count of how many times obj occurs in list a=list1.count('C#') print(a) #Appends the contents of seq to list list1.extend(list2) print(list1) #Returns the lowest index in list that obj appears print(list1.index('C#')) #Inserts object obj into list at offset index list1.insert(2, 'ASP') print(list1) #Removes and returns last object or obj from list obj=list1.pop() print(obj) print(list1) #Removes and returns last object or obj from list obj=list1.pop(3) print(obj) print(list1) #Removes object obj from list list1.remove('C#') print(list1) #Reverses objects of list in place list1.reverse() print(list1) #Sorts objects of list, use compare func if given '''list1.sort() print(list1) list1.sort(reverse=True) print(list1) '''
true
71356cbfce0df685f7b02f7b719289bd3b395b21
Sarayin/Ejercicios-de-trabajo
/ejercicio 12.py
559
4.125
4
'''Escribir una función que, dado un string, retorne la longitud de la última palabra. Se considera que las palabras están separadas por uno o más espacios. También podría haber espacios al principio o al final del string pasado por parámetro.''' def lenramiro(frase): if len(frase)==0: return 0 cantidad=0 for i in range(len(frase)): if frase[i]!=' ': cantidad+=1 else: if i<len(frase)-1 and frase[i+1]!=' ': cantidad=0 return cantidad print(len("ramiro"))
false
b253f828fc56c2f9e7148e13ae2a910c542f1249
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 05/ProgrammingExercises/03_budget_analysis.py
1,540
4.40625
4
# Write a program that asks the user to enter the amount that they have # budgeted for a month. A loop should then prompt the user to enter each of # their expenses for the month, and keep a running total. When the loop # finishes, the program should display the amount that the user is over # or under budget. def budget(): # Get the budget's limit. m_limit = float(input('Enter amount budgeted for the month: ')) # Initialize accumulator variable. total_expenses = 0.0 # Variable to control the loop. another = 'y' # Get each expense and accumulate them. while another == 'y' or another == 'Y': # Get expense and tack it to the accumulator. expense = float(input('Enter expense: ')) # Validate expense. while expense < 0: print('ERROR: You can\'t enter a negative amount.') expense = float(input('Enter correct expense: ')) total_expenses += expense # Do it again? another = input('Do you have another expense? ' + \ '(Enter y for yes): ') # Determine over/under budget's amount. if m_limit > total_expenses: under = m_limit - total_expenses print('You are $', format(under, ',.2f'), ' under budget!', sep='') elif m_limit < total_expenses: over = total_expenses - m_limit print('You are $', format(over, ',.2f'), ' over budget...', sep='') else: print('Impressively, you are exactly on budget.') # Call budget function. budget()
true
88cfb1d6b2746e689d6a661caa34e5545f044670
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 04/ProgrammingExercises/09_shipping_charges.py
1,098
4.4375
4
# The Fast Freight Shipping Company charges the following rates: # # Weight of Package Rate per Pound # 2 pounds or less $1.10 # Over 2 pounds but not more than 6 pounds $2.20 # Over 6 pounds but not more than 10 pounds $3.70 # Over 10 pounds $3.80 # # Write a program that asks the user to enter the weight of a package and # then displays the shipping charges. def main(): # Prompt weight = float(input('Enter weight of package: ')) # Decide + Calculate if weight <= 2: rate = weight * 1.10 print('Shipping charges: $', format(rate, ',.2f'), sep='') elif weight > 2 and weight <= 6: rate = weight * 2.20 print('Shipping charges: $', format(rate, ',.2f'), sep='') elif weight > 6 and weight <= 10: rate = weight * 3.70 print('Shipping charges: $', format(rate, ',.2f'), sep='') else: rate = weight * 3.80 print('Shipping charges: $', format(rate, ',.2f'), sep='') main()
true
4d24d83ec69531dd864ef55ed900a6d154589fd8
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 03/ProgrammingExercise/04_automobile_costs.py
1,248
4.34375
4
# Write a program that asks the user to enter the monthly costs for the # following expenses incurred from operating his or her automobile: loan # payment, insurance, gas, oil, tires, and maintenance. The program should # then display the total monthly cost of these expenses, and the total # annual cost of these expenses. def main(): # Get input lp = float(input('Enter monthly loan payment cost: ')) ins = float(input('Enter monthly insurance cost: ')) gas = float(input('Enter monthly gas cost: ')) oil = float(input('Enter monthly oil cost: ')) tire = float(input('Enter monthly tire cost: ')) maint = float(input('Enter monthly maintenance cost: ')) # Calculate monthly cost monthly(lp, ins, gas, oil, tire, maint) # Calculate annual cost annually(lp, ins, gas, oil, tire, maint) def monthly(lp, ins, gas, oil, tire, maint): cost_monthly = lp + ins + gas + oil + tire + maint print('The monthly amount of expenses is $', \ format(cost_monthly, ',.2f'), sep='') def annually(lp, ins, gas, oil, tire, maint): cost_annually = (lp + ins + gas + oil + tire + maint) * 12 print('The annual amount of expenses is $', \ format(cost_annually, ',.2f'), sep='') main()
true
36e179b5db4afaf4b7bc2b6a51f0a81735ac2002
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 06/ProgrammingExercises/01_feet_to_inches.py
521
4.40625
4
# One foot equals 12 inches. Write a function named feet_to_inches that # accepts a number of feet as an argument, and returns the number of inches # in that many feet. Use the function in a program that prompts the user # to enter a number of feet and then displays the number of inches in that # many feet. def main(): feet = int(input('Enter a number of feet: ')) inches = feet_to_inches(feet) print('There are', inches, 'inches in', feet, 'feet.') def feet_to_inches(feet): return feet * 12 main()
true
a8bf3cc39005180b6d3b2d18a751c43f3665ec23
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 07/ProgrammingExercises/09_exception_handling.py
348
4.125
4
# Modify the program that you wrote for Exercise 6 so it handles the following # exceptions: # • It should handle any IOError exceptions that are raised when the file is # opened and data is read from it. # • It should handle any ValueError exceptions that are raised when the items # that are read from the file are converted to a number.
true
3d4cba89be0858b757da7c59a4845ab4360d28d3
cosmos512/PyDevoir
/StartingOutWithPy/Chapter 06/ProgrammingExercises/05_kinetic_energy.py
1,110
4.40625
4
# In physics, an object that is in motion is said to have kinetic energy (KE). # The following formula can be used to determine a moving object’s kinetic # energy: # # KE = (1/2) * m * v^2 # # The variables in the formula are as follows: KE is the kinetic energy in # joules, m is the object’s mass in kilograms, and v is the object’s velocity # in meters per second. # Write a function named kinetic_energy that accepts an object’s mass in # kilograms and velocity in meters per second as arguments. The function # should return the amount of kinetic energy that the object has. Write a # program that asks the user to enter values for mass and velocity, and then # calls the kinetic_energy function to get the object’s kinetic energy. def main(): mass = float(input('Enter the object\'s mass in kilograms: ')) velocity = float(input('Enter the object\'s velocity in meters: ')) KE = kinetic_energy(mass, velocity) print('The object\'s kinetic energy is', KE, 'joules.') def kinetic_energy(m, v): return (1/2) * m * v**2 # Call the main function. main()
true
8cccedbab97b4439c53bbec5f443011066947897
kescalante01/learning-python
/Address.py
867
4.28125
4
#Use raw_input() to allow a user to type an address #If that address contains a quadrant (NW, NE, SE, SW), then add it to that quadrant's list. #Allow user to enter 3 addresses; after three, print the length and contents of each list. ne_adds = [] nw_adds = [] se_adds = [] sw_adds = [] address1 = raw_input("Whats your address?") address2 = raw_input("Whats your work address?") address3 = raw_input("Whats your address of your favorite bar?") address1 = address.upper() address2 = address.upper() address3 = address.upper() address_as_a_list1 = address1.split(' ') print address_as_a_list1 address_as_a_list2 = address2.split(' ') print address_as_a_list2 address_as_a_list3 = address3.split(' ') print address_as_a_list3 all_addresses_as_list = address_as_a_list1 + address_as_a_list2 + address_as_a_list3 if NW in all_addresses_as_list: nw_adds.append()
true
15e748a72d65e156856ef84264c8700e9e7e3c83
uciharis/Udemy-dletorey
/Python Programming Masterclass/Python/Squences/joining_things.py
228
4.125
4
flowers = [ "Daffodil", "Crocus", "Iris", "Tulip", "Rose", "Lily", ] # for flower in flowers: # print(flower) separator = " | " output = separator.join(flowers) print(output) print(",".join(flowers))
false
6d72e4e2ce4447de1dfee99def28204c089f7faf
riteshsingh1/learn-python
/string_function.py
406
4.34375
4
string="Why This Kolaveri DI" # 1 # len(string) # This function returns length of string print(len(string)) # 2 # In Python Every String is Array string = "Hello There" print(string[6]) # 3 # index() # Returns index of specific character / Word - First Occurance string="Python is better than PHP." print(string.index("PHP")) # 4 # replace string = "PHP is best" print(string.replace("PHP", "Python"))
true
6b8442b9cd22aa2eeb37966d42ca6511f3ba6c17
antoninabondarchuk/algorithms_and_data_structures
/sorting/merge_sort.py
797
4.125
4
def merge_sort(array): if len(array) < 2: return array sorted_array = [] middle = int(len(array) / 2) left = merge_sort(array[:middle]) right = merge_sort(array[middle:]) left_i = 0 right_i = 0 while left_i < len(left) and right_i < len(right): if left[left_i] > right[right_i]: sorted_array.append(right[right_i]) right_i += 1 else: sorted_array.append(left[left_i]) left_i += 1 sorted_array.extend(left[left_i:]) sorted_array.extend(right[right_i:]) return sorted_array if __name__ == '__main__': sorted1 = merge_sort([1, 7, 5, 3, 4, 2, 0]) sorted2 = merge_sort([]) sorted3 = merge_sort('') sorted4 = merge_sort([9, 8, 7, 6, 5, 4, 3, 2, 1]) print(sorted1)
true
12ee12d7d101ed158bae6079f14e8a6360c424f6
elicecheng/Python-Practice-Code
/Exercise1.py
359
4.15625
4
#Exercise 1 #Asks the user to enter their name and age. #Print out a message addressed to them that #tells them the year that they will turn 100 years old. import datetime name = input("What is your name?") age = int(input("How old are you?")) now = datetime.datetime.now() year = (now.year - age) + 100 print(name, "will be 100 years old in year", year)
true
cb04890ea51898c5c225686f982e77da4dc71535
playwithbear/Casino-Games
/Roulette Basic.py
1,488
4.28125
4
# Basic Roulette Mechanics # # Key attributes: # 1. Provide a player with a balance # 2. Take a player bet # 3. 'Spin' Roulette wheel # 4. Return result to player and update balance if necessary with winnings # # NB. This roulette generator only assumes a bet on one of the evens i.e. red of black to test a gambling strategy # Import modules import random # Initialise game balance = 1000 playing = "y" print("Welcome to The Oversimplified Roulette Machine.") print("This game will assume you always bet on evens.") print("Your current balance is: " + str(balance)) # Game loop while playing == "y": # Take bet bet = int(input("\nHow much would you like to bet? ")) balance -= bet # Spin wheel result = random.randrange(36) print("The result is: " + str(result)) # Assess winning if result == 0: # i.e. no winning or losing balance += bet print("\nZero. Player stands.") elif result % 2 == 0: # Result is even balance += (bet*2) print("\nCongratulations, you win " + str(bet*2)) else: # You lose print("\nSorry, you lose.") # Inform player of their current balance print("\nYour current balance is: " + str(balance)) # Invite to play again playing = str.lower(input("\nWould you like to play again? Y/N: ")) input("\nThank you for playing The Oversimplified Roulette Machine. \nPress any key to exit.")
true
c413add161722e8efad1b4319463ede4f5a3aff8
ramsundaravel/PythonBeyondBasics
/999_Misc/004_generators.py
1,140
4.375
4
# Generators - # Regular function returns all the values at a time and goes off # but generator provides one value at a time and waits for next value to get off. function will remain live # it basically yields or stops for next call # basically not returning all values together. returning one value at a time def generator_example(num): for i in range(1,num): print('Loop started for {}'.format(i)) yield i print('Loop end for {}'.format(i)) test = generator_example(10) # print('1*********') # print(next(test),'\n') # print('2*********') # print(next(test),'\n') # print('3*********') # print( next(test),'\n') # print('*********') # alternative way of call for x in test: print(x) print('\n') #****************************************# print('Square example using generators') def square(num): for i in num: yield i * i sq = square([1,2,3,4,5,6]) # sq is a generator object pointing to the function square # now call sq till end of iteration using for loop or through next method method # advantage memory saving and performance for i in sq: print (i) # it yields one value
true
d70c7e14cb9974a1320850eb1e70fa2fb1e14dd7
AhmedElatreby/python_basic
/while_loop.py
2,392
4.4375
4
""" # While Loop A while loop allows code to be repeated an unknown number of times as long as a condition is being met. ======================================================================================================= # For Loop A for loop allows code to be repeated known number of loops/ iterations """ # import random # i = 1 # while i < 6: # print("True") # i += 1 """ craete a programme to ask the user to guess a number between 1 - 10 and count the number of attemeted """ # count = 0 # num = 0 # rand = str(random.randint(1, 10)) # while num != rand: # num = input("Enter a number between 1-10: ") # count += 1 # print(rand) # print(f"Guess count {count}") # print("Correct!") """ create a programe to genarate a random numbers and to stop the programe once number 5 found """ # num1 = 1 # while num1 > 0: # print(num1) # num1 = random.randint(1, 10) # if num1 == 5: # break # print("5 was found") # # Write a while loop that adds all the numbers from 1 to 100 # i = 1 # while i <= 100: # print(i) # i += 1 """ Take the following list: numbers=[10, 99, 98, 85, 45, 59, 65, 66, 76, 12, 35, 13, 100, 80, 95] Using a while loop iterate through the list and for every instance of 100 print out "Found one!" """ # numbers = [10, 99, 100, 98, 85, 45, 59, 65, # 100, 66, 76, 12, 100, 35, 13, 100, 80, 95] # length = len(numbers) # i = 0 # while i < length: # if numbers[i] == 100: # print("Found one!") # i += 1 """ Using the following list of names: names=["Joe", "Sarah"] Using a while loop allow users to add new names to the list indefinitely. Each time a user adds a new name ask the user if they would like to add another name. 1 = yes and 2 = no. The programme should stop if the users selects 2, no. """ # names = ["Joe", "Sarah"] # while True: # names.append(input("Enter name: ")) # print(names) # x = int(input("1-add more, 2-exit: ")) # if x == 2: # break """ Create a dice roll simulator whereby the user is first given an option on screen to either play or exit the simulator. An input() function is used to capture the users choice. """ import random while True: print("1. Roll dice, \n2. Exit game") user = int(input("Choice 1 or 2: ")) if user == 1: number = random.randint(1, 6) print(number) else: break
true
4280063ba51d897bdb1049d6a1a84c6625ed0a39
igor-kurchatov/python-tasks
/Warmup1/pos_neg/pos_neg_run.py
355
4.1875
4
################################# # Task 8 - implementation # Desription: Given 2 int values, return True if one is negative and one is positive. # Except if the parameter "negative" is True, then return True only if both are negative. # Author : Igor Kurchatov 5/12/2016 ################################# from pos_neg import pos_neg_run pos_neg_run()
true
0fe469e04d72b5e225fdc4279f6f4c9542031644
AmeyMankar/PracticePython
/Exercise2.py
462
4.28125
4
# Let us find the sum of several numbers (more than two). It will be useful to do this in a loop. #http://www.codeabbey.com/index/task_view/sum-in-loop user_input = [] sum_of_numbers = 0 choice=1 while choice != 2: user_input.append(int(input("Please enter your number: \t"))) choice = int(input("Do you want to add more numbers: 1) Yes 2) No: \t")) for item in user_input: sum_of_numbers += item print("Total sum of numbers is:\t"+str(sum_of_numbers))
true
edbc80e91c8a9ad244bee62bcfe3809a3dce876a
ethanpierce/DrZhao
/LinkedList/unitTestLinkedList.py
644
4.15625
4
from linkedlist import LinkedList def main(): #Create list of names listOfNames = { "Tom", "Harry","Susan","Ethan","Willy","Shaina"} #Create linkedlist object testinglist = LinkedList() #Test insertion method for name in listOfNames: testinglist.insert(name) #Test size of list print testinglist.size() #Test print list testinglist.printList() #Test Deletion of head node testinglist.delete("Tom") #Test Deletion method: testinglist.delete("Susan") testinglist.printList() #Test search list testinglist.search("Willy") if __name__ == '__main__': main()
true
97fc123c1a6beb45aa2893c0c4a8d21bfc41b174
dvcolin/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
2,387
4.1875
4
class Node: def __init__(self, value=None, next_node=None): # the value at this linked list node self.value = value # reference to the next node in the list self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): # set this node's next_node reference to the passed in node self.next_node = new_next class LinkedList: def __init__(self): # reference to the head of the list self.head = None def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False # get a reference to the node we're currently at; update this as we traverse the list current = self.head # check to see if we're at a valid node while current: # return True if the current value we're looking at matches our target value if current.get_value() == value: return True # update our current node to the current node's next node current = current.get_next() # if we've gotten here, then the target node isn't in our list return False def reverse_list(self): def reverse_list_inner(node): # If list is empty, return None if not self.head: return None # If a next node exists, add current node value to head and call function on next node elif node.next_node != None: self.add_to_head(node.value) return reverse_list_inner(node.next_node) # When there is no next node, we are at the tail. Add tail to head self.add_to_head(node.value) reverse_list_inner(self.head) # ex = LinkedList() # ex.add_to_head(4) # ex.add_to_head(9) # ex.add_to_head(2) # ex.add_to_head(0) # print(ex.head.value) # print(ex.head.get_next().value) # print(ex.head.get_next().get_next().value) # print(ex.head.get_next().get_next().get_next().value) # ex.reverse_list() # print(ex.head.value) # print(ex.head.get_next().value) # print(ex.head.get_next().get_next().value) # print(ex.head.get_next().get_next().get_next().value)
true
1041fe53fa1dbc0a91f0602f20530a4608656069
tadeograch/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
483
4.3125
4
#!/usr/bin/python3 """ 0. Integers addition A function that adds 2 integers add_integer(a, b) """ def add_integer(a, b=98): """ Function that add two integers """ if not type(a) is int and not type(a) is float: raise TypeError("a must be an integer") if not type(b) is int and not type(b) is float: raise TypeError("b must be an integer") if type(a) is float: a = int(a) if type(b) is float: b = int(b) return a + b
true
0725747b9015941bac5f87ff3c5a9372ab9fd5cc
uoshvis/py-data-structures-and-algorithms
/sorting_and_selection/selection.py
1,527
4.15625
4
# An example of prune-and-search design pattern import random def binary_search(data, target, low, high): """Return True if target is found in indicated portion of a Python list. The search only considers the portion from data[low] to data[high] inclusive. """ if low > high: return False # interval is empty; no match else: mid = (low + high) // 2 if target == data[mid]: # found a matcha return True elif target < data[mid]: # recur on the portion left of the middle return binary_search(data, target, low, mid - 1) else: # recur on the portion right of the middle return binary_search(data, target, mid + 1, high) # randomized quick-select algorithm # runs in O(n) expected time, O(n^2) time in the worst case def quick_select(S, k): """Return the kth smallest element of list S, for k from 1 to len(S).""" if len(S) == 1: return S[0] pivot = random.choice(S) # pick random pivot element from S L = [x for x in S if x < pivot] E = [x for x in S if x == pivot] G = [x for x in S if pivot < x] if k <= len(L): return quick_select(L, k) # kth smallest lies in L elif k <= len(L) + len(E): return pivot # kth smallest equal to pivot else: j = k - len(L) - len(E) # new selection parameter return quick_select(G, j) # kth smallest is jth in G
true
ac1dbc3d5be3fcf1cb6ec271833e8a19af1f6af6
abmport/Python
/1Semestre/inverter_numero.py
265
4.15625
4
num = int(input("Escolha um número de três dígitos para o invertermos: ")) print("O número escolhido é: ",num) p1=num%10 p2=num//10 p2=p2*11 p2=p2%10 p3=p1+p2*10 p3=num-p3 p3=p3//100 print("O número invertido é: ",p1,p2,p3) input ()
false
0ae6074efd9a9b393439a72b9f596d4baf09f7c8
v13aer14ls/exercism
/salao_de_beleza.py
1,538
4.21875
4
#!/bin/python2/env #Guilherme Amaral #Mais um exercicio daqueles hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"] prices = [30, 25, 40, 20, 20, 35, 50, 35] last_week = [2, 3, 5, 8, 4, 4, 6, 2, 1] #1. Create a variable total_price, and set it to 0. total_price = 0 #2. Iterate through the prices list and add each price to the variable total_price. for price in prices: total_price += price print(total_price) # 3. create a variable called average_price that is the total_price divided by the number of haircuts. average_price = total_price/len(hairstyles) #4. prtint average price string print("Average Price: " + str(average_price)) #5. Create list comprehension to make a list titled new_prices, with each element subtracted by 5 new_prices = [price - 5 for price in prices] #6. Print new prices print(new_prices) #7. create new variable called total_revenue and set it equal to 0 total_revenue = 0 #8. create a loop that goes from 0 to len(hairstyles)-1 for i in range(len(hairstyles)-1): print(i) #9 Add the product of prices[i] (the price of the haircut at position i) and last_week[i] for i in range(0, len(hairstyles)-1): total_revenue += prices[i] * last_week[i] #print total revenue print(total_revenue) #find average daily revenue average_daily_revenue = total_revenue/7 print(average_daily_revenue) #12. create comprehension list for haircuts less than 30 cuts_under_30 = list(zip(hairstyles,[price for price in new_prices if price < 30])) print(list(cuts_under_30))
true
ff01b081c831b0593ebb3722ee47ca04b2406991
Praneeth313/Python
/Loops.py
1,363
4.25
4
# -*- coding: utf-8 -*- """ Created on Thu May 6 23:02:40 2021 @author: Lenovo Assignment 5: Basic Loop Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". """ ''' Created a list using range function with elemnts as numbers from 1 to 100 ''' Numbers = list(range(1,101)) ''' Created a for loop with nested if statements ''' for i in Numbers: if i%3 == 0: ''' if the number is the divisible by 3 then replace the number with 'Fizz' by subracting the number with 1 and using it as index ''' Numbers[i-1] = "Fizz" if i%5 == 0: ''' if the number is the divisible by 5 then replace the number with 'Buzz' by subracting the number with 1 and using it as index ''' Numbers[i-1] = "Buzz" if i%3 == 0 and i%5 == 0: ''' if the number is the divisible by 3 and 5 then replace the number with 'FizzBuzz' by subracting the number with 1 and using it as index ''' Numbers[i-1] = "FizzBuzz" ''' Use a for loop to go through all the elements of the List and print them ''' for n in Numbers: print(n)
true
9018be0092cebcda903279b87fcdb9e78a8c79fb
akshat12000/Python-Run-And-Learn-Series
/Codes/98) list_comprehension_in_nested_list.py
389
4.53125
5
# List comprehension in nested list # We want the list --> [[1,2,3], [1,2,3], [1,2,3]] # Method 1)--> without list comprehension l=[] for i in range(3): p=[] for j in range(1,4): p.append(j) l.append(p) print(l) # Method 2)--> with list comprehension l1=[[i for i in range(1,4)] for _ in range(3)] # Note: Here we have used '_' in for loop !! print(l1)
true
8f9ef1a6b1b42b511331646021caa6a7e9b298eb
akshat12000/Python-Run-And-Learn-Series
/Codes/104) args_as_argument.py
296
4.28125
4
def multiply(*args): mul=1 print(f"Elements in args are {args}") for i in args: mul*=i return mul l=[1,2,3] t=(1,2,3) print(multiply(l)) # OUTPUT: [1,2,3] print(multiply(*l)) # OUTPUT: 6 , here all the elements of the list will get unpacked print(multiply(*t))
true
3790cba15164331e7f6d5ff4635b4190729526b7
akshat12000/Python-Run-And-Learn-Series
/Codes/86) fromkeys_get_copy_clear.py
1,523
4.25
4
# fromkeys d=dict.fromkeys(['name','age','height'],'unknown') # this will create dictionary like this {'name':'unknown','age':'unknown','height':'unknown'} print(d) d1=dict.fromkeys(('name','age','height'),'unknown') print(d1) # same as dictionary d d2=dict.fromkeys("ABC",'unknown') # this will create dictionary like this {'A': 'unknown', 'B': 'unknown', 'C': 'unknown'} print(d2) d3=dict.fromkeys(range(1,11),'unknown') # this will create dictionary like this {1: 'unknown', 2: 'unknown', 3: 'unknown', 4: 'unknown', 5: 'unknown', 6: 'unknown', 7: 'unknown', 8: 'unknown', 9: 'unknown', 10: 'unknown'} print(d3) d4=dict.fromkeys(['name','age'],['unknown','unknown']) # this will create dictionary like this {'name': ['unknown', 'unknown'], 'age': ['unknown', 'unknown']} print(d4) # get method print(d['name']) # print(d['names']) this will give you key error print(d.get('name')) print(d.get('names')) # it will not give error but instead it will print none if d.get('name'): print("Present") # Note: if None: will give you False !! else: print("Not present") # clear method d.clear() # it will clear all the key-value pairs from the dictionary print(d) # copy method d5=d1.copy() # all the key-value pairs of d1 will get copied to d5 print(d1) print(d5) # if we have used d5=d1 then both d1 and d5 will be pointing to same dictionary but by using copy method we get a separate copy for d5 d6=d1 print(d5 is d1) # OUTPUT: False print(d6 is d1) # OUTPUT: True
false
3513342cbbba1aee157d3c27dce319c2eef4bcbc
akshat12000/Python-Run-And-Learn-Series
/Codes/100) dictionary_comprehension_with_if_else.py
446
4.40625
4
# Dictionary Comprehension with if else statements # we have to create a dictionary in such a way that when key is odd then it's value will be 'odd' and same goes with even keys # Method 1)--> without dictionary comprehension d={} for i in range(1,11): if i%2: d[i]='odd' else: d[i]='even' print(d) # Method 2)--> with dictionary comprehension d1={i:('odd' if i%2 else 'even') for i in range(1,11)} print(d1)
false
9065b40cebe0cd5dbe74649d0ed526ac17b4e9d2
akshat12000/Python-Run-And-Learn-Series
/Codes/46) step_in_range.py
245
4.15625
4
for i in range(1,11): # i will increment by 1 print(i) print() # this automatically create a newline for i in range(1,11,2): # i will increment by 2 print(i) print() for i in range(10,0,-1): # i will decrement by 1 print(i)
false
4cd283528b382fab7369630629c6f46d0993590c
akshat12000/Python-Run-And-Learn-Series
/Codes/134) generators_intro.py
569
4.65625
5
# generators are iterators # iterators vs iterables l=[1,2,3,4] # iterable l1=map(lambda a:a**2,l) # iterator # We can use loops to iterate through both iterables and iterators!! li=[1,2,3,4,5] # memory --- [1,2,3,4,5], list, it will store as a chunk of memory!! # memory --- (1)->(2)->(3)->(4)->(5), generators, numbers will be generated one at a time and previously generated number will be # deallocated after it's use, hence it is time and memory efficient!! # If we want to use our data more than once then use lists otherwise use generators
true
82703ca80bd6745995fd86e4de8a7ae6e978efc5
akshat12000/Python-Run-And-Learn-Series
/Codes/137) generators_comprehension.py
444
4.21875
4
# Genrators comprehension square=[i**2 for i in range(1,11)] # list comprehension print(square) square1=(i**2 for i in range(1,11)) # generator comprehension print(square1) for i in square1: print(i) for i in square1: print(i) # Notice that it will print only once!! square2=(i**2 for i in range(1,5)) # generator comprehension print(next(square2)) print(next(square2)) print(next(square2)) print(next(square2))
true
5e5bcdee2c5fd58e9532872a8c4403e8cf47d49f
akshat12000/Python-Run-And-Learn-Series
/Codes/22) string_methods2.py
298
4.25
4
string="He is good in sport and he is also good in programming" # 1. replace() method print(string.replace(" ","_")) print(string.replace("is","was",1)) print(string.replace("is","was",2)) # 2. find() method print(string.find("is")) print(string.find("also")) print(string.find("is",5))
true
7613ae3e2b62c471be17440d5ce22679b7d61d0d
akshat12000/Python-Run-And-Learn-Series
/Codes/119) any_all_practice.py
421
4.1875
4
# Write a funtion which contains many values as arguments and return sum of of them only if all of them are either int or float def my_sum(*args): if all([type(i)== int or type(i)== float for i in args]): total=0 for i in args: total+=i return total else: return "WRONG INPUT!" print(my_sum(1,2,3,6.7,9.8,[1,2,3],"Akshat")) print(my_sum(1,2,3,4,6.7,9.8))
true
ea0f61c783a093d998866e3b7843daa2cbd01e4a
akshat12000/Python-Run-And-Learn-Series
/Codes/126) closure_practice.py
399
4.125
4
# Function returning function (closure or first class functions) practice def to_power(x): def calc_power(n): return n**x return calc_power cube=to_power(3) # cube will be the calc_power function with x=3 square=to_power(2) # square will be the calc_power function with x=2 print(cube(int(input("Enter first number: ")))) print(square(int(input("Enter second number: "))))
true
7232967214c29480b14d437eba3a42e5a2b23a5f
akshat12000/Python-Run-And-Learn-Series
/Codes/52) greatest_among_three.py
365
4.125
4
# Write a function which takes three numbers as an argument and returns the greatest among them def great3(a,b,c): if a>b: if a>c: return a return c else: if b>c: return b return c x,y,z=input("Enter any three numbers: ").split() print(f"Greatest number is: {great3(int(x),int(y),int(z))}")
true
ba1551611784af483ea8341a3fdbccc5a5d8b235
akshat12000/Python-Run-And-Learn-Series
/Codes/135) first_generator.py
932
4.5625
5
# Create your first generator with generator function # Method 1) --> generator function # Method 2) --> generator comprehension # Write a function which takes an integer as an argument and prints all the numbers from 1 to n def nums(n): for i in range(1,n+1): print(i) nums(5) def nums1(n): for i in range(1,n+1): yield(i) # or yield i # this statement makes nums1 a generator!! print(nums1(5)) # now nums1 has become a generator!! for i in nums1(5): # you can iterate through nums1(5) as it is an iterator!! print(i) print("printing numbers..") numbers=nums1(5) for i in numbers: print(i) for i in numbers: print(i) # numbers will be printed only once!! print("printing numbers which is converted to list...") numbers1=list(nums1(5)) for i in numbers1: print(i) for i in numbers1: print(i) # numbers2 will printed twice as it is list now
true
fd70a0a0c399b7ea099ad0df2069b1b861f7ac6d
akshat12000/Python-Run-And-Learn-Series
/Codes/58) intro_to_lists.py
702
4.3125
4
# A list is a collection of data numbers=[1,2,3,4,5] # list declaration syntax and it is list of integers print(numbers) words=["word1",'word2',"word3"] # list of strings as you can see we can use both '' and "" print(words) mixed=[1,2,3,4,"Five",'Six',7.0,None] # Here the list contains integers, strings, float and None data types print(mixed) # accessing list elements(Remember the indexing start from 0) print(numbers[2]) print(words[0]) print(mixed[6]) print(numbers[:2]) print(words[:]) print(mixed[4:]) # updating list elements mixed[1]=8 print(mixed) mixed[1:]="two" # whole list will replace from index 1 to end print(mixed) mixed[1:]=["one","two"] print(mixed)
true
f6ff85bebf05c377052e30a8e7c7e7ea9a7ec1a9
pedrohs86/Python_introduction
/hello.py
908
4.1875
4
#-*- coding: utf-8 -*- # coment test mensagem = "eae mano" # print ("Hello world!") # print ('Olá mundo!') """ comentario teste """ # print ( 2**2 ) #potência # print ( 10%3 ) #Resto da divisão # print (mensagem) var1 = 1 var2 = 1.1 var3 = 'string' var4 = True x = 2 y = 10 s = x # print (x == y) # print (x < y) # print (x>y) # print (soma>y) print (s > y and x == y) print (s > y or x == y) x = 3 # print (x==y) # print (x < y) # print (x>y) print (s > y and x == y) print (s > y or x == y) if s>y: print ('maior') else: print("menor") a = -2 b = -1 if b > a: if b > 0: print ("b é maior que a\nb é positivo") else: print ("b é maior que a\nb é negativo") else: print ("b é menor que a") x = 1 y =2 if x == y: print("numeros iguais") elif x > y: print("x maior que y") elif y > x: print("y maior que x") else: print("Bugou")
false
f803ca25ed0928e6c2786d99f26a2f69b5c69dd2
indradevg/mypython
/cbt_practice/for1.py
609
4.34375
4
#!/usr/bin/python3.4 i=10 print("i value before : the loop: ", i) for i in range(5): print(i) ''' The for loops work in such a way that leave's behind the i value to the end of the loop and re-assigns the value to i which was initializd as 10 in our case ''' print("i value after the loop: ", i) ''' The below line in the for loop when enclosed in the [ ] will not allow the for loop variable leak However, in Python 3.x, we can use closures to prevent the for-loop variable to cut into the global namespace ''' i = 1 #print([i for i in range(5)]) [print(i) for i in range(5)] print(i, '-> i in global')
true
b6ea51a48ca6e63a766de59acfcd8f7a9fe58245
danamur/CursoPython
/Sentencias Condicionales/SentenciaCondicionalesSimples.py
556
4.125
4
print("Sistema para cualcular el promerdio de un alumno") nombre = input("Para comenzar, ¿Cual es tu nombre?: ") matematicas = float(input(nombre + " ¿Cual es tu calificacion en matematicas?: ")) quimica = float(input(nombre + " ¿Cual es tu calificacion en quimica?: ")) lenguaje = float(input(nombre + "¿Cual es tu calificacion en biologia?: ")) promedio = (matematicas + quimica + lenguaje) / 3 if promedio >= 4.0: print('Felicidades ' + nombre + '! "Aprovaste" con un promedio de: ', promedio) print("Fin.")
false
e81d068021e2eb248346daf25096163191768be6
danamur/CursoPython
/Bucles/BucleWhile - RaizCuadrada.py
689
4.15625
4
import math print("-------------------------------------------") print("| Programa de cálculo de la raíz cuadrada |") print("-------------------------------------------\n") numero = int(input("Introduce un número por favor: \n")) intentos = 0 while numero < 0: print("No se puede hallar la raíz de un número negativo") if intento == 2: print("Has consumido demasiados intentos. El programa ha finalaizado") break; numero = int(input("Introduce un número por favor:\n")) if numero < 0: intento += 1 if intentos < 2: solucion = math.sqrt(numero) print("La raiz cuadrada de " + str(numero) + " es ",solucion)
false
0c28d1d950dbbdf74ec827583dd7c46c331bc4b0
thanasissot/myPyFuncs
/fibonacci.py
481
4.1875
4
# cached fibonacci cache = dict() def memFib(n): """Stores result in cache dictionary to be used at function definition time, making it faster than first caching then using it again for faster results """ if n in cache: return cache[n] else: if n == 0: return 0 elif n == 1: return 1 else: result = memFib(n - 1) + memFib(n -2) cache[n] = result return result
true
d3d4fe44bb69702cae5869b55e61b71b77a75025
Shivansh-Commits/Basic-Programming-Using-Python
/Program(3).py
361
4.1875
4
#Q) Print 'Hello' if the no. is only divisible by 3 #Print 'Python' if the no. is only divisible by 5 #print 'Hello Python' if the no. is divisible by both 3&5 for i in range(1,51): if(i%3==0 and i%5==0): print("Hello Python") elif(i%3==0): print("Hello") elif(i%5==0): print("Python") else: print(i)
false
0281e0caca322b8701acc8610b38a0bb8f4bd039
JiaLee0707/2019-Python
/parking07-06.py
1,075
4.125
4
## 변수 선언 부분 parking = [] top, carName, outCar=0, "A", "" select = 9 ## 메인(main) 코드 부분 while(select != 3) : select=int(input("<1> 자동차 넣기 <2> 자동차 빼기 <3> 끝 : ")) if(select == 1): if(top>=5): print("주차장이 꽉 차서 못들어감") else: parking.append(carName) print("%s 자동차 들어감. 주차장 상태==>%s"%(parking[top], parking)) top+=1 carName = chr(ord(carName)+1) elif(select == 2): if(top <= 0): print("빠져나갈 자동차가 없음") else: outCar = parking.pop() print("%s 자동차 나감. 주차장 상태==>%s" % (outCar, parking)) top-=1 carName=chr(ord(carName)-1) elif(select == 3): break; else: print("잘못 입력했네요. 다시 입력하세요.") print("현재 주차장에 %d 대가 있음" % top) print("프로그램을 종료합니다.") ## chr() 문자로 변환 ## ord() Assci코드값으로 변환
false
e58f837ab1a161e23b8af68e15cb9095961ab52c
Moglten/Nanodegree-Data-structure-and-Algorithm-Udacity
/Data Structure/queue/reverse_queue.py
329
4.21875
4
def reverse_queue(queue): """ Given a Queue to reverse its elements Args: queue : queue gonna reversed Returns: queue : Reversed Queue """ stack = Stack() while not queue.is_empty(): stack.push(queue.dequeue()) while not stack.is_empty(): queue.enqueue(stack.pop())
true
38b7b5030e6d39b2adaabe73e14b40e637a14e3b
feleck/edX6001x
/lec6_problem2.py
623
4.1875
4
test = ('I', 'am', 'a', 'test', 'tuple') def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' result = () i = 0 while i < len(aTup): if i % 2 == 0: result += (aTup[i:i+1]) i+= 1 #print result return result # Solution from page: def oddTuples2(aTup): ''' Another way to solve the problem. aTup: a tuple returns: tuple, every other element of aTup. ''' # Here is another solution to the problem that uses tuple # slicing by 2 to achieve the same result return aTup[::2]
true
8781f9f96a111b4edb2772afc5bee20e7861a881
deadsquirrel/courseralessons
/test14.1mod.py
1,059
4.15625
4
''' Extracting Data from JSON In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below: Sample data: http://python-data.dr-chuck.net/comments_42.json (Sum=2553) Actual data: http://python-data.dr-chuck.net/comments_204876.json (Sum ends with 78) ''' import urllib import json url = raw_input('Enter location: ') print 'Retrieving', url uh = urllib.urlopen(url) print uh data = uh.read() print 'Retrieved',len(data),'characters' print "----------------" print data info = json.loads(data) #print info sum = 0 #print json.dumps(info, indent=4) #print 'mm', info["comments"][0] #["count"] commentators = [] for item in info["comments"]: # print item # print item["count"] sum = sum + item["count"] commentators.append(item["name"]) print commentators print sum
true
97caae6c7fcaed2f8c0442dec8166a3c26b7caf5
pduncan08/Python_Class
/Wk3_Sec4_Ex3a.py
704
4.28125
4
# Lists - Exercise 3 # Python indexing starts at 0. This will come up whenever you # have items in a list format, so always remember to ask for # 1 less than whatt you want! John_Skills=["Python", "Communicateon", "Low Salary Request", 1000] print(John_Skills) Applicants=[["John", "Python"],["Geoff", "Doesn't Know Python"]] print(Applicants) # Create Lists of Lists heights=[["Jenny",61], ["Alexus",70],["Sam",67], ["Grace",64],["vik",68]] ages=[["Aaron",15],["Dhruti",16]] print(heights[2][1]) print(ages[0]) # You can use zip to create a new list names=["Jenny", "Alexus", "Samuel", "Grace"] skills=["Python", "R", "NOTHING","Python"] names_and_skills=zip(names, skills) print(names_and_skills)
true
5394d2d8237802a930e1c43b1fffc5fb1f2a1090
non26/testing_buitIn_module
/superMethod/test1_superMethod.py
603
4.53125
5
""" this super method example here takes the argument of two, first is the subClass and the second is the instance of that subClass so that the the subClass' instance can use the superClass' attributes STRUCTURE: super(subclass, instance) """ class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height self.area = width * height class Square(Rectangle): def __init__(self, length): # super() executes fine now super(Square, self).__init__(length, length) s = Square(5) print(s.area) # 25
true
f31816fec154d08f18eaa849cbd8d8ca3920bb2e
SoyUnaFuente/c3e3
/main.py
571
4.21875
4
score = int(input("Enter your score: ")) # if score in range(1, 51): # print (f"There is no prize for {score}") if 1 <= score <=50: print (f"There is no prize for {score}") elif 51 <= score <=150: medal = "Bronze" print(f"Congratulations, you won the {medal} medal for having {score} points ") elif 151 <= score <=180: medal = "Silver" print(f"Congratulations, you won the {medal} medal for having {score} points ") elif 181 <= score <=200: medal = "Gold" print(f"Congratulations, you won the {medal} medal for having {score} points ")
true
bcfbb2aeb996835a5d1d567c331b5a926b2c4fd9
AllanRPereira/Simple-Color-Terminal
/cursor.py
2,803
4.15625
4
""" Função: Definir funções para realização de operações com o cursor, usando o terminal Autor: Állan Rocha """ import sys ANSI = "\033[" def cursor_move(direction="UP", lines=1): """ Move o cursor de acordo com a direção e quantidade de linhas/colunas desejadas """ directions = {"UP":"A", "DOWN":"B", "FORWARD": "C", "BACK":"D"} assert direction in directions sys.stdout.write("{}{}{}m".format(ANSI, lines, directions[direction])) def next_line(position=1): """ Move o cursor para a próxima linha, e o posiciona-o nessa linha """ assert type(position) in (str, int) sys.stdout.write("{}{}{}m".format(ANSI, position, "E")) def previous_line(position=1): """ Move o cursor para a linha anterior, e o posiciona-o nessa linha """ assert type(position) in (str, int) sys.stdout.write("{}{}{}m".format(ANSI, position, "F")) def cursor_to_column(column=1): """ Move o cursor para uma determinada coluna de uma linha """ assert type(column) in (str, int) sys.stdout.write("{}{}{}m".format(ANSI, column, "G")) def move_to_position(line=1, column=1): """ Posiciona o cursor para as coordenada (line, column) """ assert type(line) in (str, int) assert type(column) in (str, int) sys.stdout.write("{}{};{}{}m".format(ANSI, line, column, "H")) def erase_in_terminal(mode="ALL_VIEW"): """ Vários modos de limpar o terminal """ cleans_mode = {"ALL" : "3", "ALL_VIEW" : "2", "CURSOR_END" : "1", "BEG_CURSOR" : "0"} assert mode in cleans_mode sys.stdout.write("{}{}{}".format(ANSI, cleans_mode[mode], "J")) def erase_in_line(mode="ALL"): """ Alguns modos para limpar uma linha de um terminal """ line_clean_modes = {"ALL" : "2", "CURSOR_END" : "1", "BEG_CURSOR" : "0"} assert mode in line_clean_modes sys.stdout.write("{}{}{}".format(ANSI, line_clean_modes[mode], "K")) def scroll_move(lines=40, mode="UP"): """ Move o scroll para um terminada linha, tanto para cima, quanto para baixo """ scroll_modes = {"UP" : "S", "DOWN": "T"} assert mode in scroll_modes sys.stdout.write("{}{}{}".format(ANSI, lines, scroll_modes[mode])) def save_position(): """ Salva a posição do cursor na tela """ sys.stdout.write("{}s".format(ANSI)) def restore_position(): """ Restaura a posição com base na posição salva """ sys.stdout.write("{}u".format(ANSI)) def change_cursor_state(mode="SHOW"): """ Altera certa característica do cursor """ states = {"SHOW":"?25h", "HIDE":"?25l"} assert mode in states sys.stdout.write("{}{}".format(ANSI, states[mode])) if __name__ == "__main__": change_cursor_state("HIDE") sys.stdout.write("Escondi seu cursor :D")
false
3223ced97083d48d879451264165dc100c62d7d2
Hugocorreaa/Python
/Curso em Vídeo/Desafios/Mundo 2/ex071 - Simulador de Caixa Eletrônico.py
1,137
4.21875
4
''' Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS. Considere que o caixa possuí cédulas de R$50, R$20, R$10 e R$1. ''' print('=' * 30) print('{:^30}'.format('BANCO CEV')) print('=' * 30) cont50 = cont20 = cont10 = cont1 = 0 valor = int(input('Que valor você quer sacar? R$ ')) while valor != 0: while valor // 50 > 0: cont50 += 1 valor = valor - 50 if cont50 > 0: print(f'Total de {cont50} cédulas de R$50') while valor // 20 > 0: cont20 += 1 valor = valor - 20 if cont20 > 0: print(f'Total de {cont20} cédulas de R$20') while valor // 10 > 0: cont10 += 1 valor = valor - 10 if cont10 > 0: print(f'Total de {cont10} cédulas de R$10') while valor // 1 > 0: cont1 += 1 valor = valor - 1 if cont1 > 0: print(f'Total de {cont1} cédulas de R$1') print('=' * 30) print('Volte sempre ao BANCO CEV! Tenha um bom dia!')
false
d0773128c4e95c086f4c21eb0e93bda36083cbac
Hugocorreaa/Python
/Curso em Vídeo/Desafios/Mundo 2/ex036 - Aprovando Empréstimo.py
1,447
4.1875
4
""" Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou então o empréstimo será negado. """ from time import sleep print("-=-" * 15) print("Aprovaremos o Empréstimo para Sua Casa Própria!!") print("-=-"*15) sleep(1) casa = float(input("Qual o valor da casa? R$")) salario = float(input("Qual o seu salário? R$")) anos = float(input("Em quantos anos você pretende pagar? ")) prestação = (casa // anos) // 12 maximo = salario * 30 // 100 print("\033[1;34mAnalisando...") sleep(1.5) if prestação <= maximo and anos == 1: print("""{}Seu empréstimo foi aprovado!{} A casa de valor R${:.2f} reais será paga em {:.0f} ano com prestações mensais de R${:.2f} reais """.format("\033[1;32m", "\033[m", casa, anos, prestação)) elif prestação <= maximo: print("""{}Seu empréstimo foi aprovado!{} A casa de valor R${:.2f} reais será paga em {:.0f} anos com prestações mensais de R${:.2f} reais """.format("\033[1;32m" , "\033[m", casa, anos, prestação)) else: print("""{}Desculpa, não podemos aprovar seu empréstimo no momento!{} Para pagar uma casa de R${:.2f} reais em {:.0f} anos a prestação mensal será de R${:.2f} reais""".format("\033[1;31m", "\033[m", casa, anos, prestação))
false
c0c7f5440c3b9ca7a783ae2b21c479ae022d9b2b
Hugocorreaa/Python
/Curso em Vídeo/Desafios/Mundo 1/ex028.py
695
4.1875
4
# Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar desco #brir qual foi o número escolhido pelo computador. # O programa deverá escrever na tela se o usuário venceu ou perdeu. from time import sleep from random import randrange random = randrange(6) print("-=-" * 20) print("Vou pensar em um número de 0 a 5. Tente adivinhar!") print("-=-" * 20) sleep(3) palpite = int(input("Qual número, de 0 a 5, estou pensando? ")) if palpite == random: print("Parabéns, você acertou! Eu estava pensando no número {}".format(random)) else: print("Que pena, você errou! Eu estava pensando no número {}".format(random))
false
5c133a38fdca5f32432dbe164820ed62e249615c
cosmos-sajal/python_design_patterns
/creational/factory_pattern.py
1,035
4.21875
4
# https://dzone.com/articles/strategy-vs-factory-design-pattern-in-java # https://stackoverflow.com/questions/616796/what-is-the-difference-between-factory-and-strategy-patterns # https://stackoverflow.com/questions/2386125/real-world-examples-of-factory-method-pattern from abc import ABCMeta, abstractmethod class DBTable(metaclass=ABCMeta): @abstractmethod def create_table(self): pass class PostgreSQL(DBTable): def create_table(self): print("creating table in postgreSQL") class MongoDB(DBTable): def create_table(self): print("creating table in MongoDB") class DBFactory(): def __init__(self): """ change this db config in order to change the underlying DB """ self.db_config = 'sql' def get_database(self): if self.db_config == 'sql': return PostgreSQL() else: return MongoDB() print("creating table in database") db_factory = DBFactory() db = db_factory.get_database() db.create_table()
true
dd5600b48a73fcc8118a305826d704766463260d
danielacevedo20/introprogramacion
/Clases/Excepciones/ejemplo.py
1,029
4.15625
4
isCorrectInfo = False while(isCorrectInfo == False): try: edad = int (input("Ingrese su edad: ")) isCorrectInfo = True except ValueError: print("Ingresaste un dato erroneo") nombreArchivo = input("Ingrese el nombre del archivo que desdea encontrar: ") try: archivo = open (nombreArchivo) except FileNotFoundError: print (f"El archiivo {nombreArchivo} no se ha encontrado") base= 4 divisor = 0 try: dividir = base/divisor except ZeroDivisionError: print ("El divisor ingresado es 0, por lo tanto la solución no se encuentra dentro de los reales") isCorrectInfo = False while(isCorrectInfo == False): try: nombre = input("Ingrese su nombre: ") assert (nombre.isalpha()) isCorrectInfo = True except AssertionError: print("Ingresaste un dato erroneo") except ValueError: print("Las edades son números enteros") lista= [2,43,54,32] try: lista [5] except IndexError: print("El indice es mayor al tamaño de la lista")
false
92d46625f1bb1bfe6e6a2a359af18f50770d540b
potnik/sea_code_club
/code/python/rock-paper-scissors/rock-paper-scissors-commented.py
2,585
4.5
4
#!/bin/python3 # The previous line looks like a comment, but is known as a shebang # it must be the first line of the file. It tells the computer that # this is a python script and to use python3 found in the /bin folder from random import randint # From the python module called random, import the function randint # randint returns a random integer in range [a, b], including both end points. # initiate some variables an assign them values play = True # this will be used to keep the game going if the user chooses to # These next three are to hold the score for reporting later draw = 0 # number of draw games pw = 0 # number of player wins cw = 0 # number of computer wins # The main part of the program consists of a while loop that runs the game # until the player tells it to quit while play==True: # while the value of the variable play equal True, keep running the game loop prompt = True # set the prompt variable to True while prompt == True: # keep prompting the player until they give the correct response player = input('rock(r), paper(p) or scissors(s)?') if player=='r' or player=='s' or player=='p': prompt=False else: print('Please enter r, p, or s') # Here we use randint to generate an integer. In this case, 1, 2, or 3 # this will map to the computers selection below chosen = randint(1,3) # A comment to remind us what each value means. Commenting you code is a good practice # 1 = rock (r) # 2 = paper (p) # 3 = scissors (s) # an if, elif, else block that assigns a letter to the value of chosen if chosen == 1: computer = 'r' elif chosen == 2: computer = 'p' else: # an else statement doesn't have a condition. computer = 's' print(player, ' vs ', computer) # A block of if statements to determine who wins if player == computer: print('DRAW!') draw = draw + 1 # these statements keep a running count of the score elif player == 'r' and computer == 's': print('Player Wins!') pw = pw + 1 elif player == 'p' and computer == 'r': pw = pw + 1 print('Player Wins') elif player == 's' and computer == 'p': pw = pw + 1 print('Player Wins!') else: print('Computer Wins!') cw = cw + 1 # prompt the user if they want to play again. # if they enter anything other than q, continue again=input('Play again? enter q to quit') if again=='q': play=False # Finally, print out the scoreboard print() print('Score') print('-----') print('Player: ', pw) print('Computer: ', cw) print('Draw: ', draw) print()
true
af908716f27a9ff46e623c883300cdcd7464d994
pranaychandekar/dsa
/src/basic_maths/prime_or_no_prime.py
1,199
4.3125
4
import time class PrimeOrNot: """ This class is a python implementation of the problem discussed in this video by mycodeschool - https://www.youtube.com/watch?v=7VPA-HjjUmU :Authors: pranaychandekar """ @staticmethod def is_prime(number: int): """ This method tells whether a given non-negative number is prime or not. :param number: The number which needs to be verified. :type number: int :return: The result whether the given number is prime or not. :rtype: bool """ result: bool = True if number < 2: result = False else: upper_limit = int(number ** 0.5) + 1 for i in range(2, upper_limit, 1): if number % i == 0: result = False return result return result if __name__ == "__main__": tic = time.time() number = 49 # Enter the number here if PrimeOrNot.is_prime(number): print("\nThe number", number, "is prime.") else: print("\nThe number", number, "is not prime.") toc = time.time() print("\nTotal time taken:", toc - tic, "seconds")
true
db56d84911eac1cae9be782fd2ebb047c625fce2
pranaychandekar/dsa
/src/sorting/bubble_sort.py
1,488
4.46875
4
import time class BubbleSort: """ This class is a python implementation of the problem discussed in this video by mycodeschool - https://www.youtube.com/watch?v=Jdtq5uKz-w4 :Authors: pranaychandekar """ @staticmethod def bubble_sort(unsorted_list: list): """ This method sorts a given list in ascending order using Bubble Sort algorithm. :param unsorted_list: The list which needs to be sorted. :type unsorted_list: list """ unsorted_list_size = len(unsorted_list) for i in range(unsorted_list_size - 1): all_sorted = True for j in range(unsorted_list_size - i - 1): if unsorted_list[j] > unsorted_list[j + 1]: temp = unsorted_list[j] unsorted_list[j] = unsorted_list[j + 1] unsorted_list[j + 1] = temp all_sorted = False if all_sorted: break if __name__ == "__main__": tic = time.time() print("\nYou are currently running Bubble Sort test case.") unsorted_list = [2, 7, 4, 1, 5, 3] print("\nUnsorted List: ") for element in unsorted_list: print(str(element), end=", ") print() BubbleSort.bubble_sort(unsorted_list) print("\nSorted List: ") for element in unsorted_list: print(str(element), end=", ") print() toc = time.time() print("\nTotal time taken:", toc - tic, "seconds.")
true
7e2f82c44c8df1de42f1026dcc52ecef804d9506
pranaychandekar/dsa
/src/basic_maths/prime_factors.py
1,324
4.25
4
import time class PrimeFactors: """ This class is a python implementation of the problem discussed in this video by mycodeschool - https://www.youtube.com/watch?v=6PDtgHhpCHo :Authors: pranaychandekar """ @staticmethod def get_all_prime_factors(number: int): """ This method finds all the prime factors along with their power for a given number. :param number: The non-negative number for which we want to find all the prime factors. :type number: int :return: All the prime factors with their corresponding powers. :rtype: dict """ prime_factors = {} upper_limit = int(number ** 0.5) + 1 for i in range(2, upper_limit, 1): if number % i == 0: count = 0 while number % i == 0: number /= i count += 1 prime_factors[i] = count if number != 1: prime_factors[int(number)] = 1 return prime_factors if __name__ == "__main__": tic = time.time() number = 99 prime_factors = PrimeFactors.get_all_prime_factors(number) print("\nThe prime factors of number", number, "are:", prime_factors) toc = time.time() print("\nTotal time taken", toc - tic, "seconds.")
true
a241a2db9e5561e428bfe0aa090059da338da4b9
anastasia1002/practise1
/21.py
252
4.125
4
#cosx+cos^2x+...cos^nx import math n = int(input("натуральне число")) x = float(input("дійсне число")) sum = 0 i = math.cos(x) while i <= math.cos(x) ** n: sum = i + math.cos(x) else: sum = math.cos(x) ** n print(sum)
false
985ee849a95356776888f8b0ea7f2a69bfcd56be
karthikwebdev/oops-infytq-prep
/queue.py
1,087
4.125
4
class Queue: def __init__(self,size): self.list = [] self.front = -1 self.rear = -1 self.size = size def enque(self,val): if(self.size-1 == self.rear): print("queue is full") elif(self.rear == -1 and self.front == -1): self.list.append(val) self.front = 0 self.rear = 0 else: self.list.append(val) self.rear += 1 def deque(self): if(self.rear == -1 and self.front == -1): print("queue is empty") else: self.list.pop(0) self.rear -= 1 if(self.rear == -1): self.front = -1 def display(self): for i in self.list[::-1]: print(i) size = int(input("enter the size of queue")) q1 = Queue(size) while(True): s = int(input("1.enque 2.deque 3.display 4.exit")) if(s == 1): val = int(input("enter value to add")) q1.enque(val) elif(s == 2): q1.deque() elif(s == 3): q1.display() else: break
false
2910d6bc150cfb5cfc60e5b31f9910d546027eda
karthikwebdev/oops-infytq-prep
/2-feb.py
1,943
4.375
4
#strings # str = "karthi" # print(str[0]) # print(str[-1]) # print(str[-2:-5:-1]) # print(str[-2:-5:-1]+str[1:4]) #str[2] = "p" -- we cannot update string it gives error #del str[2] -- this also gives error we cannot delete string #print("i'm \"karthik\"") --escape sequencing # print("C:\\Python\\Geeks\\") # print(r"I'm a \"Geek\"") # print(r"I'm a "Geek"") # print(r"C:\\Python\\Geeks\\")# --to print raw string #string formatting # print("{} hello {} hi".format(1,"hey")) # print("{0} hello {1} hi".format(1,"hey")) # print("{first} hello {second} hi".format(first=1,second="hey")) #logical operator in string # print("hello" and "hi") # if none of them is empty string then returns second string # print("hello" or "hi")# if none of them is empty string then returns first string # print("hi" or "") # if one them are empty but one is a string then returns that string # print("hello" and "") #both should be string returns empty string # print(not "hello") #false # print(not "") #true # def power(a, b): # """Returns arg1 raised to power arg2.""" # return a*b # print(power.__doc__ ) # different ways for reversing string # def rev1(s): # str = "" # for i in s: # str = i + str # return str # #using recursion # def rev2(s): # if len(s) == 0: # return s # else: # return rev2(s[1:])+s[0] # #most easy method # def rev3(s): # str = s[::-1] # return str # #using reversed method # #reversed method returns an iterator # #join used for joining iterables with a string # def rev4(s): # return "".join(reversed(s)) # print(rev1("karthik")) # print(rev2("karthik")) # print(rev3("karthik")) # print(rev4("karthik")) # #palindrome program # def palindrome(s): # if(s == s[::-1]): # print("yes") # else: # print("no") # palindrome("malayalam") str = "hello" str += " world" print(str) print("we " + "can " + "concatinate ")
true
f5869aaa4189761e68f83239aa7016ebef0b01b4
Justin696/2020-21-c1-challenge-08
/main.py
800
4.15625
4
print("you can do all chalenges in this challenge") print("Please enter the Chalenge number from 1 to 7") num = int(input("<: ")) if num < 1: print("there are no challenges less than 1") elif num > 7: print("There are no challenges more than 1") elif num == 1: print("You have chosen to play chalenge 1 good luck") elif num == 2: print("you have chosen to play chalenge 2 good luck") elif num == 3: print("you have chosen to play chalenge 3 good luck") elif num == 4: print("you have chosen to play chalenge 4 good luck") elif num == 5: print("you have chosen to play chalenge 5 good luck") elif num == 6: print("you have chosen to play chalenge 6 good luck") elif num == 7: print("you have chosen to play chalenge 7 good luck") else: print("what have you done")
false
24cd787fb713d2e489d59e4f698ec1fd233c8e93
vigoroushui/python_lsy
/8.object_oriented_programming/instanceAndClass.py
566
4.15625
4
#区别,第一个是实例属性、第二个是类属性 def Student(object): def __init__(self, name): self.name = name class Student1(object): name = 'Student' # 在编写程序的时候,千万不要对实例属性和类属性使用相同的名字 # 因为相同名称的实例属性将屏蔽掉类属性, # 但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性。 stu = Student1() print(stu.name) print(Student1.name) stu.name = 'Jack' print(stu.name) print(Student1.name) del stu.name print(stu.name)
false
29be4af3d652948430278ffe545f81c011643a1e
ronaka0411/Google-Python-Exercise
/sortedMethod.py
222
4.125
4
# use of sorted method for sorting elements of a list strs = ['axa','byb','cdc','xyz'] def myFn(s): return s[-1] #this will creat proxy values for sorting algorithm print(strs) print(sorted(strs,key=myFn))
true
d53ea1900d1bfc9ab6295430ac272616293cb09d
talebilling/hackerrank
/python/nested_list.py
1,480
4.3125
4
''' Nested Lists Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. Input: 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Output: Berry Harry ''' def main(): # if __name__ == '__main__': names_and_grades = [] names_and_grades = get_data(names_and_grades) name_list = get_lowest_grades(names_and_grades) printing(name_list) def get_data(names_and_grades): students = int(input()) for item in range(students): student_data = [] name = input() score = float(input()) student_data.append(score) student_data.append(name) names_and_grades.append(student_data) return names_and_grades def get_lowest_grades(names_and_grades): lowest = min(names_and_grades) second_lowest_list = [] for name_grade in names_and_grades: if name_grade[0] != lowest[0]: second_lowest_list.append(name_grade) second_lowest = min(second_lowest_list) name_list = [] for name_grade in second_lowest_list: if name_grade[0] == second_lowest[0]: name_list.append(name_grade[1]) return name_list def printing(name_list): name_list = sorted(name_list) print("\n".join(name_list)) main()
true
9dd75d361e52c9c1e6169b6b3f47d1e202db1a76
a-soliman/pythonData-structureAndAlgorithms
/sec-15-recursion/hw.py
2,200
4.25
4
''' ''' #======================================================================================= # recursive Sum ''' Write a recursive function that returns the sum from 0 up to n ''' def sum_down( n ): if n == 1: return 1 else: return n + sum_down(n-1) print('23- sum_down: ', sum_down(5)) #======================================================================================= # recursive fibonacci ''' ''' def nth_fibonacci( n ): fibonacci = [0, 1] # helper function def search(x, limit): #base-case if x == limit: return sum = fibonacci[x-1] + fibonacci[x-2] fibonacci.append(sum) search(x+1, limit) if n < 2: return n search(2, n) return fibonacci[-1] print('24- Fibonacci(50): ', nth_fibonacci(50)) #======================================================================================= # recursive fibonacci_2 ''' ''' def nth_fibonacci_2( n ): if n == 1: return 1 if n == 2: return 1 if n > 2: return nth_fibonacci_2(n-1) + nth_fibonacci_2(n-2) print('25- Fibonacci(10): ', nth_fibonacci_2(10)) #======================================================================================= # recursive fibonacci_3 ''' using memoization ''' def nth_fibonacci_3( n ): fib_hash = {} def search(x): if x in fib_hash: return fib_hash[x] value = 0 if x == 1: value = 1 if x == 2: value = 2 if x > 2: value = search(x-1) + search(x-2) fib_hash[x] = value return value search(n) return fib_hash[n] print('26- Fibonacci_with_memoization(100): ', nth_fibonacci_3(100)) #======================================================================================= # sum_func ''' Given an integer, create a function which returns the sum of all the individual digits in that integer. for example: if n = 4321m, return 4 + 3 + 2 + 1 '''
false
401123e1362106e0268f2050533c15048ef5d767
ruselll1705/home
/home_work3_3.py
600
4.125
4
while True: print("Type 'quit' to exit") phrase = input("Your message: ") if phrase == "quit": break elif phrase == "Hello" or phrase == "Hi": print("Hi! How‘s it going?") elif phrase == "What is your name?": print("I don't have name :(") elif phrase=="я устал": print('«Ты больше не хочешь со мной говорить?') phrase = input("Your message: ") if phrase=="нет": print("Ну, поговори еще со мной!") else: print("I don't understand you")
false
cc2355c574130c4b5244b930cb6c5c3160af40e3
KarimBertacche/Intro-Python-I
/src/14_cal.py
2,289
4.65625
5
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py [month] [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. Note: the user should provide argument input (in the initial call to run the file) and not prompted input. Also, the brackets around year are to denote that the argument is optional, as this is a common convention in documentation. This would mean that from the command line you would call `python3 14_cal.py 4 2015` to print out a calendar for April in 2015, but if you omit either the year or both values, it should use today’s date to get the month and year. """ import sys import calendar from datetime import datetime # Get length of command line arguments arg_length = len(sys.argv) # if length is more than 3, block execution and warn user if arg_length > 3: print("Exessive number of arguments passed in, \n expected 2 arguments representing the desired day and year as numeric values") sys.exit() # if inputed arguments are equal to 3 we assume those are numbers and pass them to the # calendar module and get the month and year based on the arguments elif arg_length == 3: print(calendar.month(int(sys.argv[2]), int(sys.argv[1]))) # if inputed arguments are equal to 2, that means no year has been specified, therefore # we show the month specified by the user of the current year elif arg_length == 2: print(calendar.month(datetime.now().year, int(sys.argv[1]))) # if no arguments have been provided, then we showcase the current month and year else: print(calendar.month(datetime.now().year, datetime.now().month))
true
1387e63d50e7170a0733e43c95da207acf0f5925
kagekyaa/HackerRank
/Python/005-for_while_loop_in_range.py
488
4.28125
4
'''https://www.hackerrank.com/challenges/python-loops Read an integer N. For all non-negative integers i<N, print i^2. See the sample for details. Sample Input 5 Sample Output 0 1 4 9 16 ''' if __name__ == '__main__': n = int(raw_input()) for i in range(0, n): print i * i ''' A for loop: for i in range(0, 5): print i And a while loop: i = 0 while i < 5: print i i += 1 Here, the term range(0,5) returns a list of integers from 1 to 5: [0,1,2,3,4]. '''
true
261a252acbfe4691fbee8166a699e3789f467e8b
franciscoguemes/python3_examples
/basic/64_exceptions_04.py
1,328
4.28125
4
#!/usr/bin/python3 # This example shows how to create your own user-defined exception hierarchy. Like any other class in Python, # exceptions can inherit from other exceptions. import math class NumberException(Exception): """Base class for other exceptions""" pass class EvenNumberException(NumberException): """Specific exception which inherits from MyGenericException""" pass class OddNumberException(NumberException): """Specific exception which inherits from MyGenericException""" pass def get_number(message): while True: try: number = int(input(message)) return number except ValueError: print("The supplied value is not a number, Try again...") stay = True while stay: try: num = get_number("Introduce any number (0 to exit):") if num == 0: stay = False elif num % 2 == 0: raise EvenNumberException else: raise OddNumberException except EvenNumberException: print("The number you introduced", num, "is Even!") except OddNumberException: print("The number you introduced", num, "is Odd!") # As example you can try to re-write this same application capturing the exception NumberException and using the # isinstance operator...
true
73cccc2cd1bbcea2da0015abc9ea0157be449844
franciscoguemes/python3_examples
/projects/calculator/calculator.py
1,434
4.3125
4
#!/usr/bin/python3 # This example is the typical calculator application # This is the calculator to build: # ####### # 7 8 9 / # 4 5 6 * # 1 2 3 - # 0 . + = # Example inspired from: https://www.youtube.com/watch?v=VMP1oQOxfM0&t=1176s import tkinter window = tkinter.Tk() #window.geometry("312x324") window.resizable(0,0) window.title("Calculator") tkinter.Label(window, text="0", anchor="e", bg="orange").grid(row=0, columnspan=4, sticky="nswe") #The 'sticky' option forces the element to fill all extra space inside the grid tkinter.Button(window, text="7").grid(row=1, column=0) tkinter.Button(window, text="8").grid(row=1, column=1) tkinter.Button(window, text="9").grid(row=1, column=2) tkinter.Button(window, text="/").grid(row=1, column=3) tkinter.Button(window, text="4").grid(row=2, column=0) tkinter.Button(window, text="5").grid(row=2, column=1) tkinter.Button(window, text="6").grid(row=2, column=2) tkinter.Button(window, text="x").grid(row=2, column=3) tkinter.Button(window, text="1").grid(row=3, column=0) tkinter.Button(window, text="2").grid(row=3, column=1) tkinter.Button(window, text="3").grid(row=3, column=2) tkinter.Button(window, text="-").grid(row=3, column=3) tkinter.Button(window, text="0").grid(row=4, column=0) tkinter.Button(window, text=".").grid(row=4, column=1) tkinter.Button(window, text="+").grid(row=4, column=2) tkinter.Button(window, text="=").grid(row=4, column=3) window.mainloop()
true
7244b8b9da478b14c71c81b2ff299da0e4b18877
franciscoguemes/python3_examples
/basic/06_division.py
697
4.4375
4
#!/usr/bin/python3 # Floor division // --> returns 3 because the operators are 2 integers # and it rounds down the result to the closest integer integer_result = 7//2 print(f"{integer_result}") # Floor division // --> returns 3.0 because the first number is a float # , so it rounds down to the closest integer and return it in float format. float_result = 7.//2 print(f"{float_result}") # Floor division // --> returns -4.0 because the floor division rounds the result down to the nearest integer # in this case rounding down is to -4 because -4 is lower than -3 !!! integer_result = -7.//2 print(f"{integer_result}") # Division / --> returns 3.5 float_result = 7/2 print(f"{float_result}")
true
e83ee865e27bc54b1c58fb9c220ef757d2df4de3
franciscoguemes/python3_examples
/advanced/tkinter/03_click_me.py
557
4.125
4
#!/usr/bin/python3 # This example shows how to handle a basic event in a button. # This basic example uses the command parameter to handle the click event # with a function that do not have any parameters. # Example inspired from: https://www.youtube.com/watch?v=VMP1oQOxfM0&t=1176s import tkinter window = tkinter.Tk() window.title("Handling the click event!") window.geometry('500x500') def say_hi(): tkinter.Label(window, text="Hello! I am here!").pack() tkinter.Button(window, text="Click Me!", command=say_hi).pack() window.mainloop()
true
776a51053306a024ab824003e63255c89cdbb6d4
franciscoguemes/python3_examples
/basic/09_formatting_strings.py
673
4.625
5
#!/usr/bin/python3 # TODO: Continue the example from: https://pyformat.info/ # There are two ways of formatting strings in Python: # With the "str.format()" function # Using the Old Python way through the "%" operator # Formatting strings that contain strings old_str = "%s %s" % ("Hello", "World") new_str = "{} {}".format("Hello", "World") print(old_str) print(new_str) # Formatting strings that contain integers old_str = "%d and %d" % (1, 2) new_str = "{} and {}".format(1, 2) print(old_str) print(new_str) # Formatting strings that contain float old_str = "%f" % (3.141592653589793) new_str = "{:f}".format(3.141592653589793) print(old_str) print(new_str)
true
380ac40a79d2cea253904d211f33ec41ae9d99f0
dallinsuggs/CS241
/DSweek07.py
273
4.125
4
def fibonnaci(number): if number <= 0: return 0 elif number == 1: return 1 elif number == 2: return 2 return fibonnaci(number - 1) + fibonnaci(number - 2) for i in range(0,20): print("Fibonacci({}) = {}".format(i,fibonnaci(i)))
false
b315f178386a8072670a9087e791c0f978cd2212
stianbm/tdt4113
/03_crypto/ciphers/cipher.py
1,223
4.28125
4
"""The file contains the parent class for different ciphers""" from abc import abstractmethod class Cipher: """The parent class for the different ciphers holding common attributes and abstract methods""" _alphabet_size = 95 _alphabet_start = 32 _type = '' @abstractmethod def encode(self, text, cipher_key): """Encode a text string using it's cipher and key and return encoded text""" return text @abstractmethod def decode(self, text, cipher_key): """Decode a text string using it's cipher and key and return decoded text""" return text def verify(self, text, cipher_key): """Check if the encoded - then decoded text is the same as original""" print('Type: ', self._type) print('Text: ', text) encoded = self.encode(text, cipher_key) print('Encoded: ', encoded) decoded = self.decode(encoded, cipher_key) print('Decoded: ', decoded) if text == decoded: print('VERIFIED') print() return True print('NOT VERIFIED') print() return False @abstractmethod def possible_keys(self): """Return all possible keys"""
true
a84b2ca62ea2a64073f5a54f8ea19657079819ad
smh128/jtc_class_code
/challenges/04_NBA /nba3pts.py
2,821
4.3125
4
print("Challenge 2.1:") jamal_murray_3pts_made = 46 Vanvleet_3pts_made = 43 Harden_3pts_made = 39 print("Challenge 2.2:") print("In the 2020 NBA playoffs Jamal Murray made this many 3 point shots:") print(jamal_murray_3pts_made) print("In the 2020 NBA playoffs Fred Vanvleet made this many 3 point shots:") print(Vanvleet_3pts_made) print("In the 2020 NBA playoffs James Harden made this many 3 point shots:") print(Harden_3pts_made) print("Challenge 2.3: Store the number of three point shot attempts in variables for each player") Jamal_Murray_3pts_attempts = 130 Vanvleet_3pts_attempts = 110 Harden_3pts_attempts = 117 print(Jamal_Murray_3pts_attempts) print(Vanvleet_3pts_attempts) print(Harden_3pts_attempts) print("Challenge 2.4: Build on your print statement") print("In the 2020 NBA playoffs Jamal Murray made this many 3 point attempts:") print(Jamal_Murray_3pts_attempts) print("In the 2020 NBA playoffs Fred Vanvleet made this many 3 point attempts:") print(Vanvleet_3pts_attempts) print("In the 2020 NBA playoffs James Harden made this many 3 point attempts:") print(Harden_3pts_attempts) # the number of three point shots for each player. E.g., output should be similar to # "In the 2020 NBA playoffs, player X made Y 3 point shots and Z 3 point shot attempts." print() print("Challenge 2.5: Calculate, store, and print the three point percentage for each player") # TODO: Calculate the three point percentage, which is given by `three points made/three point attempts` jamal_murray_3pts_percentage = 35 Vanvleet_3pts_percentage = 39 Harden_3pts_percentage = 33 # TODO: Calculate and print the 3 point percentage for James Harden print("In the 2020 NBA playoffs James Harden had the following 3 point percentage:") print(Harden_3pts_percentage) print('Challenge 3.1: Print out the paragraph but with only 1 sentence per line') # TODO: Print the giant chunk of text out using escape characters so each sentence comes out on a new line print('Challenge 3.2: Print out the paragraph but with only 1 sentence per line') # TODO: As above, orint out the paragraph with only 1 sentence per line, and all in upper case print('Challenge 3.3: Make a boolean variable indicating whether you think the Lakers are the best NBA team') # TODO: make a variable called `lakers_are_best` to indicate this # TODO: print out the variable in an f-string to convey your opinion on the lakers print('Challenge 3.4: Type Conversion') # TODO: Convert your `lakers_are_best` variable to an integer, and print it out. # TODO: Convert your `lakers_are best` variable to a float, and print it out print('Challenge 3.5: Type Conversion Part 2') # TODO: Take each player's three point percentage (from part 2.5) and convert it to a string, then print it out. # TODO: Take each player's three point percentage (from part 2.5) and convert it to an integer, then print it out.
false
9c20ceec0fdccd3bc2bb92815e56b7a99855058a
cindy859/COSC2658
/W2 - 1.py
721
4.15625
4
def prime_checker(number): assert number > 1, 'number needs to be greater than 1' number_of_operations = 0 for i in range(2, number): number_of_operations += 3 #increase of i, number mod i, comparision if (number % i) == 0: return False, number_of_operations # returning multiple values (as a tuple) return True, number_of_operations # returning multiple values (as a tuple) numbers = [373, 149573, 1000033, 6700417] for number in numbers: (is_prime, number_of_operations) = prime_checker(number) if is_prime: print(number, "is prime") else: print(number, "is not prime") print('Number of operations:', number_of_operations) print('')
true
bdc290072854219917fe8a24ef512b26d38e93f9
TecProg-20181/02--matheusherique
/main.py
1,779
4.25
4
from classes.hangman import Hangman from classes.word import Word def main(): guesses = 8 hangman, word = Hangman(guesses), Word(guesses) secret_word, letters_guessed = hangman.secret_word, hangman.letters_guessed print'Welcome to the game, Hangman!' print'I am thinking of a word that is', len(secret_word), ' letters long.' word.join_letters(secret_word) print'-------------' while not hangman.is_word_guessed() and guesses > 0: print'You have ', guesses, 'guesses left.' hangman.stickman(guesses) available = word.get_available_letters() for letter in available: if letter in letters_guessed: available = available.replace(letter, '') print'Available letters', available letter = raw_input("Please guess a letter: ") if letter in letters_guessed: letters_guessed.append(letter) guessed = word.letter_guessed(secret_word, letters_guessed) print'Oops! You have already guessed that letter: ', guessed elif letter in secret_word: letters_guessed.append(letter) guessed = word.letter_guessed(secret_word, letters_guessed) print'Good Guess: ', guessed else: guesses -= 1 letters_guessed.append(letter) guessed = word.letter_guessed(secret_word, letters_guessed) print"Oops! That letter is not in my word: ", guessed print'------------' else: if hangman.is_word_guessed(): hangman.stickman(guesses) print'Congratulations, you won!' else: hangman.stickman(guesses) print'Sorry, you ran out of guesses. The word was ', secret_word, '.' main()
true
a836c740813a8a4b99f644d9a0b889c134f172af
panxiufeng/panxftest
/python-test/base_test/ch14_struct03_set.py
574
4.15625
4
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) # 删除重复的 print("orange" in basket) # 两个集合间的运算 a = set('abracadabra') b = set('alacazam') print(a) print(b) print(a - b) # a和b的差集 print(a | b) # a和b的并集 print(a & b) # a和b的交集 print(a ^ b) # a和b中不同时存在的元素 print('------------------------------') # 类似列表推导式,同样集合支持集合推导式(Set comprehension): a = {x for x in 'abracadabra' if x not in 'abc'} print(a)
false
0efc2e80426f7e553442765462dfec8f4415ea67
panxiufeng/panxftest
/python-test/base_test/ch12_iter.py
1,711
4.1875
4
# 字符串,列表或元组对象都可用于创建迭代器: list=[1,2,3,4] it = iter(list) # 创建迭代器对象 print (next(it)) # 输出迭代器的下一个元素 print (next(it)) print ("---------") # 迭代器对象可以使用常规for语句进行遍历 list=[1,2,3,4] it = iter(list) # 创建迭代器对象 for x in it: print (x, end=" ") print() print ("---------") # 也可以使用 next() 函数: # import sys # 引入 sys 模块 # # list=[1,2,3,4] # it = iter(list) # 创建迭代器对象 # # while True: # try: # print (next(it)) # except StopIteration: # sys.exit() # StopIteration 异常用于标识迭代的完成,防止出现无限循环的情况,在 __next__() 方法中我们可以设置在完成指定循环次数后触发 StopIteration 异常来结束迭代。 print ("---------") # 生成器 在 Python 中,使用了 yield 的函数被称为生成器(generator) # 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。 # 在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。 import sys def fibonacci(n): # 生成器函数 - 斐波那契 a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 while True: try: print (next(f), end=" ") except StopIteration: sys.exit()
false
327d89760aca774d4cf1019eda5c88cadc469502
arossbrian/my_short_scripts
/multiplier.py
405
4.15625
4
##This is a multiply function #takes two figures as inputs and multiples them together def multiply(num1, num2): multiplier = num1 * num2 return multiplier input_num1 = input("Please enter the first value: ") input_num2 = input("Enter the Second Value: ") ##input_num1 = int(input_num1) ##input_num2 = int(input_num2) Answer = multiply(int(input_num1), int(input_num2)) print(Answer)
true
f8b914676da0c034a908c3e440313e6633264068
arossbrian/my_short_scripts
/shoppingbasketDICTIONARIES.py
492
4.15625
4
print (""" Shopping Basket OPtions --------------------------- 1: Add item 2: Remove item 3: View basket 0: Exit Program """) shopping_basket = {} option = int(input("Enter an Option: ")) while option != 0: if option == 1: item = input("Add an Item :") qnty = int(input("Enter the quantity: ")) for item, qnty in shopping_basket.items(): print(item) #print(shopping_basket) #elif option == 2:
true
36ec1104b30f90707920614405bc83cd5a2f7e40
yeonsu100/PracFolder
/NewPackage01/LambdaExample.py
601
4.5
4
# Python program to test map, filter and lambda # Function to test map def cube(x): return x ** 2 # Driver to test above function # Program for working of map print "MAP EXAMPLES" cubes = map(cube, range(10)) print cubes print "LAMBDA EXAMPLES" # first parentheses contains a lambda form, that is # a squaring function and second parentheses represents # calling lambda print(lambda x: x ** 2)(5) # Make function of two arguments that return their product print(lambda x, y: x * y)(3, 4) print "FILTER EXAMPLE" special_cubes = filter(lambda x: x > 9 and x < 60, cubes) print special_cubes
true
c30cd41b41234884aea693d3d0893f2889bd5f1d
deeptivenugopal/Python_Projects
/edabit/simple_oop_calculator.py
605
4.125
4
''' Simple OOP Calculator Create methods for the Calculator class that can do the following: Add two numbers. Subtract two numbers. Multiply two numbers. Divide two numbers. https://edabit.com/challenge/ta8GBizBNbRGo5iC6 ''' class Calculator: def add(self,a,b): return a + b def subtract(self,a,b): return a - b def multiply(self,a,b): return a * b def divide(self,a,b): return a // b calculator = Calculator() print(calculator.add(10, 5)) print(calculator.subtract(10, 5)) print(calculator.multiply(10, 5)) print(calculator.divide(10, 5))
true
6598f0f714711ea063ef0f160e65847cc9dfa295
fiberBadger/portfolio
/python/collatzSequence.py
564
4.15625
4
def collatz(number): if number % 2 == 0: print(number // 2) return number // 2 else: print(3 * number + 1) return 3 * number + 1 def app(): inputNumber = 0 print('Enter a number for the collatz functon!') try: inputNumber = int(input()) except (ValueError, UnboundLocalError): print('invalid number') if not inputNumber or inputNumber < 0: print('Enter an absolute number!') else: while inputNumber != 1: inputNumber = collatz(inputNumber) app()
true
f416c4993cfc11e8ca6105d48168d42952f55aa3
fiberBadger/portfolio
/python/stringStuff.py
813
4.125
4
message = 'This is a very long message' greeting = 'Hello' print(message); print('This is the same message missing every other word!'); print(message[0:5] + message[8:9] + ' ' + message[15:19]); print('The length of this string is: ' + str(len(message)) + 'chars long'); print('This is the message in all lower case ' + message.lower()); print('This is the message in all upper case ' + message.upper()); print('This message has: ' + str(message.count('s')) + ' S\'es'); print('The word "very" starts at' + str(message.find('very'))); print('The word long is replaced' + message.replace('Long', 'Short')); greeting += ' World' print('This string is contatianted: ' + greeting); print('This is a formated string:' + '{}, {} !'.format('Hello', 'World')); print('This is a "F" string' + f'{greeting}, {message}');
true
c4acbc2cc9cbbe534af749af6b6ceb44ee854b6f
kcthogiti/ThinkPython
/Dice.py
352
4.1875
4
import random loop_control = "Yes" Min_num = int(raw_input("Enter the min number on the dice: ")) Max_num = int(raw_input("Enter the Max number on the dice: ")) def print_rand(): return random.randrange(Min_num, Max_num) while loop_control == "Yes": print print_rand() loop_control = raw_input("Do you want to continue? Yes or No: ")
true
d8da2f3fe23acf33367543f0655f03b3dc71e9ce
yuukou3333/study-python
/55knock_py/knock_29.py
852
4.21875
4
# 辞書(キーの存在確認,get) d = {'apple':10, 'grape':20, 'orange':30} # if 'apple' in list(d.keys()): # .get(キー)は辞書にキーが存在するかどうかを判断し、存在する場合はキーに対応する値、存在しない場合はNoneを返す # .get(キー, 値)は辞書にキーが存在するかどうかを判断し、存在する場合はキーに対応する値、存在しない場合は第二引数で指定した値を返す # 例 # d.get('pine') # => None # 辞書に指定した値を反映させたい時は、 # d['pineapple'] = d.get('pineapple', '-1')のように辞書のキーを指定して代入することで辞書に格納することができる。 # 模範解答 ==================================== d['apple'] = d.get('apple', '-1') d['pineapple'] = d.get('pineapple', '-1') print(d)
false
4fb1c11f72c165f881348a2145b6130346c15bcc
L200184134/Praktikum-Algopro
/Activity 4. Data Type (shell).py
2,307
4.125
4
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> Nama = "Mahardhika Bathiarto Dim Zarita" >>> NIM = 134 >>> Tinggi = 1.68 >>> Berat = 57 >>> TahunLahir = 2000 >>> Aku = (TahunLahir, Berat, Tinggi, NIM, Nama) >>> Data = [TahunLahir, Berat, Tinggi, NIM, Nama] >>> type (Aku) <class 'tuple'> >>> ##this command to know what is the type of Aku, Why the python print <calss 'tuple'> ? because Aku is type tuple. >>> Aku [0] 2000 >>> ##this command call word in the tuple. why just 2000 ? why not the other ? because in tuple the row of object and it is start (0,1,2,...),if you write Aku[0] so the python print 2000. >>> a = NIM % 4 ; Aku [a] 1.68 >>> ##this command slice word in the tuple. why 1.68 ? because value of a is 2. so Aku[a] call the row 2 on the Aku is Tinggi. >>> type (Aku[a]) <class 'float'> >>> ##this command to know what is type of Aku[a], type is float because value Aku[a] is 1,68. >>> Aku[a:4] (1.68, 134) >>> ##this command slice word in the tuple. why 1.68 and 134 ? because value of Aku [a:4] is Tinggi and NIM.so the python print 1.68,134. >>> type(Aku[4]) <class 'str'> >>> ##this command to know what is type of Aku[4]. why class string ? because in type Aku[4] is Nama. so value nama is "Mahardhika Bathiarto Dim Zarita", it's type string. >>> Aku[0] = "ok" Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> Aku[0] = "ok" TypeError: 'tuple' object does not support item assignment >>> ##because tuple element is can not be changed >>> type(Data) <class 'list'> >>> ##this command to know what is the type of Data. >>> type(Data[4]) <class 'str'> >>> ##this command to know what is type of Data[4]. because in the Data[4] is Nama, so the python print type is class 'str'. >>> Data[4][5] 'd' >>> ##because there is d in fifth object. >>> Data[4][a:6] 'hard' >>> ##because Data[4] is nama, and [a:6] is value of a and then slice "Ma", so started by h until d.it's "hard". >>> Data[0] = 'ok'; Data ['ok', 57, 1.68, 134, 'Mahardhika Bathiarto Dim Zarita'] >>> ##because the first object already to changed with 'ok'. >>> Data[-a] 134 >>> ##because the second last in the Data is NIM. >>> range(a) range(0, 2) >>> ##because in the "a" data there is only 2 object.
false
6275eae9107c2d92a9df5f2c8749389434917a82
SDrag/weekly-exercises
/exercise1and2.py
1,450
4.375
4
################### ### Exercise 1: ### ################### def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i # Test the function with the following value. x = 18 ans = fib(x) print("Fibonacci number", x, "is", ans) ### My name is Dragutin, so the first and last letter of my name (D + N = 4 + 14) give the number 18. The 18th Fibonacci number is 2584. ################### ### Exercise 2: ### ################### def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i name = "Sreckovic" first = name[0] last = name[-1] firstno = ord(first) lastno = ord(last) x = firstno + lastno ans = fib(x) print("My surname is", name) print("The first letter", first, "is number", firstno) print("The last letter", last, "is number", lastno) print("Fibonacci number", x, "is", ans) ### My surname is Sreckovic ### The first letter S is number 83 ### The last letter c is number 99 ### Fibonacci number 182 is 48558529144435440119720805669229197641 ### ord() function in Python: Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.
true