blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ea021e6da43d11fa8ce3f4d40bb000bcf3a078a8
RodrigoPenedo/UsefulPython
/Algorithms/InsertionSort.py
409
4.15625
4
def InsertionSort(array): for i in range(1, len(array)): current = array[i] number = i-1 while number >=0 and current < array[number] : array[number+1] = array[number] number -= 1 array[number+1] = current #print(array) return array array = [20, 21, 30, 7, 19, 10, 5] print(InsertionSort(array))
true
8daba7389dc26afa87c05397f504da786b983af4
santihadad/python-course
/tuples.py
508
4.21875
4
# Definiendo tuplas x = (1, 2, 3, 4, 5) # print(x) # print(type(x)) # months = ('January', 'Febrary', 'March') # print(months) # Creando tuplas a partir de la funcion "Tupla", al igual que las listas # y = tuple((1, 2, 3)) # print(y) # Metodos de una tupla # print(dir(y)) #Tuplas de un solo elemento # z = (1) # print(type(z)) # a = (1,) # Debemos colocar una coma si queremos una tupla de un solo elemento # print(type(a)) #Acceder a un elemento #print(x[4]) # Eliminar una tupla # del x # print(x)
false
58f5fbe2ed1417afd3954439a35004257e37e51c
santihadad/python-course
/conditionals.py
1,081
4.28125
4
# Vamos a empezar a ver las estructuras condicionales, interectuando valores con el usuario y comparando parametros. Usaremos la estructura "if" # que solo devulve valores booleanos (True or False). # Para comparar se usan dos simbolos de igualdad (==) # 3==3 ---> True #Vamos a comparar el valor asignado a X con 30, Si es menor va a imprimir el mensaje # x = 30 # if x < 20: # print("x is less than 20") # else: # print("x is greater than 20") # color = "red" # if color == "red": # print("Color is red") # elif color == "blue": # print("Color is blue") # else: # print("Any color") # name = "Ryan" # lastname = "Carter" # if name == "Jhon": # if lastname == "Carter": # print("You are Jhon Carter") # else: # print("You are not Jhon Carter") # else: # print("You are not Jhon") #Utilizando los operador de comparacion # x = 3 # if x > 2 and x < 20: # print("X is greater than 2 and lesser than 20") # elif x > 2 and x > 20: # print("X is greater than 2 and greater than 20") # else: # print("X is lesser than 2")
false
6a1c682b853b466e1c351c14d0e18730925c008b
ruizsugliani/Algoritmos-1-Essaya
/Unidad 9/9_3.py
1,405
4.1875
4
def agenda(): ''' El programa solicita al usuario que ingrese nombres, si el nombre se encuentra debe mostrar el teléfono y opcionalmente permitir modificarlo si no es correcto. Si el nombre no se encuentra, debe permitir ingresar el telefono correspondiente. El usuario puede utilizar la cadena "*" para salir del programa. ''' agenda = {} while True: nombre = input("Ingrese un nombre, o * para salir: ") if nombre == "*": break if nombre not in agenda: print("Persona no agendada") numero = input(f"Ingrese el telefono para {nombre}: ") if numero == "": print() continue while not numero.isdigit() or not len(numero) != 0 or numero == " ": numero = input(f"Ingrese el telefono para {nombre}: ") agenda[nombre] = numero print(f"Nuevo telefono registrado para {nombre}, {numero}\n") continue if nombre in agenda: print(f"Telefono de {nombre} es {agenda[nombre]}") numero = input(f"Ingrese el telefono para {nombre}: ") if numero == "": print() continue agenda[nombre] = numero print(f"Telefono actualizado para {nombre}, {numero}\n") continue agenda()
false
e88a11fabb8e0c604448db82e18beb3969997b4d
ruizsugliani/Algoritmos-1-Essaya
/Unidad 12/12_3.py
1,260
4.21875
4
""" a) Crear una clase Vector, que en su constructor reciba una lista de elementos que serán sus coordenadas. En el método __str__ se imprime su contenido con el formato [x,y,z] b) Implementar el método __add__ que reciba otro vector, verifique si tienen la misma cantidad de elementos y devuelva un nuevo vector con la suma de ambos. Si no tienen la misma cantidad de elementos debe levantar una excepción. c) Implementar el método __mul__ que reciba un número y devuelva un nuevo vector, con los elementos multiplicados por ese número. """ class Vector: #a) def __init__(self, vector): self.vector = vector def __str__(self): return f'{"".join(str(self.vector).split(" "))}' #b) def __add__(self, otro): if len(self.vector) == len(otro.vector): nuevo_vector = [] for i in range(len(self.vector)): nuevo_vector.append(self.vector[i] + otro.vector [i]) return Vector(nuevo_vector) raise Exception("Vectores no tienen la misma cantidad de elementos.") #c) def __mul__(self, numero): nuevo_vector = [] for i in self.vector: nuevo_vector.append(i * numero) return Vector(nuevo_vector)
false
e5ca12b6f4a8bbea235afb53bcad237e7891e39c
ruizsugliani/Algoritmos-1-Essaya
/PARCIALITOS/P3/pila.py
1,002
4.3125
4
class Pila: """Representa una pila con operaciones de apilar, desapilar y verificar si está vacía.""" def __init__(self): """Crea una pila vacía.""" self.items = [] def __str__(self): """Muestra por pantalla la pila indicando el tope.""" return f"{self.items} <--TOPE" def ver_tope(self): """Muestra el tope de la pila""" if not self.esta_vacia(): return self.items[-1] def apilar(self, x): """Apila el elemento x.""" self.items.append(x) def desapilar(self): """Desapila el elemento x y lo devuelve. Si la pila está vacía levanta una excepción.""" if self.esta_vacia(): raise ValueError("La pila está vacía") return self.items.pop() def esta_vacia(self): """Devuelve True si la lista está vacía, False si no.""" if len(self.items) == 0: return True return False
false
a1f47e5f59e85a5ff88cffd7fea0fe9a8ee18d50
niteshkrsingh51/hackerRank_Python_Practice
/basic_data_types/nested_lists.py
668
4.21875
4
#Print the name(s) of any student(s) having the second lowest grade in. If there are multiple students, #order their names alphabetically and print each one on a new line. if __name__ == '__main__': my_list = [] scores = set() second_lowest_names = [] for _ in range(int(input())): name = input() score = float(input()) item = name,score my_list.append([name, score]) scores.add(score) second_lowest = sorted(scores) [1] for name, score in my_list: if score == second_lowest: second_lowest_names.append(name) for name in sorted(second_lowest_names): print(name, end='\n')
true
3e2ca2e8dd2ffeeb15ba524f58b96de1a367ea99
mohan-sharan/python-programming
/Loop/loops_4.py
340
4.125
4
#What is a break statement? #It stops the execution of the statement in the current/innermost loop and #starts executing the next line of code after the block. x = 20 while x > 10: print("x =", x) x -= 1 if x == 15: break print("BREAK") ''' OUTPUT: x = 20 x = 19 x = 18 x = 17 x = 16 BREAK '''
true
5383d421e4fc403d9149aa1a96c3c307e8b0ff44
mohan-sharan/python-programming
/Misc/factorial_1.py
765
4.4375
4
#FACTORIAL #Denoted by n! #where n = non-negative integer #is the product of all positive integers less than or equal to n. #For example: 4! = 4*3*2*1 = 24 n = int(input("Enter a number to find its factorial: ")) fact = 1 if (n == 0): print("The Factorial of 0 is 1.") elif (n < 0): print("INVALID! Factorial doesn't exist for negative numbers.") else: for i in range(1, n+1): fact = fact * i print("{}! is {}.".format(n, fact)) ''' OUTPUT 1: Enter a number to find its factorial: -4 INVALID! Factorial doesn't exist for negative numbers. ''' ''' OUTPUT 2: Enter a number to find its factorial: 0 The Factorial of 0 is 1. ''' ''' OUTPUT 3: Enter a number to find its factorial: 6 6! is 720. '''
true
41edeab8831e9eede53ecbd21576e9e6b8fa4171
mohan-sharan/python-programming
/Tuple/tuples_1.py
801
4.34375
4
#Tuples myTuple1 = ("07-06-1969", "01-23-1996") print(myTuple1[0]) print(myTuple1[1]) ''' OUTPUT: 07-06-1969 01-23-1996 ''' #del doesn't work on a tuple. The output below shows what happens when del is called. del(myTuple1[0]) ''' OUTPUT: File "C:/Users/PycharmProjects/tutorial/basics.py", line 5, in <module> del(myTuple1[0]) TypeError: 'tuple' object doesn't support item deletion Process finished with exit code 1 ''' myTuple2 = ("Smashing Pumpkins", "Foo Fighters", "Fleetwood Mac", "Matchbox Twenty", "Silversun Pickups") print("The length of the tuple is:", len(myTuple2)) for x in myTuple2: print(x, end=" ") ''' OUTPUT: The length of the tuple is: 5 Smashing Pumpkins Foo Fighters Fleetwood Mac Matchbox Twenty Silversun Pickups '''
true
8d356b8ca92e70413f209bdced8a1c57d8d86315
mohan-sharan/python-programming
/Misc/division_by_zero.py
893
4.1875
4
#a simple program to demonstrate the handling of exceptions. #try-except block. a = int(input("Enter a number:\n")) b = int(input("Enter another number:\n")) c = a/b print("\na/b = ", c) ''' OUTPUT 1: Enter a number: 5 Enter another number: 2 a/b = 2.5 Process finished with exit code 0 OUTPUT 2: Enter a number: 5 Enter another number: 0 Traceback (most recent call last): File "C:/Users/PycharmProjects/tutorial/basics.py", line 4, in <module> c = a/b ZeroDivisionError: division by zero Process finished with exit code 1 ''' a = int(input("Enter a number:\n")) b = int(input("Enter another number:\n")) try: c = a/b print("\na/b = ", c) except ZeroDivisionError: print("Divide By Zero Error!") ''' OUTPUT: Enter a number: 5 Enter another number: 0 Divide By Zero Error! Process finished with exit code 0 '''
true
c5d167db5dea9485a6091a04c40fa3ed9df7eff7
AGagliano/HW02
/HW02_ex03_05.py
2,631
4.375
4
#!/usr/bin/env python # HW02_ex03_05 # This exercise can be done using only the statements and other features we # have learned so far. # (1) Write a function that draws a grid like the following: # + - - - - + - - - - + # | | | # | | | # | | | # | | | # + - - - - + - - - - + # | | | # | | | # | | | # | | | # + - - - - + - - - - + # Hint: to print more than one value on a line, you can print a comma-separated # sequence: # print '+', '-' # If the sequence ends with a comma, Python leaves the line unfinished, so the # value printed next appears on the same line. # print '+', # print '-' # The output of these statements is '+ -'. # A print statement all by itself ends the current line and goes to the next line. # (2) Write a function that draws a similar grid with four rows and four columns. ################################################################################ # Write your functions below: # Body #Symbols used in the graph. node = '+' v_edge = '|' h_edge = '-' #Function for printing a set of any four symbols side by side, with continuous printing. def print_four(x): print x, x, x, x, #Function for printing a single segment of an edge row. def print_edge_seg(): print node, print_four(h_edge) #Function for creating a set of four segments to create any row. def call_four(f): f() f() f() f() #Function for printing the ending node of an edge row #and prompting print to continue on the following row. def print_right_edge_node(): print node #Function for printing an edge row. def draw_edge_row(): call_four(print_edge_seg) print_right_edge_node() #Function for printing a single segment of a body row. def print_body_seg(): print v_edge, print_four(' ') #Function for printing the ending node of a body row #and prompting print to continue on the following row. def print_right_node(): print v_edge #Function for printing a body row. def draw_body_row(): call_four(print_body_seg) print_right_node() #Function to print a block of rows. def draw_block(): draw_edge_row() call_four(draw_body_row) #Function to print grid. def draw_grid(): call_four(draw_block) draw_edge_row() # Write your functions above: ################################################################################ def main(): """Call your functions within this function. When complete have two function calls in this function: two_by_two() four_by_four() """ print("Hello World!") draw_grid() if __name__ == "__main__": main()
true
7559888242932f2ccb97df79a8a585b7885dba88
Olga20011/Django-ToDoList
/API/STACKS/stacks.py
580
4.15625
4
#creating a stack def create_stack(): stack=[] return stack #creating an empty stack def create_empty(stack): return len(stack) #adding an item toa stack def push(stack,item): stack.append(item) print("pushed item: "+ item) #Removing an element def pop(stack): if (create_empty(stack)): return "stack is empty" return stack.pop() stack = create_stack() push(stack, str(1)) push(stack, str(2)) push(stack, str(3)) push(stack, str(4)) print("popped item: " + pop(stack)) print("stack after popping an element: " + str(stack))
true
c5da8483fc03d98e0272c42bdc2fbe5bbd78502f
informatik-mannheim/PyTorchMedical-Workshop
/basic_templates/pythonBasics/loops.py
897
4.625
5
def whileLoop(): i = 0 while i < 3: print(i) i = i+1 whileLoop() def forLoop_OverElements(elements): for element in elements: print(element) x = ["a", "b", "c"] forLoop_OverElements(x) def forLoop_usingLength(elements): for i in range(len(elements)): print("elements[{0}] = {1}".format(i, elements[i])) forLoop_usingLength(x) def forLoop_overElements_WithoutUsingThem(elements): """ Coding conventions use _ as a throwaway variable other uses of _: - store the value of last executed expression - reference internationalization library - see https://stackoverflow.com/a/5893946/10761360 """ for _ in range(len(elements)): # don't use _ at all, e.g. if you wanted to print something x times: print("iteration") forLoop_overElements_WithoutUsingThem(x)
true
cc001ba5beda435c8f915efc1cfb43d75ab55b04
ShamSaleem/Natural-Language-Processing-Zero-to-Hero
/Filtering text.py
493
4.28125
4
#Filtering a text: This program computes the vocabulary of a text, then removes all items #that occur in an existing wordlist, leaving just the uncommon or misspelled words import nltk def unusual_words(text): text_vocab = set(w.lower() for w in text if w.isalpha()) english_vocab = set(w.lower() for w in nltk.corpus.words.words()) unusual = text_vocab.difference(english_vocab) print(sorted(unusual)) unusual_words(nltk.corpus.gutenberg.words('austen-sense.txt'))
true
5acfeceb07de8e7b6c1bc0edf360ab45c0a1cef8
Jessica-A-S/Practicals-ProgrammingI
/PartBTask3.py
438
4.125
4
def main(): age = int(input("Enter your age: ")) enrolled = input("Are you enrolled to vote(Y/N)? ").upper() if age >= 18: age = True if enrolled == "Y": enrolled = True else: enrolled = False else: enrolled = False if age and enrolled: print("You are enrolled to vote") else: print("You are not eligible to vote") main()
true
7cc14a4d00bc0de076a043e46a12c3d3ff55f1fd
Steven24K/First-Python
/Full_circle.py
598
4.34375
4
def DrawCircle(diameter): import math center_x = diameter/2 center_y = diameter/2 circle = "" for y in range(int(diameter+1)): for x in range(int(diameter+1)): distance = math.sqrt((center_x - x )**2 + (center_y - y)**2) distance = math.ceil(distance) if distance <= diameter/2: circle += "*" else: circle += "#" circle += "\n" return circle x = int(input("Grote van de cirkel: ")) print(DrawCircle(x))
false
25d1b68218f4b6d078380cfcf61b8e52b35970dc
nicolemhfarley/short-challenges
/common_array_elements.py
1,930
4.21875
4
""" Given two arrays a1 and a2 of positive integers find the common elements between them and return a set of the elements that have a sum or difference equal to either array length. All elements will be positive integers greater than 0 If there are no results an empty set should be returned Each operation should only use two elements Examples a1 = [1, 2, 3, 4, 5, 6] a2 = [1, 2, 4, 6, 7, 8, 9, 10] should return {2, 4, 6} because all three integers exist in both arrays and a1 has a length of 6 (2+4) and a2 has a length of 8 (2+6). a1 = [1, 2, 3, 5, 10, 15] a2 = [1, 2, 3, 4, 5, 6, 10, 12, 15, 16] should return {1, 5, 15} because all 3 integers exist in both arrays and a1 has a length of 6 (1+5) and a2 has a length of 10 (15-5). """ def common_el(a1, a2): # first compare all elements in both arrays. add any common elements to a list, then filter common = [] results = [] for i in range(len(a1)): for j in range(len(a2)): if a2[j] == a1[i]: common.append(a2[j]) if common == None: return {} for i in range(len(common)): for j in range(len(common)): if ((common[j] + common[i] == len(a1)) or (common[j] + common[i] == len(a2))) and j != i: results.append(common[j]) results.append(common[i]) elif ((common[j] - common[i] == len(a1)) or (common[i] - common[j] == len(a1))) and j != i: results.append(common[j]) results.append(common[i]) elif ((common[j] - common[i] == len(a2)) or (common[i] - common[j] == len(a2))) and j != i: results.append(common[j]) results.append(common[i]) results = set(results) return results arr1 = [1, 2, 3, 4, 5, 6] arr2 = [1, 2, 4, 6, 7, 8, 9, 10] a1 = [1, 2, 3, 5, 10, 15] a2 = [1, 2, 3, 4, 5, 6, 10, 12, 15, 16] x = common_el(a1, a2) print(x)
true
94f38973ce467e5a357b5d8b2c28c3091dfe91c5
sanjipmehta/Enumerate
/enumerate.py
390
4.15625
4
#First i want to print position and and its value without using enumerate pos=0 name=['google','amazon','Dell','nasa'] for x in name: print(pos,'is the index of:',name[pos]) pos+=1 pos=0 for x in name: print(f" {pos}-------->{name[pos]}") pos+=1 #Now by using enumerate function name=['google','amazon','Dell','nasa'] for pos,name in enumerate(name): print(pos,"----------->",name)
true
acd6dfc6362f466a4b77b5b8cd1217fe65a8fc15
ZuDame/studyForPython
/design_patterns/dahua/factory_method.py
1,445
4.15625
4
""" 工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪个类。 工厂方法使一个类的实例化延迟到其子类。 代码示例:学习雷锋好榜样,继承雷锋精神的大学生和社区的构建:: >>> factory = UndergraduateFactory() >>> student = factory.create_leifeng() >>> student.buyrice() 买米 >>> student.sweep() 扫地 >>> student.wash() 洗衣 工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行。 """ import abc class LeiFeng: def sweep(self): print('扫地') def wash(self): print('洗衣') def buyrice(self): print('买米') class IFactory(abc.ABC): @abc.abstractmethod def create_leifeng(self): """工厂接口""" class Undergraduate(LeiFeng): """继承雷锋精神的大学生类""" class Volunteer(LeiFeng): """继承雷锋精神的社区志愿者类""" class UndergraduateFactory(IFactory): """大学生工厂""" def create_leifeng(self): return Undergraduate() class VolunteerFactory(IFactory): """社区志愿者工厂""" def create_leifeng(self): return Volunteer() if __name__ == '__main__': factory = UndergraduateFactory() # 要换成 “社区志愿者”,修改这里就可以了 student = factory.create_leifeng() student.buyrice() student.sweep() student.wash()
false
020c8ab5b314eebea1aed3cfd0548f744d76aad3
seowteckkueh/Python-Crash-Course
/10.7_addition_calculator.py
378
4.15625
4
while True: try: num1=input("please enter the first number: ") break except ValueError: print("That's not a number, please try again") while True: try: num2=int(input("please enter the second number: ")) break except ValueError: print("That's not a number, please try again") total=num1+num2 print(total)
true
6dd0731adde536a8be2b900a6e0cb0ece6fb15b0
seowteckkueh/Python-Crash-Course
/5.9_no_users.py
683
4.15625
4
usernames=['admin','ben','poppy','alice','emily','jane'] if usernames: for username in usernames: if username=='admin': print("Hello admin, would ou like to see a status report?") else: print("Hello "+username.title()+" thank you for logging in again.") else: print("We need to find some users!") #removed all the usernames usernames=[] if usernames: for username in usernames: if username=='admin': print("Hello admin, would ou like to see a status report?") else: print("Hello "+username.title()+" thank you for logging in again.") else: print("We need to find some users!")
true
98dd378fe9ed51cd810bba3e019d0ab5502a5694
TylerPrak/Learning-Python-The-Hard-Way
/ex7.py
843
4.40625
4
#Prints out a string print "Mary had a little lamb." #Prints out a string containg the string(%s) format character. The string is followed by a '%' and a string instead of a variable. print "Its fleece was white as %s." % 'snow' #Prints out a string print "And everywhere that Mary went." #Prints out '.' 10 times because of the * operation. print "." * 10 # what'd that do? #Create and initialize variables end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # watch that comma at the end. try removing it to see what happens #Prints out the variables we created earlier. The comma at the end of the line makes it so that the next thing printed is inline. print end1 + end2 + end3 + end4 + end5 + end6, print end7 + end8 + end9 + end10 + end11 + end12
true
22543f81b1b52ab248d11f39b6d4003a438a1d68
d3r3k6/PyPraxy
/listProjectRefactor.py
355
4.28125
4
# The task is to Write a function that takes a list value as an argument and return #a string with all the items separated by a comma and a space, with and inserted before the last items newList = ['apples', 'bananas', 'tofu', 'cats'] def convert(list): list = newList list[-1] = 'and ' + str(list[-1]) +'.' print(', ' .join(list)) convert(newList)
true
1ba7e0187c1800f680d5f80dfd3698b81304351d
developergaurav-exe/Minimal-Python-Programs
/PythonPrograms/largest no.py
334
4.21875
4
n1=int(input('number1: ')) n2=int(input('number2: ')) n3=int(input('number3: ')) #conditions if n1>n2: if n1>n3: largest=n1 else: largest=n3 else: if n2>n3: largest=n2 else: largest=n3 #to print largest no print('largest no: ',largest)
false
4fed83ae1ef25bef17f187b6402c3b43d8435a25
Krishna219/Fundamentals-of-computing
/Principles of Computing (Part 1)/Week 1/2048 (Merge).py
1,731
4.375
4
""" Merge function for 2048 game. """ def shift_to_front(lst): """ Function that shifts all the non-zero entries of the list 'line' to the front Exactly shifts all the zeros to the end """ for index in range(0, len(lst) - 1): #if an element is zero just swap it with the number next to it if lst[index] == 0: lst[index] = lst[index + 1] lst[index + 1] = 0 #The following code checks if the swapped element is zero #And ensures all the non zero entries are at the front #for example [0, 0, 2, 4] the result should be [2, 4, 0, 0] #the above code alone will give [0, 2, 4, 0] dummy_index = index while dummy_index > 0: if lst[dummy_index - 1] == 0: lst[dummy_index - 1] = lst[dummy_index] lst[dummy_index] = 0 dummy_index -= 1 return lst def merge(line): """ Function that merges a single row or column in 2048. """ line = list(shift_to_front(list(line))) #Code to add/ merge equal adjacent cells and place the sum in the first cell #replacing the second cell with zero (as per order - proceeding from left to right) for index in range(0, len(line) - 1): if line[index] == line[index + 1]: line[index] += line[index + 1] line[index + 1] = 0 line = list(shift_to_front(list(line))) return line print merge([0, 2]) #print merge([2, 0, 2, 4]) #print merge([0, 0, 2, 2]) #print merge([2, 2, 0, 0]) #print merge([2, 2, 2, 2]) #print merge([8, 16, 16, 8])
true
15694511a5cd2ff336f3a84102882be85cae8f04
zhuyoujun/DSUP
/nextGreater.py
1,268
4.21875
4
##http://www.geeksforgeeks.org/next-greater-element/ ##Given an array, print the Next Greater Element (NGE) for every element. ##The Next greater Element for an element x is the first greater element on the right side of x in array. ##Elements for which no greater element exist, consider next greater element as -1. ## ##Examples: ##a) For any array, rightmost element always has next greater element as -1. ##b) For an array which is sorted in decreasing order, all elements have next greater element as -1. ##c) For the input array [4, 5, 2, 25}, the next greater elements for each element are as follows. ## ##Element NGE ## 4 --> 5 ## 5 --> 25 ## 2 --> 25 ## 25 --> -1 ##d) For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows. ## ## Element NGE ## 13 --> -1 ## 7 --> 12 ## 6 --> 12 ## 12 --> -1 def nextGreater(lst): n = len(lst) result = [] for i in range(n): elem = lst[i] flag = 0 for j in range(i+1,n): if lst[j]>elem: result.append(lst[j]) flag = 1 break if flag == 0: result.append(-1) return result
true
38b7b604deeff14c459663458ffdef9ab238b5f2
zhuyoujun/DSUP
/priorityq.py
1,973
4.21875
4
#------------------------------------------ #Book:Data Structures and Algorithms Using Python #Author:zhuyoujun #Date:20150118 #Chapter8: Queue Structure #------------------------------------------ #Implements the PriorityQueue ADT using Python list #using the tial of list as Queue back #the head of list as Queue front class PriorityQueue: #Create an empty unbounded Priority Queue queue def __init__(self): self._theElements = list() #Judge the Queue is empty or not according to the len of list. def isEmpty(self): return len(self._theElements) == 0 #Return the number of items in Queue according to the list length. def __len__(self): return len(self._theElements) #Add item in Queue top using list method:append. def enqueue(self,item,priority): entry = _PriorityElem(item,priority) self._theElements.append(entry) #Return and remove the top item in the Queue after being sure the Queue is not empty. def dequeue(self): assert not self.isEmpty(),"The Queue is empty." highest = 0 for i in range(len(self._theElements)): if self._theElements[i]._priority < self._theElements[highest]._priority: highest = i entry = self._theElements.pop(highest) return entry._item #For debug:using overload operation __str__ def __str__(self): print "The elements in Queue is: ", for elem in self._theElements: print elem, return "" class _PriorityElem: def __init__(self,item,priority): self._item = item self._priority = priority #test Q = PriorityQueue() Q.enqueue( "purple", 5 ) Q.enqueue( "black", 1 ) Q.enqueue( "orange", 3 ) Q.enqueue( "white", 0 ) Q.enqueue( "green", 1 ) Q.enqueue( "yellow", 5 ) print"Length of Q:",len(Q) print Q.dequeue() print Q.dequeue() print Q.dequeue() print Q.dequeue() print Q.dequeue() print Q.dequeue() print Q.dequeue()
true
2cacb006786cff997765ba342ccd065f34646e81
zhuyoujun/DSUP
/vector_test.py
776
4.125
4
#------------------------------------------ #Book:Data Structures and Algorithms Using Python #Author:zhuyoujun #Date:20150101 #Chapter2: Programing Projects2.1, Vector ADT using Array class. #Test module #------------------------------------------ from vector import Vector Vect = Vector() print Vect ##for i in range(64): ## print 'before append len = ',len(Vect) ## Vect.append(i) ## print "Vect[{}] = ".format(i),Vect[i] ## print 'after append len = ',len(Vect) def print_vector(Vect): for i in range(len(Vect)): print Vect[i], print "" for i in range(8): print 'before append len = ',len(Vect) Vect.insert(0,i) #print "Vect[{}] = ".format(0),Vect[0] print_vector(Vect) print 'after append len = ',len(Vect) print ""
true
86c537414652905b52bb7310264d6e9aaf38f3be
rifqirianputra/RandomPractice
/Day 2.py
1,766
4.5
4
# exercise source: https://www.w3resource.com/python-exercises/python-basic-exercises.php # circle calculator with math.pi function import math loopcontrol = 0 while loopcontrol != 1: menuinput = input('please enter the unit to calculate the circle \n [1] Radius || [2] Diameter || [0] to exit program\n your input: ') if menuinput == '1': inputradius = (input('please enter the radius of the circle (in cm): ')) typetestradius = type(inputradius) == float typetestradius2 = type(inputradius) == int if typetestradius == True or typetestradius2 == False: r=float(inputradius) print('=======================================================') print('the area of your circle is',(math.pi*r**2), 'cm') print('the circumference of your circle is',(2*math.pi*r), 'cm') print('=======================================================') else: print('wrong input') elif menuinput == '2': inputdiameter = input('please enter the diameter of the circle (in cm): ') typetestdiameter = type(inputdiameter) == float typetestdiameter2 = type(inputdiameter) == int if typetestdiameter == True or typetestdiameter2 == False: d=float(inputdiameter) print('=======================================================') print('the area of your circle is',(math.pi*(d/2)**2), 'cm') print('the circumference of your circle is', (2*math.pi*(d/2)), 'cm') print('=======================================================') else: print('wrong input') elif menuinput == '0': print('program ended') break else: print('wrong input')
true
0e3d2dab80931668d9f27e42039ae83ca9cddd84
AdamSierzan/Learn-to-code-in-Python-3-basics
/Exercises/names_if_dict.py
713
4.34375
4
names = { "Adam" : "male", "Tom" : "male", "Jack" : "male", "Tim" : "male", "Jenny" : "female", "Mary" : "female", "Tina" : "female", "Juliet" : "female" } name = input("Type your name: ") if (name) in (names.keys()): print("Seems like we have your name on the list.") print("And its a: ", names[name], "name") else: print("Sorry, we dont have your name on the list") x = input("Do you want to add it to the list, type 'yes' or 'no': ") if x == "yes": y = input("Is that a male name? If it is type 'yes': ") if y == "yes": names[name] = "male" else: names[name] = "female" if x != "yes": print("Ok, that,s cool") print(names)
true
dd900dc5664677077bc37a0528d4163f7aa0d662
AdamSierzan/Learn-to-code-in-Python-3-basics
/Exercises/If_ex.py
232
4.1875
4
age = int(input("Enter your age:")) if age < 18: print("User is under 18, he will be 18 in:", 18- age, "year") elif age >= 18 and age < 100: print("User is 18 or over 18") elif age > 100: print("I wish you 200 years!")
true
b022e908ed5af3394d37eec7fb5b6cd453aef941
AdamSierzan/Learn-to-code-in-Python-3-basics
/2. Python_data_types/9.1.2 Data_types_Boleans.py
986
4.1875
4
#let's put to variables num1 = float(input("type the first number:")) num2 = float(input("type the second number:")) #now we can use the if statement, we do it like this # if (num1 > num2) #in the parentesis it is expecting the true or false valuable, in most programming languages we use curly braces, # and everything in the curly braces is the part of the "if", but not in python, in python we use colon ":" #the ":" makes automaticly an indetetion, so everything starting with indetetion is the part of if statemtnt if (num1 > num2): print(num1, "is grater than", num2) elif (num1 == num2): print(num1, "is equal than", num2) #so if this is true it's going to execute this code else: print(num1, "is smaller than", num2) #Here's how it works, if first statement is true, it's going to ignore the other two statements, # if it's not ttrue it's going to continue in structute, if second statemnt is not true it's going to exectue the third one, #which will be exectued
true
984eaa43e73488048b7d64f0a311850d7c2f2968
AdamSierzan/Learn-to-code-in-Python-3-basics
/Exercises/tv_series_recommendation.py
678
4.28125
4
print("Hi, whis programe will let you know what rate (0-10)," "has the tv series you want to watch:") series = { "Friends": 9, "How I met your mother": 8, "Big Bang Theory": 5, "IT:Crowd": 7, "The Office": 7 } print(list(series.keys())) print('-------------------------') name = input("Type the name of a tv series:" ) print("TV series {} has {} points in our scale.".format(name, series[name])) print('------------------------') new_series = input("Type the name of the series you want to add to list: ") new_rating = input("How would you rate it:") series[new_series] = float(new_rating) print(list(series.keys()))
true
bcaa979906f3f191865511d4d376adb57a2f552b
AdamSierzan/Learn-to-code-in-Python-3-basics
/2. Python_data_types/7.1.1 Data_types_lists_tupels ex1.py
550
4.34375
4
print("Hi this programme will generate your birth month when you eneter it") months = ("January", "February", "March", "April", "June" , "July", "August", "September", "October", "November", "December") birthday = input("Type your date of birth in the formay: DD-MM-YYYY: ") print(birthday) month = birthday[3:5] print(month) monthAsNumber = int(month) # zmieniam typ zmiennej ze stringa na liczbę print(monthAsNumber) index = monthAsNumber - 1 # - 1, bo zaczynamy liczyć od 0 print(index) monthFromTuple = months[index] print(monthFromTuple)
true
454dfc773bae0babd4a0dbaeea39201aeb0f22d0
brendanwelzien/data-structures-and-algorithms
/python/code_challenges/insertion-sort/insertion_sort.py
658
4.15625
4
def insert_sort(list): for index in range(1, len(list)): index_position = index temporary_position = list[index] while index_position > 0 and temporary_position < list[index_position - 1]: # comparing 8 and 4 for example list[index_position] = list[index_position - 1] index_position -= 1 list[index_position] = temporary_position return list if __name__ == "__main__": sortify = insert_sort([8, 4, 23, 42, 16, 15]) reverse_sort = insert_sort([20, 18, 12, 8, 5, -2]) few_unique = insert_sort([5, 12, 7, 5, 5, 7]) print(sortify) print(reverse_sort) print(few_unique)
true
bf96b609bebf534386cd7d6df28842630686fc18
avldokuchaev/testProject
/multiplicational_table.py
575
4.53125
5
# Напишите программу, выводящую на экран таблицу умножения. Первым делом она должна # спрашивать, для какого числа требуется вывести таблицу. number_for_multipl = int(input("Введите число для таблицы умножения: ")) number_1_for_multiple = int(input("Введите число до какого множителя: ")) for i in range(1, number_1_for_multiple): print(i, "* ", number_for_multipl, "=", number_for_multipl * i)
false
1c52d6473878fa04879dabed4b798aed74266201
avldokuchaev/testProject
/sell_procent.py
1,138
4.34375
4
# В магазине распродажа. На товары за 10 долларов и меньше скидка 10%, а на товары дороже 10 долларов # — 20 %. Напишите программу, которая будет запрашивать цену товара и показывать # размер скидки (10 или 20 %) и итоговую цену. cost_of_thing = float(input("Введите цену товара: ")) if cost_of_thing <= 10: cost_of_thing_with_saler = cost_of_thing - cost_of_thing * 0.1 cost_of_thing_salers = cost_of_thing * 0.1 print("Ваша скидка равна: 10%") print("Ваша скидка равна: ", round(cost_of_thing_salers, 1)) print("Цена вашего товара: ", cost_of_thing_with_saler) else: cost_of_thing_with_saler = cost_of_thing - cost_of_thing * 0.2 cost_of_thing_salers = cost_of_thing * 0.2 print("Ваша скидка равна: 20%") print("Ваша скидка равна: ", round(cost_of_thing_salers, 1)) print("Цена вашего товара: ", cost_of_thing_with_saler)
false
7177047bb7942ee379b9a656bd76e19b93703c25
adipopbv/pf-laboratory-4-6
/Cheltuieli_de_familie/UI/Graphics.py
1,937
4.34375
4
def EmptyLine(): """ prints an empty line in the console """ print("") def Display(text): """ prints the given text in the console Args: text (str): text to be printed """ print(text) #EmptyLine() def DisplayAppName(): """ displays the name of the app """ Display(" <-----------------------> \n" + " Cheltuieli De Familie \n" + " <-----------------------> ") def DisplayCommands(): """ displays all the posible commands that can be inputed, with a description """ Display("COMENZI:") Display("Adaugare si actualizare:\n" + " [1]: Adauga o noua cheltuiala;\n" + " [2]: Actualizeaza o cheltuiala;\n" + "Stergere:\n" + " [3]: Sterge toate cheltuielile dintr-o zi;\n" + " [4]: Sterge toate cheltuielile dintr-un interval de zile;\n" + " [5]: Sterge toate cheltuielile de un anumit tip;\n" + "Cautari:\n" + " [6]: Cauta toate cheltuielile mai mari decat o anumita suma;\n" + " [7]: Cauta toate cheltuielile efectuate inainte de o zi anume si mai mici decat o anumita suma;\n" + " #[8]: Cauta toate cheltuielile de un anumit tip;\n" + "Rapoarte:\n" + " [9]: Afiseaza suma totala pentru un anumit tip de cheltuieli;\n" + " [10]: Afiseaza ziua cu suma cheltuita maxima;\n" + " #[11]: Afiseaza toate cheltuielile ce au o anumta suma;\n" + " #[12]: Afiseaza toate cheltuielile sortate dupa tip;\n" + "Filtrare:\n" + " [13]: Elimina toate cheltuielile de un anumit tip;\n" + " #[14]: Elimina toate cheltuielile mai mici decat o suma data;\n" + "Anulare:\n" + " #[15]: Anuleaza ultima operatie efectuata asupra cheltuielilor;\n" + "\n[16]: Iesire din aplicatie.") EmptyLine() def DisplayMenu(): """ displays the main menu """ DisplayAppName() DisplayCommands()
false
dc3c3ffbf7cc974b0ae38f962a9ed6558ad5b737
myronschippers/training-track-python
/sequences/groceries.py
1,122
4.625
5
# All sequences are iterable they can be looped over sequences are no exception # For in Loop - a way to perform an action on every item in a sequence my_name = 'Myron' for letter in my_name: print(letter) print('\n==========\n') # groceries list was provided groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food'] count = 1 # iterate over the list and print out the grocery items for food in groceries: # f' string can be used in order to add variables to strings print(f'{count}. {food}') count+=1 print('\n==========\n') # iterate over groceries and use the enumerate function to access index but notice it starts at for index, food in enumerate(groceries): # f' string can be used in order to add variables to strings print(f'{index}. {food}') print('\n==========\n') # iterate over groceries and use the enumerate function to access a tupol of index, food for index, food in enumerate(groceries, 1): print(f'{index}. {food}') print('\n==========\n') # start count at 20 for index, food in enumerate(groceries, 20): print(f'{index}. {food}')
true
40718d2720654b50421a64233f0d18586e1c1c0e
myronschippers/training-track-python
/sequences/ranges.py
666
4.25
4
# testing out a range what if we wanted something that would loop 10 times #for i in 10: # print(i) # getting an error because an int is not iterable # start - the index the range starts at # stop - the index the range stops at # step - how much the index increases as iterated through # Range[ start, stop, step ] for i in range(0, 10, 1): print(i) print('\n==========\n') # Python is smart enough to know that ranges always start at 0 and increase by 1 unless otherwise specified for i in range(10): print(f'{i} - shortened') print('\n==========\n') # make the range start at 5 for i in range(5, 10): print(f'{i} - start at 5')
true
d7f8216f8516f963aa7fcd797e2ae89c2a4e7d0f
taraj-shah/search_engine
/test.py
1,274
4.5
4
from tkinter import * #*********************************** #Creates an instance of the class tkinter.Tk. #This creates what is called the "root" window. By conventon, #the root window in Tkinter is usually called "root", #but you are free to call it by any other name. root = Tk() root.title('how to get text from textbox') #********************************** mystring = StringVar() ####define the function that the signup button will do def getvalue(): print(mystring.get()) #************************************* Label(root, text="Text to get").grid(row=0, sticky=W) #label Entry(root, textvariable = mystring).grid(row=0, column=1, sticky=E) #entry textbox WSignUp = Button(root, text="print text", command=getvalue).grid(row=3, column=0, sticky=W) #button ############################################ # executes the mainloop (that is, the event loop) method of the root # object. The mainloop method is what keeps the root window visible. # If you remove the line, the window created will disappear # immediately as the script stops running. This will happen so fast # that you will not even see the window appearing on your screen. # Keeping the mainloop running also lets you keep the # program running until you press the close buton root.mainloop()
true
cc0b1afd1e25acf5dafab63df5eec04009c0f6a5
subsid/sandbox
/algos/sliding_window/length_of_longest_substring.py
1,062
4.15625
4
# Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement. def length_of_longest_substring(input_str, k): max_length = 0 start = 0 freq_map = {} max_repeat = 0 for end in range(len(input_str)): letter = input_str[end] if letter not in freq_map: freq_map[letter] = 0 freq_map[letter] += 1 max_repeat = max(max_repeat, freq_map[letter]) window_len = end - start + 1 if ((window_len - max_repeat) > k): freq_map[input_str[start]] -= 1 start += 1 new_window_len = end - start + 1 max_length = max(max_length, new_window_len) return max_length if __name__ == "__main__": print("length_of_longest_substring") assert(length_of_longest_substring("aabccbb", 2) == 5) assert(length_of_longest_substring("abbcb", 1) == 4) assert(length_of_longest_substring("abccde", 1) == 3)
true
c709f0e7f1bc08922bd4000fb3074b02be085a59
Acidcreature/05-Python-Programming
/homeclasswork/cool things/mapdemo.py
585
4.34375
4
# Map() function # calls the spcified function and applies it to each item of an iterable def square(x): return x*x numbers = [1, 2, 3, 4, 5] #sqrList = map(square, numbers) #print(next(sqrList)) #print(next(sqrList)) #print(next(sqrList)) #print(next(sqrList)) #print(next(sqrList)) #print(next(sqrList)) sqrList2 = map(lambda x: x*x, numbers) #print(next(sqrList2)) #print(next(sqrList2)) #print(next(sqrList2)) #print(next(sqrList2)) #print(next(sqrList2)) #print(next(sqrList2)) tens = [10, 20, 30, 40, 50] indx = [1, 2, 3] powers = list(map(pow, tens, indx)) print(powers)
true
943dbe1b3380ef4f2ab81fcf6f42598716ac9680
Acidcreature/05-Python-Programming
/homeclasswork/liststupes/listtup_lottonums.py
464
4.15625
4
""" 2. Lottery Number Generator Design a program that generates a seven-digit lottery number. The program should generate seven random numbers, each in the range of 0 through 9, and assign each number to a list element. Then write another loop that displays the contents of the list.""" import random def lotto(): lottolist = [0,0,0,0,0,0,0] for l in range(len(lottolist)): lottolist[l] = (random.randrange(0, 9)) print(lottolist) lotto()
true
8b7699247d59c50d1edf6ae82a9a53301c2672da
Acidcreature/05-Python-Programming
/homeclasswork/classes/gcd.py
533
4.15625
4
# This program uses recursion to find the GCD of two numbers # if x can be evenly divded by y, then gcd(x, y) = y # otherwise, gcd(x, y) = gcd(y, remainder of x/y) def main(): # get two numbers num1 = int(input("Enter a number: ")) num2 = int(input("Enter another number: ")) # Display GCD print("The GCD of ") print("the two numbers is ", gcd(num1, num2)) # The gcd function returns the gcd of two numbers def gcd(x, y): if x % y == 0: return y else: return gcd(y, x % y) main()
true
ad1a87911099f0691ea8aa2557d3326115780a2b
viniciuslizarte/Python3
/First Steps/Ex032.py
574
4.1875
4
'''''Desenvolva um programa que leia 3 comprimentos de retas e imprima se ele pode ou não formar um triângulo''' print('PODE OU NÃO SER UM TRIÂNGULO...') r1 = float(input('Digite o valor de uma reta: ')) r2 = float(input('Digite o valor de uma reta: ')) r3 = float(input('Digite o valor de uma reta: ')) r4 = (r1 + r2) r5 = (r2 + r3) r6 = (r1 + r3) if r1 < r5 and r2 < r6 and r3 < r4: print('Com as medidas informadas é possível construir um Triângulo!') else: print('Com as medidas informadas NÃO é possível forma um triângulo.') print('---- FIM ----')
false
2341a384da37e088a76648c701c1f836b35c3dca
viniciuslizarte/Python3
/First Steps/Ex033.py
1,052
4.21875
4
'''ESCREVA UM PROGRAMA QUE APROVE UM EMPRÉSTIMO BANCÁRIO PARA A COMPRA DE UMA CASA. O PROGRAMA IRÁ PERGUNTAR O VALOR DA CASA, O SALÁRIO DO COMPRADOR E EM QUANTOS ANOS ELE IRÁ PAGAR CALCULE O VALOR DA PRESTAÇÃO MENSAL, SABENDO QUE ELA NÃO PODE ULTRAPASSAR 30% DO SALÁRIO OU ENTÃO O EMPREPÉSTIMO SERÁ NEGADO''' import time print('EMPRÉSTIMO BANCÁRIO') name = str(input('Olá qual é seu nome: ')).upper().strip() home = float(input('{} qual o valor do imóvel que deseja comprar? R$' .format(name))) salary = float(input('{} qual é o valor do seu salário? R$' .format(name))) m = (salary * 30) / 100 year = int(input('{} em quantos anos pretende parcelar este financiamento? ' .format(name))) print('Ok, estamos analisando seus dados...') time.sleep(3) if (home / (year * 12)) > m: print('{} infelizmente seu crédito não foi aprovado' .format(name)) else: print('PARABÉNS, SEU FINANCIAMENTO FOI APROVADO!!') print(('{} o valor da mensalidade ficará R$:{:.2f}') .format(name, (home / (year * 12)))) print('---- FIM ---')
false
09dbe5ba46289d391aa26da317deff7195c05e3b
vadvag/ExercisesEmpireOfCode
/006.TwoMonkeys.py
555
4.125
4
""" Two Monkeys We have two monkeys, a and b, and the parameters asmile and bsmile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble. Input: Two arguments as numbers. Output: Maximum of two. Example: two_monkeys(True, True) == True two_monkeys(False, False) == True two_monkeys(True, False) == False two_monkeys(False, True) == False """ def two_monkeys(asmile, bsmile): if asmile == bsmile: res = True else: res = False return res
true
e36c46ded18f40dbe940089f78e4cd608afe7b3e
vadvag/ExercisesEmpireOfCode
/003.IndexPower.py
1,165
4.46875
4
""" Index Power Each level of the mine requires energy in exponential quantities for each device. Hmm, how to calculate this? You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0. Let's look at a few examples: array = [1, 2, 3, 4] and N = 2, then the result is 32 == 9; array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1. Input: An array as a list of integers and a number as an integer. Output: The result as an integer. Example: index_power([1, 2, 3, 4], 2) == 9 index_power([1, 3, 10, 100], 3) == 1000000 index_power([0, 1], 0) == 1 index_power([1, 2], 3) == -1 Precondition: 0 < |array| ≤ 10 0 ≤ N ∀ x ∈ array: 0 ≤ x ≤ 100 """ def index_power(array, n): if n < 0 or n>100: res = -1 elif n == 0: res = 1 else: if len(array) < n+1: res = -1 else: zn = array[n] res = 1 for i in range(n): res = res*zn return res
true
4f25e52640eb346576c425032996b0210d791b99
achinthagunasekara/sorting_algorithms
/selection_sort/sort.py
1,751
4.34375
4
""" Implementation of selection sort algorithm """ def selection_sort_same_list(list_to_sort): """ Sort a list using selection sort algorithm (using the same list). Args: list_to_sort (list): Unsorted list to sort. Returns: list: Sorted list. """ for outter_index, outter_element in enumerate(list_to_sort): # pylint: disable=unused-variable smallest_index = outter_index for inner_index in range(outter_index, len(list_to_sort)): if list_to_sort[inner_index] < list_to_sort[smallest_index]: smallest_index = inner_index list_to_sort[outter_index], list_to_sort[smallest_index] = \ list_to_sort[smallest_index], list_to_sort[outter_index] return list_to_sort def selection_sort_new_list(list_to_sort): """ Sort a list using selection sort algorithm (using a new list). Args: list_to_sort (list): Unsorted list to sort. Returns: list: Sorted list. """ sorted_list = [] for outter_index, outter_element in enumerate(list_to_sort): # pylint: disable=unused-variable smallest_index = outter_index for inner_index in range(outter_index, len(list_to_sort)): if list_to_sort[inner_index] < list_to_sort[smallest_index]: smallest_index = inner_index sorted_list.append(list_to_sort[smallest_index]) return list_to_sort TO_SORT = [ [1, 9, -5, 12, 2, 3, 4, 20, 6], [9, 8, 7, 6, 5, 4, 3, 2, 1], [10, -5, -4, 9, 9, 4, 9, 7] ] for each_list in TO_SORT: print 'Sorting using the same list' print selection_sort_same_list(each_list) print 'Sorting using a new list' print selection_sort_new_list(each_list) print '\n'
true
59f157d861704930e57aacc4eddf8c2bdd49254e
Danya1998/DP-189-TAQC
/elem3/venv/triangle.py
1,114
4.125
4
import math def input_triangle(): input_param = input("Input triagle name and it's 3 sides through the ',':") input_param=input_param.split(',') return input_param def real_triangle(a,b,c): if a+b > c and a+c > b and b+c >a> 0 and b> 0 and c> 0: return True else: print("Enter correct value\n") input_triangle() def sq_Gerona(side1, side2, side3): p = float((side1 +side2 +side3)/2) return math.sqrt(p*(p-side1)*(p-side2)*(p-side3)) def main(): triangles = {} while(True): triangle = input_triangle() print(triangle[3]) if(real_triangle(float(triangle[1]),float(triangle[2]),float(triangle[3]))): area = sq_Gerona(float(triangle[1]),float(triangle[2]),float(triangle[3])) triangles[triangle[0]] = area cont = input("Do you want to continue:").lower() if (cont != 'y'): break list_triangles = list(triangles.items()) list_triangles.sort(key=(lambda i: i[1]),reverse=True) for i in list_triangles: print(i[0], ':', i[1]) if __name__ == '__main__': main()
false
66e43d92a853402d0bc638d8bd4796c2d9ced2b1
AlexandreLouzada/Pyquest
/envExemplo/Lista04/Lista04Ex08.py
1,310
4.15625
4
# Programa que calcula a área de um retângulo, círculo ou triângulo retangulo = lambda lado_a_ret, lado_b_ret: lado_a_ret * lado_b_ret triangulo = lambda lado_triângulo, altura_triângulo: (lado_triângulo * altura_triângulo) / 2 circulo = lambda raio_circulo: 3.14 * (raio_circulo ** 2) opcao = -1 while opcao != 0: print() print('Escolha o objeto que deseja calcular a área') print() print('1 - Retângulo') print('2 - Triângulo') print('3 - Círculo') print('0 - Sair') print() opcao = int(input('Entre com o número da opção desejada: ')) if opcao == 1: lado_a = float(input('Entre com um lado do retângulo: ')) lado_b = float(input('Entre com o outro lado do retângulo: ')) print(f'\nA área do retâgulo é: {retangulo(lado_a, lado_b):0.2f}') elif opcao == 2: lado = float(input('Entre com o lado do triângulo: ')) altura = float(input('Entre com a altura do triângulo: ')) print(f'\nA área do triângulo é: {triangulo(lado, altura):0.2f}') elif opcao == 3: raio = float(input('Entre com o raio do cículo:')) print(f'\nA área do círculo é: {circulo(raio):0.2f}') elif opcao != 0: print(f'\n{opcao} não é uma opção válida') print() print('Fim!')
false
a581b59db57011f22159e88df376f9993c5fb2ec
afforeroc/find-the-real-gauss
/find_the_real_gauss.py
1,922
4.46875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Find The Real Gauss!""" def iterative_sum(num_list): """Calculate the sum using a for loop.""" total = 0 for num in num_list: total += num return total def python_sum(num_list): """Calculate the sum using standart 'sum' function of python.""" return sum(num_list) def fake_gauss_1(num_list): """Fake Gauss v1""" a = num_list[0] b = num_list[-1] n = b - a + 1 return int(n * (n + 1)/2) def fake_gauss_2(num_list): """Fake Gauss v3""" a = num_list[0] b = num_list[-1] return int(b * (a + b)/2) def fake_gauss_3(num_list): """Fake Gauss v3""" a = num_list[0] b = num_list[-1] n = b - a + 1 return int(n * (b + 1)/2) def the_real_gauss(num_list): """Real Gauss""" return '?' def compare_algorithms(a, b): print('//////////////////////////////') list_of_numbers = list(range(a, b + 1)) n = len(list_of_numbers) print('List: [{}, {}, ..., {}, {}]'.format(a, a + 1, b - 1, b)) print('Size of list: {}\n'.format(n)) total1 = iterative_sum(list_of_numbers) total2 = python_sum(list_of_numbers) total3 = fake_gauss_1(list_of_numbers) total4 = fake_gauss_2(list_of_numbers) total5 = fake_gauss_3(list_of_numbers) total6 = the_real_gauss(list_of_numbers) print('Algorithm\tSum') print('---------------------') print('Iterative\t{}'.format(total1)) print('Standart\t{}'.format(total2)) print('Fake Gauss 1\t{}'.format(total3)) print('Fake Gauss 2\t{}'.format(total4)) print('Fake Gauss 3\t{}'.format(total5)) print('The Real Gauss\t{}'.format(total6)) def main(): """Compare different algorithms that sum all integers of an interval.""" print("==== Find The Real Gauss! ====") compare_algorithms(1, 100) compare_algorithms(101, 200) if __name__ == '__main__': main()
false
23b3786f6577a88d872e32f63670d28c68d4db8c
debasis-pattanaik-au16/Python
/Hackerrank/pangrams.py
1,214
4.25
4
# Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence # “The quick brown fox jumps over the lazy dog” repeatedly, because it is a pangram. # (Pangrams are sentences constructed by using every letter of the alphabet at least once.) # After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams. # Given a sentence s, tell Roy if it is a pangram or not. # Input Format # Input consists of a string s. # Constraints # Length of s can be at most 10Msup>3 and it may contain spaces, lower case and upper case letters. # Lower-case and upper-case instances of a letter are considered the same. # Output Format # Output a line containing pangram if s is a pangram, otherwise output not pangram. import math import os import random import re import sys # Complete the pangrams function below. def pangrams(s): s = set(s.lower()) if len(s) == 27: return 'pangram' else: return 'not pangram' if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = pangrams(s) fptr.write(result + '\n') fptr.close()
true
151b5af60bca9ea7c60b154e49ed077cd552f989
debasis-pattanaik-au16/Python
/Hackerrank/Mod Divmod.py
524
4.125
4
# Read in two integers, and , and print three lines. # The first line is the integer division (While using Python2 remember to import division from __future__). # The second line is the result of the modulo operator: . # The third line prints the divmod of and # . # Input Format # The first line contains the first integer, # , and the second line contains the second integer, # . # Output Format # Print the result as described above. a = int(input()) b = int(input()) print(a // b) print(a % b) print(divmod(a, b))
true
b3a590436d1bc37cbe6685d1f49735ed36c29b29
iamfakeBOII/pythonP
/lab_record_LISTS.py
1,517
4.28125
4
#PROGRAM TO FIND INDEX VALUE ''' l = eval(input('ENTER NUMBERS: ')) e = float(input('ENTER THE ELEMENT: ')) if e in l: print(f'{e} has {l.index(e)} index vlaue') else: print('not found') ''' #LARGEST/SMALLEST VALUE IN A LIST/TUPLE ''' l = eval(input('ENTER ELEMENTS: ')) print(f'THE LARGEST VALUE IS {max(l)} AND {min(l)}') ''' #SWAP ELEMENTS IN A LIST/TUPLE ''' l = eval(input('ENTER ELEMENTS: ')) final = [] for a in l: if l.index(a)%2==0: temp = a else: final.append(a) final.append(temp) print(final) ''' #SEARCH ELEMENT FOR A SPECIFIC ELEMENT IN A LIST/TUPLE ''' l = eval(input('ENTER ELEMENTS: ')) e = float(input('ENTER THE ELEMENT TO BE FOUND: ')) if e in l: print(f'THE ELEMENT {e} IS A PART OF THE SEQUENCE WITH INDEX VALUE {l.index(e)}') else: print('NOT FOUND') ''' #SEARCH FOR A ARMSTRONG NUMBER FROM A LIST/TUPLE AND PRINT THE LARGEST AND SMALLEST NUMBER ''' l = eval(input('ENTER ELEMENTS: ')) nums = [] #TO STORE FINAL ARMSTRONG NUMBERS for a in l: #TO CHECK ARMSTRONG NUMBER check = a s = 0 while a>0: #TO CALCULATE THE ARMSTRONG NUMBER d = a%10 s = s + (d**3) a = a//10 if s == check: nums.append(check) else: continue print(f'THE ARMSTRONG NUMBERS ARE {nums}') print(f'THE LARGEST ARMSTRONG NUMBER IS {max(nums)} AND THE SMALLEST ARMSTRONG NUMBER IS {min(nums)}') '''
false
7299e28fbf3cc036c84670036241455f45605a2b
ravigupta19/Algorithm
/RecurisveFactorial.py
241
4.25
4
fact_num = input("Enter the num for which you want calculate the factorial") def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) res = factorial(int(fact_num)) print("Your Results is :" +str(res))
true
bb26a151b8f6f68371a86735dacf74aca87cfda4
resullar-vince/fsr
/python/py-quiz-refactor-1.py
1,212
4.375
4
# Task: # - Create a feature that can display and calculate volumes of 3D shapes (cube, sphere, etc.) # # As a Final Reviewer, you should be able to: # Comment, review and/or refactor the code below. import math class Cube: def __init__(self, side): self.side = side self.name = "Cube" class Sphere: def __init__(self, radius): self.radius = radius self.name = "Sphere" class RectangularPyramid: def __init__(self, width, length, height): self.width = width self.length = length self.height = height self.name = "Rectangular Pyramid" def ShowV(solids): for solid in solids: if (solid.name == "Cube"): volume = solid.side ** 3 print(solid.name, "volume:", volume) elif (solid.name == "Sphere"): volume = (4 / 3) * math.pi * (solid.radius ** 3) print(solid.name, "volume:", volume) elif (solid.name == "Rectangular Pyramid"): volume = (1 / 3) * solid.width * solid.length * solid.height print(solid.name, "volume:", volume) if __name__ == "__main__": solids = [Cube(4), Sphere(3), RectangularPyramid(3, 4, 6)] ShowV(solids)
true
fd0130467b3315994ce1929ff9d785b5a903d1d2
Sigrud/lesson1
/hello.py
739
4.125
4
# a=input() # print(f'hello '+a) # numbers # -------------------------- a=2 b=4.5 print(a+b) # v=int(input('введите число')) # print(v+10) # strings # ------------------------- # name=input('введите ваше имя: ') # print('привет, '+name+'! Как дела?') # lists # -------------------------- a=[2,3,4,5,6,7] print(a) a.append('python') print(len(a)) print(a[0]) print(a[-1]) print(a[2:5]) a.remove('python') # dict # -------------------------- s={'cyty':'Moscow','temperature':'20'} print(s['cyty']) print(s) s['temperature']=int(s['temperature'])-5 print(s) s.get('country','russia') s['date']='25.11.2018' print(s) print(len(s)) # variables # -------------------------- name='Sergey' print(name)
false
6a5ffd1b7303589ebe16318946ce964b4b988dee
Igor-fr/GB
/Python_algorithms/lesson_2/les_2_task_1.py
1,857
4.125
4
# 1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции # вводятся пользователем. После выполнения вычисления программа не завершается, а запрашивает новые данные для # вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве знака операции. Если # пользователь вводит неверный знак (не '0', '+', '-', '', '/'), программа должна сообщать об ошибке и снова запрашивать # знак операции. Также она должна сообщать пользователю о невозможности деления на ноль, если он ввел его в качестве # делителя. while True: a = float(input("Введите первое число: ")) b = float(input("Введите второе число: ")) oper = input("Введите знак операции (+ - * / 0(Для завершения): ") if oper == '+': print(f"Сумма равна {a+b}") elif oper == '-': print(f"Разница равна {a-b}") elif oper == '*': print(f"Произведение равно {a*b}") elif oper == '/': if(b!=0): print(f"Частное равно {a/b}") else: print("На ноль делить запрещено!") elif oper == '0': print("Вы завершили работу.") exit() else: print("Вы ввели неверный знак операции.")
false
1cfc0783013a88df0bdd29d6def431a38728b8ea
wfoody/LearningPython
/day4_Largest-Element.py
432
4.3125
4
# Finding the largest element numbers = [384, 84, 489, 2347, 47, 94] numbers.sort() print(numbers[-1]) #alternative arg1 = max(numbers) print(arg1) print(max(numbers)) #2nd_alternative def find_largest(numbers): largestSeen = numbers[0] for x in numbers: if x > largestSeen: largestSeen = x return largestSeen largestSeen = find_largest(numbers) print(largestSeen)
true
3d3d4582c2af150e87583374eca95da34f353165
wfoody/LearningPython
/WeekendAssignment/todo_list.py
1,275
4.59375
5
""" TODO: Functions: - Present user with menu - take in input - add task - take additional input - actually add the task to the todo list - delete task - take additional input - show all tasks """ tasks = [] choice = input("Press 1 to add task.\nPress 2 to delete task.\nPress 3 to view all tasks.\nPress 'q' to quit. ") if choice == 1: tasks_dict = add_task() tasks.append(tasks_dict) # put tasks_dict into tasks elif choice == 2: delete_task() elif choice == 3: view_tasks() elif choice == "q": quit() def add_task(): title = input("Name of task: ") priority = input("Priority of task (high, medium, low): ") tasks_dict = { "title": title, "priority": priority } return tasks_dict # show all tasks with index number of each task. input index to delete respective task def delete_task(): for i, val in enumerate(tasks): print( i, val) number = input("Enter number of task to delete: ") del tasks[number] # allow user to view tasks with format : title - priority def view_tasks(): for index, task in enumerate(tasks): # {"title": "dishes", "priority": "high"} print(index, task["title"], task["priority"])
true
6c27fcf13ad2a6dbef592436c8ebd4b75ccec8b1
PCLWXM/pclpy
/my-控制语句/mypy03.py
647
4.125
4
#使用完整的条件表达式结构 score = int(input("请输入分数:")) grade = '' if(score<60): grade = "不及格" if(60<=score<80): grade = "及格" if(80<=score<90): grade = "良好" if(90<=score<=100): grade = "优秀" print("分数是{0},等级是{1}".format(score,grade)) print("******************************************************") #使用多分支结构 score = int(input("请输入分数:")) grade = '' if(score<60): grade = "不及格" elif(score<80): grade = "及格" elif(score<90): grade = "良好" elif(score<=100): grade = "优秀" print("分数是{0},等级是{1}".format(score,grade))
false
de733d1e71fbb6b34a2b130274ea49825b435747
NiteshPidiparars/python-practice
/HCFORGCDOfTwoNumbers.py
730
4.15625
4
''' Calculation of HCF Using Python: In this video, we will learn to find the GCD of two numbers using Python. Python Program to Find HCF or GCD is asked very often in the exams and we will take this up in todays video! Highest Common Factor or Greatest Common Divisor of two or more integers when at least one of them is not zero is the largest positive integer that evenly divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4 ''' num1 = int(input("Enter first number\n")) num2 = int(input("Enter second number\n")) if num2 > num1: mn = num1 else: mn = num2 for i in range(1, mn+1): if num1 % i == 0 and num2 % i == 0: hcf = i print(f"The HCF/GCD of these two numbers is {hcf}")
true
36eb39d005f9a1fa4edd4f1ad38644c9eed42e1c
jicuss/learning_examples
/fibonacci/fibonacci.py
990
4.34375
4
# First, calculate the fibonacci sequence by using a loop def fibonacci_loop(number): ''' all fibonacci elements where element is <= n ''' results = [] first_element = 0 second_element = 0 # for element in range(0,number + 1): while True: sum = (first_element + second_element) if sum > number: break else: results.append(sum) if sum == 0: first_element = 1 else: first_element = second_element second_element = sum return results # Second, calculate the fibonacci sequence by using a loop. A better approach def fibonacci_recurse(number, results = [], first_element = 0, second_element = 0): sum = (first_element + second_element) if sum > number: return results else: results.append(sum) if sum == 0: results.append(1) sum = 1 return fibonacci_recurse(number, results, second_element, sum)
true
46cad0caed62396f91d5cdb32103c2083cbfc5c4
jicuss/learning_examples
/string_manipulation/string_rotation.py
1,089
4.28125
4
''' Original Source: Cracking the Coding Interview Question: Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call eg. waterbottle is a rotation of erbottlewat ''' import unittest import pdb def isSubstring(s1,s2): if s1 in findRotations(s2): return True def findRotations(string): ''' return all possible rotations ''' rotations = [] l = len(string) for i in range(0,l + 1): beginning = string[i:l + 1] # grabs the current index to the end of the string ending = string[0:i] rotations.append(beginning + ending) return rotations class StringRotationTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_isSubstring(self): self.assertTrue(isSubstring('waterbottle','erbottlewat')) def test_findRotations(self): self.assertIn('erbottlewat',findRotations('waterbottle')) if __name__ == '__main__': unittest.main()
true
171bb33eb82dd199aa78153963536b9191092d4b
zyall/demo
/Downloads/PycharmProjects/pyse11/python_base/function_test.py
740
4.28125
4
''' 用引号 1.多行注释 2.类、方法、函数内部注释 ''' def add(a=1, b=2): '''用于计算(参数默认)a add b ''' return a + b # print(add(5, 7)) # print(help(add)) #类和方法 ''' class jisuan(object): class jisuan(): class jisuan: class A(): def __init__(self, a, b): self.a = int(a) self.b = int(b) def add(self): return self.a + self.b def sub(self): '''调用add函数''' C = self.add() return C class B(A): '''B继承A''' def __init__(self, a, b, c): self.a = int(a) self.b = int(b) self.c = int(c) def add(self): return self.a + self.b + self.c c = B(5, 7, 3).add() print(c) '''
false
de333ba0ab185ab9a7d3dbbe4af3ba7809034ddc
Devinwon/master
/coding-exercise/hankerRank/python/Introduction/lists.py
779
4.1875
4
""" https://www.hackerrank.com/challenges/python-lists/problem insert i e print remove e append e sort pop reverse """ if __name__ == '__main__': N = int(input()) lst=[] for _ in range(N): cmd=input().split() if 'insert' in cmd: lst.insert(int(cmd[1]),int(cmd[2])) elif 'print' in cmd: print(lst) elif 'pop' in cmd: lst.pop() elif 'sort' in cmd: lst.sort() elif 'reverse' in cmd: lst.sort(reverse=True) elif 'append' in cmd: lst.append(int(cmd[1])) elif 'remove' in cmd: lst.remove(int(cmd[1])) """ 注意eval的用法 n = input() l = [] for _ in range(n): s = raw_input().split() cmd = s[0] args = s[1:] if cmd !="print": cmd += "("+ ",".join(args) +")" eval("l."+cmd) else: print l """
false
10aff88a25874189ecc11da916a2f7ae505ef00f
Devinwon/master
/computer-science-and-python-programing-edX/week6/code_ProblemSet6/test.py
1,422
4.6875
5
def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ ### TODO. # return "Not yet implemented." # Remove this comment when you code the function dic={} lcase="abcdefghijklmnopqrstuvwxyz" ucase="ABCDEFGHIJKLMNOPQRSTUVWXYZ" for l in lcase: dic[l]=chr((ord(l)+shift-97)%26+ord('a')) for u in ucase: dic[u]=chr((ord(u)+shift-65)%26+ord('A')) return dic def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is. text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ ### TODO. ### HINT: This is a wrapper function. # return "Not yet implemented." # Remove this comment when you code the function afterText="" for c in text: if c.isalpha(): afterText+=buildCoder(shift)[c] else: afterText+=c return afterText print applyShift('This is a test.', 8) print applyShift('Bpqa qa i bmab.', 18)
true
50c63296729e3177fa2042237ec1a28c41d05e6b
Devinwon/master
/coding-exercise/hankerRank/algorithm/warmup/simply-array-sum.py
1,126
4.40625
4
""" Given an array of integers, find the sum of its elements. Function Description Complete the function which is described by the below function signature. integer simpleArraySum(integer n, integer_array ar) { # Return the sum of all array elements } n: Integer denoting number of array elements ar: Integer array with elements whose sum needs to be computed Raw Input Format The first line contains an integer,n , denoting the size of the array. The second line contains n space-separated integers representing the array's elements. Sample Input 0 6 1 2 3 4 10 11 Sample Output 0 31 Explanation 0 We print the sum of the array's elements: . 1 +2+ 3+ 4 +10+ 11=31 """ #!/bin/python3 import os import sys # # Complete the simpleArraySum function below. # def simpleArraySum(ar): # # Write your code here. # s=0 for v in ar: s+=v return s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') ar_count = int(input()) ar = list(map(int, input().rstrip().split())) result = simpleArraySum(ar) fptr.write(str(result) + '\n') fptr.close()
true
19c1f863c8589b384decbc7af986d0795856346f
Devinwon/master
/python-language-programing-BIT/Pythonlan06/W6_dict.py
1,071
4.1875
4
dict={'name':'abc','pwd':'123'} #define dict print('print the dict:',dict,sep='') print('search the name key:'+dict['name']) #visit key-'name' print('Now append status-off to dict') dict['status']='off' #append key-value print('Newer dict:',end='') print(dict) #list operation in dict print('\n-----------------') for key in dict: print(key+':'+str(dict[key])) print('-----------------') print('print all keys') for key in dict.keys(): print(key) print('-----------------') print('print all values') for value in dict.values(): print(value) print('-----------------') print('print all items') for item in dict.items(): print(item) print('-----------------') print('print keys values') for key,value in dict.items(): print(key,value) print('-----------------') print('Delete the name key in dict:') del dict['name'] #delete the key and the value print(dict) for key in dict: print(key+':'+str(dict[key])) print('key name exist or not:','name' in dict,sep='')
true
3457ee16db0574eb3046500464a45197f40ffc0c
shobhadoiphode42/python-essentials
/day4Assignment.py
460
4.59375
5
#!/usr/bin/env python # coding: utf-8 # In[2]: str1 = "What we think we become; we are a python programmer" sub = "we" print("The original string is : " + str1) print("The substring to find : " + sub) res = [i for i in range(len(str1)) if str1.startswith(sub, i)] print("The start indices of the substrings are : " + str(res)) # In[4]: str2="HELLO" print(str2) str2.islower() # In[6]: str2="hello" print(str2) str2.isupper() # In[ ]:
true
c583cd8c5cd420858133243bda87eb1186e133da
BChris98/AdvancedPython2BA-Labo1
/utils.py
1,522
4.375
4
# utils.py # Math library # Author: Sébastien Combéfis # Version: February 8, 2018 from math import sqrt def fact(n): """Computes the factorial of a natural number. Pre: - Post: Returns the factorial of 'n'. Throws: ValueError if n < 0 """ result = 1 for x in range (1,n+1): result *= x return (result) def roots(a, b, c): """Computes the roots of the ax^2 + bx + x = 0 polynomial. Pre: - Post: Returns a tuple with zero, one or two elements corresponding to the roots of the ax^2 + bx + c polynomial. """ delta = b**2 - (4*a*c) if delta == 0: result = -b/(2*a) return (result) elif delta > 0: result1 = (-b+sqrt(delta))/2 result2 = (-b-sqrt(delta))/2 return (result1,result2) def integrate(function, lower, upper): """Approximates the integral of a fonction between two bounds Pre: 'function' is a valid Python expression with x as a variable, 'lower' <= 'upper', 'function' continuous and integrable between 'lower‘ and 'upper'. Post: Returns an approximation of the integral from 'lower' to 'upper' of the specified 'function'. """ h = (upper-lower)/2 approx = 0 compteur = lower while compteur <= upper: x = compteur approx += h*(eval(function)) compteur += h return (approx) if __name__ == '__main__': print(fact(5)) print(roots(1, 0, 1)) print(integrate('x ** 2 - 1', -1, 1))
true
e41f57732472cb40248e2a2e573a9ddac4574c27
zurgis/codewars
/python/7kyu/7kyu - List of all Rationals.py
1,707
4.40625
4
# Here's a way to construct a list containing every positive rational number: # Build a binary tree where each node is a rational and the root is 1/1, with the following rules for creating the nodes below: # The value of the left-hand node below a/b is a/a+b # The value of the right-hand node below a/b is a+b/b # So the tree will look like this: # 1/1 # / \ # 1/2 2/1 # / \ / \ # 1/3 3/2 2/3 3/1 # / \ / \ / \ / \ # 1/4 4/3 3/5 5/2 2/5 5/3 3/4 4/1 # ... # Now traverse the tree, breadth first, to get a list of rationals. # [ 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, .. ] # Every positive rational will occur, in its reduced form, exactly once in the list, at a finite index. # In the kata, we will use tuples of type (int, int) to represent rationals, where (a, b) represents a / b # Use this method to create an infinite list of tuples: # def all_rationals() -> Generator[(int, int)]: # matching the list described above: # all_rationals => [(1, 1), (1, 2), (2, 1), (1, 3), (3, 2), ...] def all_rationals(): yield (1, 1) for a, b in all_rationals(): yield (a, a + b) yield (a + b, b) ''' tree = [[[1,1]]] while True: tree.append([]) for a, b in tree[-2]: left = [a, b + a] right = [a + b, b] tree[-1].extend([left, right]) yield tree from fractions import Fraction x = Fraction(1, 1) yield x while True: x = Fraction(1, 2 * Fraction(int(x)) - x + 1) yield x '''
true
752f757361c65f5c37ee549bb2cd50fe0b5b637c
zurgis/codewars
/python/7kyu/7kyu - Integer Difference.py
645
4.125
4
# Write a function that accepts two arguments: an array/list of integers and another integer (n). # Determine the number of times where two integers in the array have a difference of n. # For example: # [1, 1, 5, 6, 9, 16, 27], n=4 --> 3 # (1,5), (1,5), (5,9) # [1, 1, 3, 3], n=2 --> 4 # (1,3), (1,3), (1,3), (1,3) # My answer def int_diff(arr, n): count = 0 for i in range(len(arr)): for j in range(i + 1, len(arr)): if abs(arr[j] - arr[i]) == n: count += 1 return count ''' import itertools return sum(abs(a - b) == n for a, b in itertools.combinations(arr, 2)) '''
true
e846b57528f0bf301274935b7465dba6098478b5
adamhowe/variables
/Revision exercise 3.py
396
4.1875
4
#Adam Howe #16/09/2014 #Revision Exercise 3 first_number = int(input("Enter your first number: ")) second_number = int(input("Enter your second number: ")) answer_one = first_number / second_number answer_two = first_number % second_number # the % symbol will give the remainder of the two number divided together print(answer_one) print(answer_two)
true
2b4a979722711ce0c8813687baae135f77719c87
nerbertb/learning_python
/open-weather.py
1,273
4.28125
4
import requests open_api_key = "<Enter the provided key here from Open Weather>" city = input("Enter the city you like to check the forecast: ") #Ask the user what city he like to check the forecast url = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&appid="+open_api_key+"&units=imperial" #will call the result from OpenWeather API with a Farenheight temperature request = requests.get(url) #Calling the site to provide the information of the city json = request.json() #Will format the request to JSON #I had to get format the json result to a JSON Formatter site so I can analyze the data properly as it's returning a hard to read data when printing the JSON result that we get from the API. city = json.get("name") country = json.get("sys").get("country") forecast = json.get("weather")[0].get("description") print ("The weather forecast today in", city, "city,", country, "is:", forecast ) min_temp = json.get("main").get("temp_min") max_temp = json.get("main").get("temp_max") print ("The current temperature is", min_temp, "to", max_temp) ''' The result will be like the one below: Enter the city you like to check the forecast: manila The weather forecast today in Manila city, PH is: few clouds The current temperature is 82 to 82.99 '''
true
53c71e55746207c5be76bb6a67d01e08e59e7b5b
emGit/python100
/p19/race.py
977
4.21875
4
import random from turtle import Screen, Turtle screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ") colors = ["red", "orange", "yellow", "green", "blue", "purple"] y_positions = [-70, -40, -10, 20, 50, 80] all_turtles = [] for turtle_index in range(0, 6): new_turtle = Turtle(shape="turtle") new_turtle.penup() new_turtle.color(colors[turtle_index]) new_turtle.goto(x=-230, y=y_positions[turtle_index]) all_turtles.append(new_turtle) while user_bet: for turtle in all_turtles: if turtle.xcor() > 230: user_bet = None winning_color = turtle.pencolor() if winning_color == user_bet: print(f"You've won! The {winning_color} turtle is the winner!") else: print(f"You've lost! The {winning_color} turtle is the winner!") turtle.forward(random.randint(0, 10)) screen.exitonclick()
true
eecab9761bd76ad15c4856b960dc8bcbf9618759
2caser/CapstoneSoHo
/Capstone_SoHo/script.py
2,842
4.1875
4
from trie import Trie from data import * from welcome import * from hashmap import HashMap from linkedlist import LinkedList ### Printing the Welcome Message print_welcome() ### Write code to insert food types into a data structure here. The data is in data.py t = Trie() for word in types: t.insert(word) ### Write code to insert restaurant data into a data structure here. The data is in data.py hash_data = HashMap(len(restaurant_data)) for type in types: ll = LinkedList() for data in restaurant_data: if type == data[0]: ll.insert_beginning(data) hash_data.assign(type,ll) #print("**************",hash_data.retrieve((type))) # finding food type for retrieving restaurant data here def restaurants_in_soho(usr_input): lln = hash_data.retrieve((usr_input)) head_node = lln.get_head_node() while head_node.value != None: print("\n") print("Name: {}".format(head_node.value[1])) print("----------------------"); print("Type: {}".format(head_node.value[0])) print("Price: {}/5".format(head_node.value[2])) print("Rating: {}/5".format(head_node.value[3])) print("Address: {}".format(head_node.value[4])) #print("\n") head_node = head_node.get_next_node() #Write code for user interaction here while True: #Search for user_input in food types data structure here user_input = str(input("\nWhat type of food would you like to eat?\n\nType the beginning of that food type and press enter to see if it's in SoHo or 'quitting' to exit\n")).lower() if user_input == 'quitting': print("\nThanks for considering SoHo restaurants!") exit() if user_input.isalpha(): beginning_letter = t.starts_with(user_input) if beginning_letter == None: print("\n*** Please try again!! ***, no letters beginning with letter '{}'\n".format(user_input)) continue elif len(beginning_letter) > 1: print("\nWith those begining letters, your choices are:\n", beginning_letter) continue elif user_input in types: restaurants_in_soho(user_input) elif len(beginning_letter) == 1: print("The only option with those begining letter is ", (beginning_letter[0])) print("Do you want to look at '{}' restaurants, please select 'y' for yes and 'n' for no.\n".format(beginning_letter[0])) y_n_input = str(input('y/n: ')).lower() if y_n_input == 'y': print("The '{}' restaurants in SoHo are .......\n".format(beginning_letter[0])) restaurants_in_soho(beginning_letter[0]) elif y_n_input == 'n': print("selected 'No'!") continue else: print("\nTry again, wrong selection!!") continue break else: exit() print("\n*** Thanks for considering SoHo restaurants! ***") exit()
true
fe2ad273f8168e73392cdc8f1cf19930375b29ff
lucabecci/IP-UNGS
/guia-1/exer16.py
841
4.125
4
""" # Determinar cuántos segundos tiene una hora, y cuántos tiene un día. # Escribir una expresión matemática que transforme un lapso de tiempo expresado en segundos a uno expresado en minutos. # Escribir otra para transformar a horas y una última que transforme a días. # Escribir un programa en Python que pida al usuario una cantidad de segundos y muestre cuantos minutos son, así como también cuantas horas y cuantos días. """ # 1 hour === 3600 seconds # 1 day === 86400 seconds # expr: x_seconds / 60 # expr2: x_hours / 36000 # expr3: x_days / 86400 to_minutes = 60 to_hours = 3600 to_days = 86400 print("===> Ingrese la cantidad de segundos a calcular:") n = int(input()) print("===> Su valor en minutos:", n / to_minutes) print("===> Su valor en horas:", n / to_hours) print("===> Su valor en days:", n / to_days)
false
70c0c7fb617551ed849ecd84f9e8b07d2d4bdbc3
runda87/she_codes_python
/user_input_playground.py
1,666
4.125
4
# name = input("what is your name?") # print(f"Hi {name}") # age = input(f" Hi {name}, how old are you ?") # years_until_100 = 100 - int(age) # print(f"Wow {name} You'll be 100 in {years_until_100} years!") # question 1 # number1 = input("enter a number =") # number2 = input("enter another number =") # total1 = int(number1) + int(number2) # print(f"these two numbers add up to = {total1}") # number3 = input("Enter another number = ") # number4 = input("go crayz and choose another number = ") # total2 = float(number3) - float(number4) # print(f"these two number equal = {total2}") # number5 = input("enter a number = ") # number6 = input("enter a number = ") # total3 = float(number5) + float(number6) # print(f"these two number equal = {total3}") # question 2 # print(f"another number question") # number7 = input("you know what to do enter another number = ") # number8 = input("enter a number =") # total4 = float(number7) * float(number8) # print(f" {number7} * {number8} equal= {total4}") # print(f"question 2") # number9 = input("enter a number = ") # number10 = input("enter a number = ") # total5 = int(number9) * int(number10) # print(f"{number9} * {number10} equals = {total5}") #Question 3 # number = input("how many kilometers? - ") # m = int (number) *1000 # cm = int (number) * 100000 # print(f"number km = {m} m") # print(f"number km = {cm} cm") # number = input("how many kilometers? - ") # m = int (number) * 1000 # cm = int (number) * 100000 # print(f"number km = {m} m") # print(f"number km = {cm} cm") #question 4 name = input(" what is your name ?") height = input("how tall are you (cm)?") print(f"{name} is {height}cms tall.")
false
cbc6012a9ffab6745f197b42a9a081f3c4d0c0af
polo1250/CS50-Projects
/Problem_Set_6/mario/more/mario.py
280
4.25
4
# Get the right value for the height while True: height = input("height: ") if (height.isdigit()) and (1 <= int(height) <= 8): height = int(height) break # Print the pyramid for i in range(1, height+1): print(" " * (height-i) + "#"*i + " " + "#"*i)
true
ca2f6b097aa5462fd678bc93466dcc90aef4c593
clintjason/flask_tutorial_series
/4_url_building/app.py
1,031
4.28125
4
from flask import Flask, url_for # import the Flask class and the url_for function ''' url_for() is used to build the url to a function. It takes as first argument the function name. If it takes any more arguments, those arguments will be variables used to build the url to the function. ''' app = Flask(__name__) # instantiate the flask application @app.route('/') def index(): return 'index' @app.route('/login') def login(): return 'login' @app.route('/user/<username>') def profile(username): return "{}'s profile".format(username) with app.test_request_context(): print(url_for('index')) #builds the url to index function. In this case '/' print(url_for('login')) #builds the url to the login function, in this case '/login' print(url_for('login', next='/')) # builds the url to the login function with and additional parameter '/' # not defined in the function print(url_for('profile', username='John Doe')) #builds the url to the profile function with the 'username' # variable already defined in the function.
true
fea11f166857be327b4a9919c671bf2d42c70d80
leeseoyoung98/javavara-assignment
/2nd week/python_if_elif.py
473
4.15625
4
my_name="이서영" print(f"my name is {my_name}.") #{}안에서 연산도 가능. ex) my_name.upper() #리스트 안에 리스트 list_in_list=[1, 2, [3, 4, 5], 6] print(len(list_in_list)) list_in_list[2][0] #index=2에서의 0번째 (chained index) #조건문 name = "이서영" if name == "이서영": print("백현을 JONNA 사랑한다.") else: print("오늘부로 입덕한다.") #ternary operator name = "이서영" value = 0 if name == "이서영" else 1
false
6bcdb7d66372b11c9631d05a25192db2104c1506
kaushiks90/FrequentInterviewPrograms
/Program28.py
425
4.15625
4
#Program to reverse an Array def reverseAnArray(arraynum): for x in range(len(arraynum)-1,-1,-1): print arraynum[x] reverseAnArray([56,3,45,12,89,34]) def reverseArrayMethod2(arraynum): limit=len(arraynum)/2 totalSize=len(arraynum) for x in range(0,limit): temp=arraynum[x] arraynum[x]=arraynum[totalSize-1] arraynum[totalSize-1]=temp totalSize-=1 print arraynum reverseArrayMethod2([56,3,45,12,89,34])
false
ac3397c2fcc339bacadefdbb11e4370581bc53c3
Beelthazad/PythonExercises
/EjerciciosBasicos/ejercicio33.py
665
4.28125
4
# -*- coding: utf-8 -*- # Implemente una función tal que dada una lista de palabras devuelva un conjunto con todos los caracteres de esas palabras. # Puedes hacer varias versiones, mediante un recorrido de las palabras de la lista y dentro recorrer los caracteres... # O por comprensión con un doble for o bien usando la funcion aplana que se ha viesto en un ejercicio anterior def lista_conjunto(lista): conjunto = set() for i in range(len(lista)): for x in range(len(lista[i])): print len(lista[i]) conjunto.add(lista[i][x]) return conjunto a = ['amigo', 'juanjo', 'josefino', 'lopetegui'] print lista_conjunto(a)
false
29551642e0ccfb4874e64ef84701c46bc5d4760c
CloudBIDeveloper/PythonTraining
/Code/Strings Methods.py
303
4.21875
4
str='Baxter Internationl' print(str.lower()) print(str.upper()) s1 = 'abc' s2 = '123' """ Each character of s2 is concatenated to the front of s1""" print('s1.join(s2):', s1.join(s2)) """ Each character of s1 is concatenated to the front of s2""" print('s2.join(s1):', s2.join(s1))
true
5950e80a726c7f13e3c94b36f7709395a6a6d0d5
allenmo/python_study
/049_is_prime.py
1,081
4.21875
4
import time def isPrime(n): if n==2 or n ==3: return True if n%2==0 or n<2: print '\t', 2 return False for i in range(3, int(n**0.5)+1, 2): #only odd numbers if n%i == 0: print '\t', i return False return True def is_prime(n): if n==2 or n==3: return True if n%2==0 or n<2: print '\t', 2 return False if n<9: return True if n%3 == 0: print '\t', 3 return False r = int(n**0.5) f = 5 while f <= r: #print '\t', f if n%f == 0: print '\t', f return False if n%(f+2) == 0: print '\t', f+2 return False f +=6 return True n = int(input('Input a number to check if prime:')) t1 = float(time.time()) while n != None: #if isPrime(n): if is_prime(n): print "It is a prime" else: print "Not a prime" t2 = float(time.time()) print int(t2-t1), "s used." n = int(input('Input a number to check if prime:')) t1 = float(time.time())
false
29b87f157ef7686c53d896f60724bd97189a2851
huskydj1/CSC_630_Machine_Learning
/Python Crash Course/collatz_naive.py
366
4.40625
4
def print_collatz(n): while (n != 1): print(n, end = ' ') if (n % 2 == 0): n = n // 2 else: n = 3*n + 1 print(1) num = input("Enter the number whose Collatz sequence you want to print: ") try: num = int(num) print_collatz(num) except: print("Error. You likely didn't input a positive integer.")
true
b34016ca1e68e8e207f7d781283cc0f9fb8d6586
santosh96r/test
/regular expression.py
2,428
4.28125
4
##import re ##var = 'python is the programming lang' # match used to search 1st word of string ##var1 = re.match("python" , var) ## ##print(var1) ##print(var1.group()) ##print(var1.start()) ##print(var1.end()) ##var = 'python is the programming lang' #search used to search any word in string ##var1 = re.search("the" , var) ## ##print(var1) ##print(var1.group()) ##print(var1.start()) ##print(var1.end()) ##var = 'python is the programming lang' #search used to search any word in string ##var1 = re.search("The" , var, re.I) ## ##print(var1) ##print(var1.group()) ##print(var1.start()) ##print(var1.end()) ##var = "<html><head><body>" ## ##var1 = re.search("<.*>", var) # .* method used to search anystring ##print(var1.group()) #greedy method ##print(var1.start()) ##print(var1.end()) ##var = "<html><head><body>" ## ##var1 = re.search("<.*?>", var) # .*? method used to search 1st word ##print(var1.group()) #non-greedy method ##print(var1.start()) ##print(var1.end()) ##var = "India is better than England" ##var1 = re.search(".* is .*",var) ##print(var1.group()) ##var = "India is better than England" ##var1 = re.search("(.*) is (.*)",var) ##print(var1.group()) ##print(var1.group(1)) ##print(var1.group(2)) ## ## ##var = "India is better than England" ##var1 = re.search("(.*) is (.*) (.*)",var) ##print(var1.group()) ##print(var1.group(1)) ##print(var1.group(2)) ##print(var1.group(3)) ##var = "INDIA !!! is my country @@@ 2021 with 349 in 43 and NEWDELHI with" ####var1 = re.findall("\d{1,3}",var) ##var1 = re.findall("\D{1,3}",var) ##var2 = re.findall("\w",var) # everythin but not special character ##var3 = re.findall("\w*",var) ##var4 = re.findall("\W+",var) ## ##print(var1) ##print(var2) ##print(var3) ##print(var4) ## ## ##var = "india is wprld is greatt is eng" ####var1 = re.split("is", var) ####print(var1) ##var1 = re.sub("is", "IS", var) ##print(var1) ##pattern = '^d...a$' ##my_string = "delha" ##var1 = re.search(pattern.my_string) ##print(var1.group()) import re ##pattern = '^d...i' ##my_string = "delhi" ##var1 = re.search(pattern,my_string) ##print(var1.group()) pattern = '[abc]' ##my_string = 'zbadc' my_string = 'abc de ce' var1 = re.search(pattern, my_string) print(var1.group())
false
2955a1dac0e1ff268564954509c7100dcbe8c334
shazia90/code-with-mosh
/numbers.py
268
4.25
4
print (10 + 3) print (10 - 3) print (10 * 3) print (10 / 3) #which gives float no print (10 // 3)# this gives integer print (10 % 3)#modulus remainder of division print (10 ** 3)#10 power 3 x = 10 x = x + 3 # a) x += 3 # b) a, b both are same print (x)
true
0a0c80b6182e450fe6d7c90e6fcd438dc8e0a6bf
pranshuag9/my-cp-codes
/geeks_for_geeks/count_total_permutations_possible_by_replacing_character_by_0_or_1/main.py
768
4.1875
4
""" @url: https://www.geeksforgeeks.org/count-permutations-possible-by-replacing-characters-in-a-binary-string/ @problem: Given a string S consisting of characters 0, 1, and ‘?’, the task is to count all possible combinations of the binary string formed by replacing ‘?’ by 0 or 1. Algorithm: Count the number of ? characters in string. Since ? can be replaced only by 0 or 1, so total permutations possbile are 2^count 1. Create count = 0 2. for every character in string: 3. if character equals "?", then, increment count 4. return 2^count """ def count_permutations(string): count = 0 for i in string: if i == "?": count += 1 return (2**count) if __name__ == "__main__": string = input() print(count_permutations(string))
true
2bd068d2ef3a4069eeeed84807cf730a806abac1
pranav1698/algorithms_implementation
/Problems/unique_character.py
318
4.15625
4
def uniqueChars(string): # Please add your code here char=list() for character in string: if character not in char: char.append(character) result="" for character in char: result = result + character return result # Main string = input() print(uniqueChars(string))
true
70956143a82115aff42295f241d966c6aa3d55f6
UN997/Python-Guide-for-Beginners
/Code/number_palindrome.py
271
4.15625
4
num = input('Enter any number : ') try: val = int(num) if num == str(num)[::-1]: print('The given number is PALINDROME') else: print('The given number is NOT a palindrome') except ValueError: print("That's not a valid number, Try Again !")
true
3480189cc08cc286884c0b0b4506997960f864bc
Matheuspaixaocrisostenes/Python
/ex009.py
569
4.15625
4
num = int(input('digite um numero: ')) print('-' * 12) print('{} x {:2} = {}'.format(num , 1 , num * 1)) print('{} x {:2} = {}'.format(num , 2 , num*2)) print('{} x {:2} = {}'. format(num , 3 , num*3)) print('{} x {:2} = {}'.format(num , 4 , num * 4)) print('{} x {:2} = {}'.format(num , 5 , num* 5)) print('{} x {:2} = {}'.format(num , 6 , num * 6)) print('{} x {:2} = {}'.format(num , 7 , num * 7)) print('{} x {:2} = {}'.format(num , 8 , num * 8)) print('{} x {:2} = {}' .format(num, 9 , num * 9)) print('{} x {:2} = {}'.format(num , 10 , num * 10)) print('-' * 12)
false
485369e97ba682adae1920a4eb135330bd8ef2d2
tecmaverick/pylearn
/src/43_algo/11_permutation_string.py
1,180
4.1875
4
# The number of elements for permutations for a given string is N Factorial = N! (N=Length of String) # When the order does matter it is a Permutation. # Permutation Types - # Repetation allowed - For a three digit lock, the repeat permutations are 10 X 10 X 10 = 1000 permutations # No Repeat - For a three digit lock, the non-repeat permutations are 10 X 9 X 8 = 720 permutations # 4 things can be placed in 4! = 4 × 3 × 2 × 1 = 24 different ways # Combination - When the order doesn't matter # Types # Repeat - # Non-repeat - Such as lottery numbers (2,14,15,27,30,33) Order doesn't matter # def permutations(elements): # if len(elements) <= 1: # yield elements # return # for perm in permutations(elements[1:]): # for i in range(len(elements)): # # nb elements[0:1] works in both string and list contexts # yield perm[:i] + elements[0:1] + perm[i:] # # # print(list(permutations("ABC"))) # ******* # Python native permutations from itertools import permutations print(list(permutations(["A","B","C","D"],3))) # 4 X 3 X 2 = 24 permutations # from itertools import combinations # combinations([1, 2, 3], 2)
true
372a40b95e5464150724b67f66c94b59c2424a04
tecmaverick/pylearn
/src/38_extended_args/extended_args_demo.py
2,116
4.90625
5
#extended argument syntax #this allows functions to receive variable number of positional arguments or named arguments #example for variable positional args, which accepts variable number of argument print "one","two" #example of variable keyword args, which accepts variable number of keyword aegs val = "hello {a}, {b}".format(a="Alpha",b="Good Morning!!!") print val #*args returns tuple, and are optional. The *args should precede **kargs. Any args passed after *args must be passed as **kargs #else it will lead to type error #**kargs returns dict, and are optional. If present these must be the last parameters, else an InvalidSyntax error will be thrown #format def add_nums(*args): print type(args) #returns tuple print(args) result = 0 for arg in args: result = result + arg print result add_nums(1,2,3,4,5) #keyword args def keyword_args(name, *args, **kargs): print("name: {}".format(name)) print("type: {}".format(type(args))) print("Args:{}".format(args)) print("Keyword Args:{}".format(kargs)) print("keyword args type: {}".format(type(kargs))) keyword_args(12,fno=1,sno=2,ops="*") #keyword_args(12,1,2,3,fno=1,sno=2,ops="*") #iterating *args with iter function def add_nums(*args): print "Adding nums with iter" itr = iter(args) itm = 0 while True: try: val = next(itr) itm += val except StopIteration: break else: print val print "Sum:{}".format(itm) add_nums(1,2,3) #Valid calls #def fn(fno, *args, **kargs) #invalid calls #def fn(**kargs, *args) #def fn(**kargs, fno, sno) #def fn(fno,sno,**kargs,defaultval) #def fn(*args, fno, sno, **kargs) #pass values to args parameter via tuple data = (1,2,3,4,5) def nums(fno,sno,*args): print fno, sno, args #tuple unpacking. Here the first 2 params will be mapped to first two args # and last three will be passed as tuple args nums(*data) #dict unpacking color1 = dict(red=1,green=2,blue=3,yellow=4,white=5) color = {"red":"1","green":"2","blue":"3","yellow":"4","white":"5"} def show_colors(red,green,blue,**kw_args): print red,green,blue,kw_args show_colors(**color) show_colors(**color1)
true
46bb500aa36043c5d94e7217dc2b4b9a04c71eb3
tecmaverick/pylearn
/src/39_scopes/scope_demo.py
1,051
4.1875
4
#LEGB Rule #Local, enlcosing, global, built-in my_global_var = "this is global" def outer(): outer_msg = "outer msg" val1 = {"test":"val"} def inner(): #here the variables in the enclosing scope in outer() function #is closed over by referencing the vairables referred #the enclosed variables can be viewed by printing the references #fnref.__closure__ #to view each closed variable #fnref.__closure__[0].cell_contents print outer_msg print val1 global my_global_var inner_msg = "inner msg" my_global_var = "12" return inner print ("global: {}".format(globals())) print ("locals: {}".format(locals())) print ("calling outer") inner = outer() print ("calling inner") print ("global var before modification:{}".format(my_global_var)) inner() print ("global var after modification:{}".format(my_global_var)) print ("is outer a closure:{}".format(outer.__closure__)) print ("is inner a closure:{}".format(inner.__closure__)) #Closures allows implementing of features like #Callback function reference #Function factories
true
73d5479e38e90c50d977e16ad32e549185b633ba
tecmaverick/pylearn
/src/32_closures/closuredemo.py
1,360
4.5
4
#Python closure is lst nested function that allows us to access variables of the outer function even after the outer function is closed. def my_name(name, time_of_day): def morning(): print "Hi {} Good Morning!".format(name) def evening(): print "Hi {} Good Evening!".format(name) def night(): print "Hi {} Good Night!".format(name) if time_of_day == "morning": return morning elif time_of_day == "evening": return evening elif time_of_day == "night": return night else: return morning greet_morning = my_name("Alfred","morning") greet_noon = my_name("Andrew","evening") greet_evening = my_name("Philip","night") greet_morning() greet_noon() greet_evening() #A def is executed at runtime, hence the memory ref of nested function change over time #example def calc(fno,sno,ops): def add(fno,sno): return fno + sno if ops == "+": print add return add(fno,sno) calc(11,22,"+") calc(12,22,"+") calc(10,20,"+") #A function is said to be first class if the function can be passed around like an object # ------------------------------------------------------------------ def greet(): # variable defined outside the inner function name = "John" # return lst nested anonymous function return lambda: "Hi " + name # call the outer function message = greet() # call the inner function print(message()) # Output: Hi John
true