blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0d40a5b9aa69331ddf02b23c01c481add9e31fdb
f2k5/Practice-python-problems
/pp_03.py
923
4.40625
4
""" Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5. Extras: 1. Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list. 2. Write this in one line of Python. 3. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user. """ a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #Doing the very first part: #------------------------------ print("Part 1 and 2:") a1 = [a1 for a1 in a if a1 < 5] print(a1) for x in a1: print(x) #----------------------------- #1 & 2. Already implemented above #3 --------------------------- user = int(input("Enter a number: ")) new_list = [m for m in a if m < user] print(new_list)
true
b50f395edc523564aa69938af3b9068995c217e6
cmcclanahan89/mastermnd_python
/Loops/ForLoops.py
482
4.40625
4
#For loops only works for things that iterable. An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop. # Intergers are not iterable. shoppingList = ['apple', 'cokes', 'food', 'ice cream'] adjectives = ['red', 'cold', 'delicous', 'frozen'] """ for items in shoppingList: print(items) """ for item in shoppingList: for adjective in adjectives: print(f"{item} is {adjective}")
true
f31d78ef22c92beb16fa75d7f9422eb0c59f4dbd
antonysamy931/python_research
/while_loop.py
273
4.15625
4
#while looping example python count = 0 while(count<5): print('count is :', count) count+=1 #while else looping python elsecount = 0 while elsecount<10: print('elsecount is :', elsecount) elsecount+=1 else: print('elsecount is :', elsecount)
true
9123ffa2a5cfdac40bf7011bb085daa5e478df9e
pasinimariano/masterUNSAM
/clase06/comparaciones.py
1,965
4.15625
4
# Ejercicio 6.19: Contar comparaciones en la búsqueda binaria # comparaciones.py def ordenar_lista(lista): """ Ordenara la lista del elemento menor al mayor. Esto se hace ya que el algoritmo necesita una lista ordenada, para su eficiencia. """ return sorted(lista) def donde_insertar(lista, x, ordenar=False): """ Se encargara de buscar el elemento x (pasado como parametro), en la lista seleccionada. Si el elemento se encuentra, se devolvera la posicion del elemento dentro de la lista. Caso contrario, se devolvera la posicion en donde se podria agregar el elemento. Como tercer parametro, se podrá especificar el parametro ordenar, el cual al pasarle True ordenará la lista. (eludir este paso si su lista esta correctamente ordenada). Devolvera 4 elementos, [0] Lista [1] Posicion del elemento o posible posicion [2] True o False si lo encuentra o no [3] Cantidad de comparaciones realizadas. """ if ordenar: lista_ = ordenar_lista(lista) else: lista_ = lista # Posicion inicial, la cual sera intercambiada por el recorrido de la lista pos = 0 # Por default diremos que el elemento no se encuentra en la lista encontrado = False # Cantidad de comparaciones que se realizan comp = 0 # Punteros de la lista inicio = 0 final = len(lista_) - 1 while inicio <= final: medio = (inicio + final) // 2 comp += 1 if lista_[medio] == x: pos = medio break elif lista_[medio] > x: final = medio - 1 else: inicio = medio + 1 if inicio > final and lista_[pos] != x: pos = inicio print(f'El elemento {x} podria insertarse en la posicion {pos}, en la lista: {lista_}') else: encontrado = True print(f'El elemento {x} se encuentra en la posicion {pos}, en la lista: {lista_}') return lista_, pos, comp, encontrado
false
0bc8ee5b017ba66fdd3dfa08349ff80da8f2635e
pasinimariano/masterUNSAM
/clase04/4.7MaxMin.py
1,390
4.15625
4
# Ejercicio 4.7: Búsqueda de máximo y mínimo # 4.7MaxMin.py def comparacion(lista): ''' Se encargará de mostrar el elemento más grande y el mas chico, de una lista de números''' num_max = lista[0] # Primer item de la lista num_min = lista[0] # Primer item de la lista for i in range(0, len(lista)): # Recorrera la lista completa if lista[i] >= num_max: # Compara el elemento de la lista con el num_max num_max = lista[i] # Si el elemento es mayor que el num_max, este último se reemplazará. if lista[i] <= num_min: # Compara el elemento de la lista con el num_min num_min = lista[i] # Si el elemento es menor que el num_min, este último se reemplazará. else: pass data = f'Max: {num_max}, Min: {num_min}' return data l1 = [1,2,7,2,3,4] print('Lista a comparar: ', l1) print(comparacion(l1)) print('------------------------------------------------------') l2 = [1,2,7,2,3,4] print('Lista a comparar: ', l2) print(comparacion(l2)) print('------------------------------------------------------') l3 = [-5,4] print('Lista a comparar: ', l3) print(comparacion(l3)) print('------------------------------------------------------') l4 = [-5,-4] print('Lista a comparar: ', l4) print(comparacion(l4)) print('------------------------------------------------------')
false
0f6c3dd2a3cb8d7f6a60dce9dca2c7aeee143330
comaecliptic/python_course
/6.functions/maximum.py
428
4.125
4
def maximum(numbers_list): """Return the biggest number in the list. Parameters ---------- numbers_list : list of int or float List with digits. Returns ------- m : int or float Maximum value in list. """ m = None for i in numbers_list: if m is None or i > m: m = i return m if __name__ == '__main__': print(maximum([100, 2, 3, 45, -2, 4]))
true
818fb13a35cbcdc6f64da250c37c3f809158d084
Kroket93/Pythagoras-theorem-calculator
/pythagoras_interface.py
2,878
4.125
4
from tkinter import * import math import sys running = True welcome_message_1 = "Pythagoras' theorem!" welcome_message_2 = "Calculate the hypotenuse of a right-angled triangle!" welcome_message_3 = "A right-angled triangle is a triangle in which one angle is 90 degrees" welcome_message_4 = "The two sides which make up the 90 degree angle are called the 'legs'" input_message_a = "Enter the length of the first leg: " input_message_b = "Enter the length of the second leg: " empty_string = " " hypotenuse_message = "The length of the hypotenuse is: " credits_message = "Made by Luuk van Wolferen" ### main window = Tk() window.title("Pythagoras' Theorem Calculator") c = StringVar() c.set("0") errormessage = StringVar() errormessage.set(" ") #labels Label(window, text=welcome_message_1, fg="black", font="none 12 bold").grid(row=1, column=0, sticky=W) Label(window, text=welcome_message_2, fg="black", font="none 12 bold").grid(row=2, column=0, sticky=W) Label(window, text=welcome_message_3, fg="black", font="none 12 bold").grid(row=3, column=0, sticky=W) Label(window, text=welcome_message_4, fg="black", font="none 12 bold").grid(row=4, column=0, sticky=W) Label(window, text=empty_string, fg="black", font="none 12 bold").grid(row=5, column=0, sticky=W) Label(window, text=input_message_a, fg="black", font="none 12 bold").grid(row=6, column=0) # Label(window, text=input_message_b, fg="black", font="none 12 bold").grid(row=8, column=0) # Label(window, text=empty_string, fg="black", font="none 12 bold").grid(row=10, column=0, sticky=W) Label(window, text=hypotenuse_message, fg="black", font="none 12 bold").grid(row=11, column=0) # Label(window, textvariable=c, fg="black", font="none 12 bold").grid(row=12, column=0) # errorlabel = Label(window, textvariable=errormessage, fg="black", font="none 12 bold").grid(row=13, column=0, sticky=W) Label(window, text=empty_string, fg="black", font="none 12 bold").grid(row=14, column=0, sticky=W) Label(window, text=empty_string, fg="black", font="none 12 bold").grid(row=15, column=0, sticky=W) Label(window, text=credits_message, fg="black", font="none 12 bold").grid(row=16, column=0, sticky=W) #text entry textentry_a = Entry(window, width=20, bg="grey") textentry_a.grid(row=7, column=0) textentry_b = Entry(window, width=20, bg="grey") textentry_b.grid(row=9, column=0) #run main loop while running: try: if len(textentry_a.get()) > 0 and len(textentry_b.get()) > 0: try: val_a = float(textentry_a.get()) val_b = float(textentry_b.get()) errormessage.set(" ") hypotenuse = math.sqrt(float(textentry_a.get())**2 + float(textentry_b.get())**2) c.set(str(hypotenuse)) except ValueError: errormessage.set("Please enter numbers only!") window.update_idletasks() window.update() except: pass
true
8e55ce13de77aa1762193136bb8bbe95f7df8d2a
nikitiwari/Learning_Python
/sort_words.py
364
4.125
4
print "Sorting of words" print "Enter a choice : 1. sort words in a sentence 2.sort alphabets in words" ch = (int)(raw_input()) st = raw_input("String :") if ch == 1 : w = st.split() w.sort() print " ".join(w) elif ch== 2 : w=[] for i in xrange(len(st)) : w.append(st[i]) w.sort() print "".join(w) else : print "Invalid Input"
false
f0d8c188b6f36e11d40f1a9c636208f857505422
aqualad11/InterviewPrep
/TripleByte/StudyGuide/python_collections.py
1,586
4.125
4
# This file is to practice and document how collections work # Counter. Returns a dict where the key is the element in the list and the value is the amount of times it occurs from collections import Counter dicto = [6,55,6,4,6,50,4,40,18,60,10,50] c = Counter(dicto) print(c) # defaultdict. Allows you to initialize keys that aren't already in the dictionary from collections import defaultdict dd = defaultdict(list) print(dd['hello']) # prints an empty list #namedtuple. Are easy to create, lightweight object types for simple tasks from collections import namedtuple Point = namedtuple('Point','x,y') pt1 = Point(1,2) pt2 = Point(3,4) dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y ) print(dot_product) # 11 #OrderedDict. A dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged. from collections import OrderedDict ordered_dictionary = OrderedDict() ordered_dictionary['a'] = 1 ordered_dictionary['b'] = 2 ordered_dictionary['c'] = 3 ordered_dictionary['d'] = 4 ordered_dictionary['e'] = 5 print(ordered_dictionary.keys()) # OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) # deque. A deque is a double-ended queue. It can be used to add or remove elements from both ends. from collections import deque d = deque() d.append(1) print(d) # deque([1]) d.appendleft(2) print(d) # deque([2, 1]) d.clear() print(d) # deque([]) d.extend('1') print(d) # deque(['1']) d.extendleft('234') print(d) # deque(['4', '3', '2', '1']) d.count('1')
true
5f2d33c64493e332d10ddb566a0ad9a74c39c05c
yashua4V/pyashua
/test_list.py
560
4.28125
4
#!/usr/bin/python3 #列表有关的函数 alist=[1,2,3] alist.append(4) alist.append([5,6]) print(alist) #还用序列扩展列表,向列表末尾追加元素 alist.extend([4,5,6]) print(alist) #insert(index,obj) alist.insert(0,0) print(alist) alist.insert(-1,8)#插入内容后,原位置的元素向后移 print(alist) alist = [3,534,3,234,565] #print(alist.sort()); print(alist) print(alist.reverse()) print(alist) print(alist.index(3)) print(alist.pop())#删除列表的最后一个元素,并且返回值 print(alist) print(alist.pop(1)) print(alist)
false
0c49c618a7623e2d59c76da06e3103ec7d52c7f4
AP-MI-2021/lab-4-Luci01
/main.py
2,274
4.125
4
def citire(): ''' Functie care citeste o lista :return: O lista de numere float ''' lista = [] dimensiune = int(input("Dimensiune lista: ")) while dimensiune: element = float(input()) lista.append(element) dimensiune = dimensiune - 1 return lista def afisare_parte_intreaga(lista): ''' Functie care returneaza partea intreaga a numerelor din lista :param lista: Lista de float uri :return: Partea intreaga a fiecarui numar ''' result = [] for numar in lista: result.append(int(numar)) return result def afisare_interval(lista): ''' Functie care afiseaza numerele intr-un inverval dat :param lista: Lista de float uri :return: Numerele care se afla in intervalul respectiv ''' lista = [] def extract_fractionar(numar): return str(numar).split('.')[1] def parte_intreaga_divizor(lista): result = [] for numar in lista: n=int(numar) m=extract_fractionar(numar) if n % m == 0 : result.append(numar) return result def meniu(): ''' Functie care afiseaza meniul ''' print("Meniu \n ") print("1.Citirea unei liste de numere float.") print("2.Afișarea părții întregi a tuturor numerelor din listă.") print("3.Afisarea tuturor numerelor care apartin unui interval") print("4.Afișarea tuturor numerelor a căror parte întreagă este divizor al părții fracționare.") print("5.Afișarea listei obținute din lista inițială în care numerele sunt înlocuite cu un string format din cuvinte care le descriu caracter cu caracter.") print("6.Iesire.") def main(): meniu() optiune = 0 lst = [] while optiune != 6 : optiune = int(input("Alegeti o optiune: ")) if optiune == 1 : lst = citire() elif optiune == 2 : secv1 = afisare_parte_intreaga(lst) print (secv1) elif optiune == 3 : secv2 = (lst) print (secv2) elif optiune == 4 : secv3 = parte_intreaga_divizor(lst) print (secv3) elif optiune == 5 : secv4 = (lst) print (secv4) elif optiune == 6 : break main()
false
972a19a680aa11752f9ccc92e6fdfd403d798d1a
Fgsj10/Python_Trainning
/Python_Lists/Code_Seven.py
520
4.21875
4
""" Author = Francisco Junior """ #Creating lists of structure for adding values listAge = [] listHeight = [] #Structure repetition for add values in lists for x in range(0,5): age = int(input("Enter with you age = ")) listAge.append(age) height = float(input("Enter with you height: ")) listHeight.append(height) #Printing lists with values ordened print("List of ages is: ", listAge) print("List of Height is: ", listHeight) #Printing lists of values inversed print(listAge[::-1]) print(listHeight[::-1])
true
ef450eb6772207f867767d6966a1f323e80a8fae
Fgsj10/Python_Trainning
/Python_Repetition/Code_Six.py
368
4.25
4
""" Author = Francisco Junior """ #Creating variables and received user input data sum = 0 for x in range(0,5): number = int(input("Enter with a number: ")) sum += number #Printing sum of numbers print("Sum of numbers is: %.2f " %(sum)) #Calculating average of numbers average = sum / 5 #Printing average print("Average of numbers is: %.2f " %(average))
true
53e64cf6b0f66aae7cd9866f002b268de66ce793
Fgsj10/Python_Trainning
/Python_Sequential/Code_Five.py
304
4.125
4
""" Author: Francisco Gomes """ #Received values of user meters = float(input("Enter with value em meters: ")) #Converting value meters in centimeters converter = (meters * 100) #printing value converted print("Value meters converted is: %.2f " %(converter), "cm") #Printing value with 2 decimal value
true
be11b5fd3cf1d7b63788b06d63866e2f5b0757e5
jezelldomer/if-else-program
/if-else_age.py
347
4.25
4
your_age = int(input("Enter your age: ")) if your_age >= 0 and your_age <= 12: print ("Kid") elif your_age >= 13 and your_age <= 17: print ("Teen") elif your_age == 18: print ("Debut") elif your_age >= 19: print ("Adult") else: print("Invalid input for your age. Please provide and enter a valid input. ") print ("--Done--")
true
a6ff77c11d3ec4f98c4800f600a1ab9e71557334
Josephcle7/csf
/hw1.py
1,412
4.40625
4
# Joseph Clevenger # Clejos10 # Computer Science Foundations # Programming as a Way of Life # Homework 1 # You may do your work by editing this file, or by typing code at the # command line and copying it into the appropriate part of this file when # you are done. When you are done, running this file should compute and # print the answers to all the problems. import math # makes the math.sqrt function available # Example of math.sqrt: print math.sqrt(2) print "Problem 1 solution follows:" #Original equation: x^2 - 5.86x + 8.5408 #Equation with Variables: ax^2 + bx + c a = 1.0 b = 5.86 c = 8.5408 x = (-b + math.sqrt(b**2 - 4*a*c)) / 2*a; y = (-b-math.sqrt(b**2 - 4*a*c)) / 2*a; print y print x, "\n" ### ### Problem 2 ### print "Problem 2 solution follows:" import os, sys os.chdir(os.path.dirname(sys.argv[0])) import hw1_test a = hw1_test.a b = hw1_test.b c = hw1_test.c d = hw1_test.d e = hw1_test.e f = hw1_test.f print a, "\n", b, "\n", c, "\n", d, "\n", e, "\n", f, "\n \n" ### ### Problem 3 ### print "Problem 3 solution follows:" print (a and b) or (~c) and not (d or e or f) ### ### Reflection ### #This assignment took me about five hours. The reading all took me about three hours and the actual programming excersized took me one and a half to two hours. #The reading, tutorials, and lecture definitely contained everything I needed to complete in this assignment.
true
7608d959b7eb5f85bf583cb9f9766a0d8bfec51b
Bryan-Brito/IFRN
/Programação de Computadores (NCT)/LISTAS/Lista #04.2/Lista #04.2 Questão 1.py
370
4.21875
4
X = int(input("Insira um valor")) Y = X%2 if X > 0 and Y == 0: print("Seu número é par e positivo") elif X < 0 and Y == 0: print("Seu número é par e negativo") elif X > 0 and Y == 1: print("Seu número é ímpar e positivo") elif X < 0 and Y == 1: print("Seu número é ímpar e negativo") elif X == 0: print("Seu número é nulo")
false
24538454ec8b56a709c8d46b7a6cc1d7a862b8a9
abhinav-mk/War-Game
/Modules/Player.py
1,355
4.3125
4
class Player(): """ This player class initializes a player with a unique ID and exposes functions to play a card and assign/add cards to the player's deck. """ def __init__(self, player_id): self.player_id = player_id self.player_deck = [] def assign_cards(self, cards): """ This function adds the cards to the players hand/deck. Usage: useful during the beginning of the game where each user is assigned cards and also to add the cards that are won during a round to the hand/deck. """ try: if len(cards) < 1: raise ValueError("Please assign at least one card to the player") self.player_deck += cards except ValueError as error: print(error) exit() def is_deck_empty(self): """ This function returns true if the player does not possess any card. Usage: useful to eliminate the player from the game. """ return len(self.player_deck) == 0 def play_a_card(self): try: if len(self.player_deck) == 0: raise ValueError("This player does not have any cards or is not playing") return self.player_deck.pop(0) except ValueError as error: print(error) exit()
true
c6e04e7c730328eb7a1f202cda33decdb3794c4a
sughosneo/dsalgo
/src/basic/ReverseStringUsingRecursion.py
1,466
4.5
4
''' Below script shows a sample of how we can reverse one string. This is an inplace reverse algorithm. This script also shows some of the standard method to reverse one string using it chars. ''' def getPythonicReversedStr(inputStr): ''' Function to reverse the string using python built in functions. :param inputStr: :return: Reversed string. ''' if inputStr and len(inputStr) > 0: return "".join(reversed(inputStr)) def getNaturalReversedStr(inputStr): ''' Function to reverse string using for/while loop. :param inputStr: Actual string value :return: reversed string ''' reversedStr = "" length = len(inputStr) if inputStr and length > 0: while(length>0): reversedStr = reversedStr + inputStr[length-1] length = length - 1 return reversedStr def getReversedStr(inputStr): ''' Function to reverse the string using recursion. :param inputStr: :return: Return reversed string. ''' if len(inputStr) == 1: return inputStr else: return inputStr[len(inputStr)-1] + getReversedStr(inputStr[0:len(inputStr)-1]) if __name__ == '__main__': inputStr = "sumit" reversedStr = getReversedStr(inputStr) print(reversedStr) reversedStr2 = getNaturalReversedStr(inputStr) print(reversedStr2) reversedStr3 = getPythonicReversedStr(inputStr) print(reversedStr3)
true
9d4709d30a44aa637820d3420f0f43816b4548b0
sughosneo/dsalgo
/src/custom/Heap.py
1,588
4.25
4
''' Below is the implementation of Heap data structure. Standard operation has been captured. Sample example has been provided in here - ''' class Heap: __heapList = None __heapSize = None def __init__(self): self.__heapList = [0] self.__heapSize = 0 ''' Below method would actually insert individual item in the array. Then heapify method would actually keep the heap structure. ''' def insert(self,item): if item: self.__heapList.append(item) self.__heapSize = self.__heapSize + 1 self.heapify(self.__heapSize) ''' Below method would actually to keep the structure of the heap property. ''' def heapify(self,index): print(self.__heapList) print(index,index // 2) while index // 2 > 0: if self.__heapList[index] < self.__heapList[index // 2]: tmp = self.__heapList[index // 2] self.__heapList[index // 2] = self.__heapList[index] self.__heapList[index] = tmp index = index // 2 def getTotalitems(self): return self.__heapSize def printHeapItems(self): print(self.__heapList) def delMin(self,itemValue): pass if __name__ == '__main__': heap = Heap() itemList = [5,9,11,14,18,19,21,33,17,27] #itemList = [1, 9, 8, 2] for eachItem in itemList: heap.insert(eachItem) print("---------------") print(heap.getTotalitems()) print("---------------") heap.printHeapItems()
true
c7b7e1f15483a90e6e0df1863983847b53fa5657
sughosneo/dsalgo
/src/sorting/BinaryInsertionSort.py
1,592
4.46875
4
''' In the binary insertion sort we would require to find the location using binary search. ''' def binarySearch(arrInput,itemToSearch): middleElementIndex = len(arrInput) // 2 if itemToSearch == arrInput[middleElementIndex]: return middleElementIndex else: if len(arrInput) > 1: # Means if searchable item value is less than middle element. if itemToSearch < arrInput[middleElementIndex]: leftArray = arrInput[0:middleElementIndex] return binarySearch(leftArray, itemToSearch) else: rightArray = arrInput[middleElementIndex:len(arrInput)] return binarySearch(rightArray, itemToSearch) else: return -1 def insertionSort(arrInput): # This loop would run from [4, 2, 9, 3, 5] for i in range(1, len(arrInput)): # print(arrInput[i]) key = arrInput[i] j = i - 1 # It would start with 0th position # In actual insertion sort we perform below operation ## Move elements of arrInput[0...i-1], that are greater than key, to one position ahead of ## their current position. # But to reduce down the complexity we can use binary search to find correct location. loc = binarySearch(arrInput, key); while (j >= loc): arrInput[j + 1] = arrInput[j] j = j - 1 arrInput[j + 1] = key return arrInput if __name__ == '__main__': arrInput = [1, 4, 2, 9, 3, 5] sortedArr = insertionSort(arrInput) print(sortedArr)
true
4cfe60fbcdcea54f31be4f1726d319c10f13d37d
zhan006/Algorithms
/SimplifyPath.py
1,456
4.28125
4
'''Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path. In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.''' class Solution: def simplifyPath(self, path): """ :type path: str :rtype: str """ import re pattern=r'/([a-z A-Z . _ \d]+)' pth=re.findall(pattern,path) if len(pth)==0: return '/' order=-1 res=[] for i in range(len(pth)): if order==-1: if pth[i]=='..' or pth[i]=='.': pass else: order+=1 res.append(pth[i]) else: if pth[i]=='..': order-=1 res.pop() elif pth[i]=='.': pass else: order+=1 res.append(pth[i]) res='/'+'/'.join(res) return res
true
efeaf1dd141e51068553835dfc5bb9a8789a304b
ilikeya/prac.py
/work/string formatting.py
401
4.125
4
""" CP1404/CP5632 - Practical Various examples of using Python string formatting with the str.format() method Want to read more about it? https://docs.python.org/3/library/string.html#formatstrings """ name = "Gibson L-5 CES" year = 1922 cost = 16035.4 print("{} {} for about ${:,.0f}!".format(year, name, cost)) print() numbers = {0, 50, 100, 150} for number in numbers: print("{:>3}".format(number))
true
18bf0c5ba93a3ddfe9511978818f227a417fbaed
Nathalia11/Estudos_Python
/aula1_2.py
507
4.1875
4
print ('meu primeiro programa em Python') a = 2 b = 3 soma = a + b print(soma) #Interagir com usuario a = int(input('Entre com o primeiro valor:')) b = int(input('Entre com o segundo valor:')) print(type(a)) soma = a + b subtracao = a - b multiplicacao = a * b divisao = a / b resto = a % b print ('soma: {}'.format(soma)) print('soma: ' + str(soma)) # = print(soma) mas com texto print(subtracao) print(multiplicacao) print(int(divisao)) #o int tira a casa dos decimais/aredonda o numero print(resto)
false
a62d62058a188f9f07a747d57d4462df42db8691
littlebabyshit/python_automation1
/first_python/answer.py
606
4.21875
4
""" 1.python函数参数这块看的不是很明白,默认值只会执行一次,这条规则在默认值为可变对象时很重要,希望老师再举个例子讲解一下; 2.函数的缩进特别关键,如果格式不对,就会返回语法错误,如何确保缩进格式的正确书写? 3.print和return的区别以及应用场景 4.字典传参和元组传参,解包参数列表这 5.字面量插值这块求实例 """ class Name: age = 111 def __init__(self): self.name = "bob" def name_n(self): self.joey = 111 return self.name print(Name.age)
false
7310c4f7f2a03ad744c27a44aa3810b2de43eaaf
Anand111993/Python_Practice
/palimdrom.py
234
4.34375
4
def is_palindrome(string): return string[::-1] == string word = input("Enter your word : ") if is_palindrome(word): print("'{}' is a palindrome".format(word)) else: print("'{}' is not a palindrome".format(word))
false
c17557643244d980d9660b208e1dac31ceffa798
jarvis-666/Automate_Python
/assertions.py
783
4.21875
4
#! python3 # assertions shouldn't be in the try-except block # they should just terminate the program, if the given condition is a fallocy # assertions are for programmer errors and not to handle user errors # using assertions in your code makes it to fail faster, shorten the time between original cause of the bug and when # you actually notice the bug # this reduces the amount of code that needs to be checked for bugs, because you are using safeguards to ensure # the sanity is maintained in the code # # a, b = 3, 0 # # assert b != 0, "Can't divide by zero" # # print(a // b) list_of_temperatures = [40, 26, 39, 30, 25, 21] for temp in list_of_temperatures: assert temp >= 26, "Whole batch has been rejected" print(f"{temp} means hot")
true
4ca30770f588365312943dee2118ed7e9e83d795
RyanHankss/PRG_16.1
/printTime.py
305
4.28125
4
class Time(object): """ Represents the time of day. attributes: hour, minute, second """ t = Time() hours = 1 minutes = 59 seconds = 30 def print_time(t): print('{0:0>2d}'.format(hours) + ':' + '{0:0>2d}'.format(minutes) + ':' + '{0:0>2d}'.format(seconds)) print_time(t)
true
0afad2b7f2f740ecc213bf00bd220443af4a5478
Runzhou-Li/CP1404-practicals
/prac_04/lists_warmup.py
1,032
4.25
4
numbers = [3, 1, 4, 1, 5, 9, 2] # What values do the following expressions have? # Without running the code, write down your answers to these questions (on paper, or in your Python file as a comment), # then use Python to see if you were correct # numbers[0] 3 # numbers[-1] 2 # numbers[3] 1 # numbers[:-1] [3, 1, 4, 1, 5, 9] # numbers[3:4] [1] # 5 in numbers True # 7 in numbers False # "3" in numbers False # numbers + [6, 5, 3] [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] print(numbers[0]) print(numbers[-1]) print(numbers[3]) print(numbers[:-1]) print(numbers[3:4]) print(5 in numbers) print(7 in numbers) print("3" in numbers) print(numbers + [6, 5, 3]) # Write Python expressions (in your Python file) to achieve the following: # Change the first element of numbers to "ten" (the string, not the number 10) numbers[0] = "ten" # Change the last element of numbers to 1 numbers[-1] = 1 # Get all the elements from numbers except the first two (slice) print(numbers[2:]) # Check if 9 is an element of numbers print(9 in numbers)
true
5be5263b4f17d774b1bdb5133715129ba73bd1da
xiajingdongning/liuyangli
/Mastermind/src/Marble.py
1,888
4.15625
4
import turtle from Point import Point MARBLE_RADIUS = 15 class Marble: def __init__(self, position, color, size): self.pen = self.new_pen() self.color = color self.position = position self.visible = False self.is_empty = True self.pen.hideturtle() self.size = size self.pen.speed(0) # set to fastest drawing def new_pen(self): return turtle.Turtle() def set_color(self, color): self.color = color self.is_empty = False def get_color(self): return self.color def draw(self): # if self.visible and not self.is_empty: # return self.pen.up() self.pen.goto(self.position.x, self.position.y) self.visible = True self.is_empty = False self.pen.down() self.pen.fillcolor(self.color) self.pen.begin_fill() self.pen.circle(self.size) self.pen.end_fill() def draw_empty(self): self.erase() self.pen.up() self.pen.goto(self.position.x, self.position.y) self.visible = True self.is_empty = True self.pen.down() self.pen.circle(self.size) def erase(self): self.visible = False self.pen.clear() def clicked_in_region(self, x, y): if abs(x - self.position.x) <= self.size * 2 and \ abs(y - self.position.y) <= self.size * 2: return True return False def set_empty(self): self.is_empty = False def main(): marble = Marble(Point(0,0), "blue", 10) marble.draw_empty() k = input("enter something here and I'll fill the marble > ") marble.draw() k = input("enter something here and I'll erase the marble > ") marble.erase() print(marble.clicked_in_region(10,10)) if __name__ == "__main__": main()
false
ece5c2b8b59d214d22d4dd3025cf8b4abdc288c4
marjamis/kata-python
/examples/text_string_formatting.py
2,042
4.65625
5
import helpers.formatting as formatting test_data='Here is some test data' numeric_data=3.091 def fstrings(): print(f"This is an fstring, it will replace the braced values for the relevant variable. For example: {test_data.upper()}. Numeric data: {numeric_data:.1f}") def format_function_string(): print('This is a formatted string similar to the fstring approach but a bit less easy to read. For example: {data}'.format(data=test_data.lower())) print('A different way to populate the string, purely based on {}. For example: {} and some numeric data: {:.1f}'.format("position", test_data.lower(), numeric_data)) print('Yet another way to display data based on positon. For example: {1} and some numeric data: {0:.2f}'.format(numeric_data, test_data.upper())) def numbers(): print(f'To make numbers easier to read _\'s can be used in numbers in the code but wont be displayed, such as: {1_000_000}') numbers = list(range(3, 30, 4)) print(f'Inbuilt functionality to find the min and/or max of a list of numbers, for example the list is {numbers} with a min of {min(numbers)} and a max of {max(numbers)}. They also all add up to: {sum(numbers)}. There are lots of these helper functions, so it\'s always worth checking the documentation first.') def main(): print('There are many formatting options for text, such as seen with the formatting of numeric_data above. Check documentation for more details.') print('\nMy preffered way for larger text formatting is the use of something like jinja2. Check my examples under: ../markdown_templates_j2.\n') runs = [ { 'Title': 'f strings', 'FunctionName': fstrings, 'Comment': 'Easier to read that .format() examples but only available in python 3.6 and above.', }, { 'Title': 'format() strings', 'FunctionName': format_function_string, 'Comment': 'Another way to format strings', }, { 'Title': 'Numbers', 'FunctionName': numbers, } ] formatting.wrapper(runs) if __name__ == '__main__': main()
true
1e667fa035b17c4f9f4d4b857d0955ca975debc1
Froloket64/py3-progs
/calc.py
940
4.28125
4
### Claqulator!! ### from math import factorial, sqrt math = input('Your math: ') ## Asking for the math to perform math_lst = math.split() for pos, item in enumerate( math_lst ): ## Doing things for our user-friendly language to understand the math operations if item == '^': ## |- Changing "^" (power symbol) to "**" math_lst[pos] = '**' ## | elif '!' in item: ## |- Changing "!" (factorial symbol) to "factorial()" (from "math" lib) math_lst[pos] = f'factorial({item[:-1]})' ## | ## Debug: # print(math_lst) if math_lst == []: pass else: ## (Trying to) catch the possibe errors try: print( f'Answer: {eval( " ".join(math_lst) )}' ) ## Evaluating the math and printing the result except NameError: ## Messing the math operation syntax print('No such operation') # except SyntaxError: # pass
true
7f063b4748999c66f47c6fd9e4f790331a37fab0
mkioga/42_python_MusicFiles
/challenge2.py
1,143
4.53125
5
# =============== # challenge2.py # =============== # ================================= # List comprehension challenge 2 # ================================= # In case it's not obvious, a list comprehension produces a list, but # it doesn't have to be given a list to iterate over. # # You can use a list comprehension with any iterable type, so we'll # write a comprehension to convert dimensions from inches to centimetres. # # Our dimensions will be represented by a tuple, for the length, width and height. # # There are 2.54 centimetres to 1 inch. inch_measurement = (3, 8, 20) cm_measurement = [inch * 2.54 for inch in inch_measurement] print("cm_measurement list = {}".format(cm_measurement)) # Once you've got the correct values, change the code to produce a tuple, rather than a list. # This is converting above cm_measurement to a tuple: cm_measurement = tuple(cm_measurement) print("cm_measurement tuple1 = {}".format(cm_measurement)) # This is converting directly from the list comprehension: cm_measurement = tuple([inch * 2.54 for inch in inch_measurement]) print("cm_measurement tuple2 = {}".format(cm_measurement))
true
68365aeeedb4b3d907ef52552cd021796ad49111
xuesongTU/Algorithm
/sort/sorting.py
1,256
4.28125
4
def insertion_sort(array): for i in range(0, len(array)): j = i - 1 if array[j] > array[i]: key = array[i] array[i] = array[j] j -= 1 while j >= 0 and key < array[j]: array[j + 1] = array[j] j -= 1 array[j + 1] = key return array def bubble_sort(array): for i in range(0, len(array)): for j in range(0, i): if array[j + 1] < array[j]: temp = array[j + 1] array[j + 1] = array[j] array[j] = temp return array def merge(left, right): len_l = len(left) len_r = len(right) combo = [] l = 0 r = 0 while l < len_l and r < len_r: if left[l] < right[r]: combo.append(left[l]) l += 1 else: combo.append(right[r]) r += 1 combo = combo + left[l:] + right[r:] return combo def merge_sort(array): if len(array) == 1: return array mid = len(array) // 2 left = merge_sort(array[:mid]) right = merge_sort(array[mid:]) return merge(left, right) if __name__ == "__main__": A = [1, 3, 6, 2, 5, 8] #A = [1] A = merge_sort(A) print(A)
false
8133b3dc758359c2988c9d4e695aabee53675f55
Williamcassimiro/Programas_Basicos_Para_Logica
/Desafio 101.py
667
4.21875
4
#Exercício Python 101: Crie um programa que tenha uma função chamada voto() # que vai receber como parâmetro o ano de nascimento de uma pessoa, # retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL e OBRIGATÓRIO nas eleições. def voto(ano): from datetime import date atual = date.today().year idade = atual - ano if idade < 16: return f' Com {idade} anos : Não vota!' elif 16 <= idade < 18 or idade > 65: return f' Com {idade} anos: Voto opcional' else: return f'Com {idade} anos: Voto obrigatorio' nascimento = int(input("Qual foi ano do seu nascimento?")) print(voto(nascimento))
false
13bb98a7a57da922557d58329918ed14e2b6a0ac
elifmeseci/python-examples
/Basic Data Structures and Objects/boy_kilo_index.py
295
4.125
4
""" Kullanıcıdan aldığınız boy ve kilo değerlerine göre kullanıcının beden kitle indeksini bulun. Beden Kitle İndeksi : Kilo / Boy(m) Boy(m) """ kilo = int(input("kilonuz: ")) boy = float(input("boyunuz: ")) indeks = kilo/(boy**2) print("Beden kitle indeksiniz: {}".format(indeks))
false
0be6f7ed85bb9b6c794946359743c7394969d749
r4gus/Sichere_Programmierung
/Praktikum1/SP-P1-Sobott-Sugar/Code/affinecipher.py
1,488
4.3125
4
#! /usr/bin/python3 import sys import argparse from string import ascii_lowercase from aclib import decode, acDecrypt, acEncrypt def crypt(path: str, key: str, fun) -> None: """ Encodes/ Decodes the file pointed to by 'path' using the specified function 'fun'. """ k1, k2 = decode(key) try: with open(path, "r") as f: print(fun(k1, k2, f.read())) except FileNotFoundError: print( "usage: affinecipher.py [-h] {e,d} key path\n" + "error: The specified file could not be opened! Please ensure, that\n" + " you've provided the right path and that the file does exist.") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Encrypt or decrypt a file using the affine cipher") parser.add_argument("mode", choices=["e", "d"], help="[e]ncrypt or [d]ecrpyt the file") parser.add_argument("key", help="String with exactly two lower case ascii letters") parser.add_argument("path", help="File path") args = parser.parse_args() mode = args.mode key = args.key path = args.path if len(key) != 2 or not key[0] in ascii_lowercase or not key[1] in ascii_lowercase: print( "usage: " + sys.argv[0] + "[-h] {e,d} key path\n" + "error: Invalid key pair. Use '-h' for help.") else: if mode == "e": crypt(path, key, acEncrypt) elif mode == "d": crypt(path, key, acDecrypt)
true
df38bc0783c37010bda0ca5fdcd46be32dffd1ef
Cashfire/leetcodePython
/is-monotonic.py
895
4.28125
4
def is_monotonic(array): # very neat solution if len(array) <= 2: return True is_non_increasing = True is_non_decreasing = True for i in range(1, len(array)): n1, n2 = array[i-1], array[i] if n1 < n2: is_non_increasing = False if n1 > n2: is_non_decreasing = False return is_non_decreasing or is_non_increasing def isMonotonic(array): # optimized to early stop if len(array) <= 2: return True main_direct = 0 for i in range(1, len(array)): diff = array[i] - array[i-1] if diff == 0: continue if main_direct == 0: main_direct = diff continue if main_direct/diff < 0: return False return True if __name__ == "__main__": arr1 = [0,1,-4,-5] print(is_monotonic(arr1)) print(isMonotonic(arr1))
false
e820443b708c91421e4367d8d9cc35c6144c6af2
dfyisco/Dfy_first_repo
/priority_queue.py
2,046
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 28 23:35:52 2020 @author: ThinkPad """ class Node: # Create a class of node def __init__(self, value = None, next = None): self.value = value self.next = next # point to the next node class PriorityQueue: # Create Priority Queue class def __init__(self): self.root = Node() # Set the root node self.length = 0 #Set the length of queue def is_empty(self): return (self.length == 0) # judge by whether length is 0 def clear(self): # reset the queue self.root = Node() self.length = 0 def insertInQueue(self, content, priority): node = Node([content,priority]) # the new node if self.root.next is None: # the first node self.root.next = node else: cur_node = self.root.next # define a current node for i in range(self.length): if self.root.next == cur_node and cur_node.value[1] > node.value[1]: # the situation add a node after root node.next = self.root.next self.root.next = node break elif cur_node.next == None and cur_node.value[1] <= node.value[1]: # the situation add a node at the tail cur_node.next = node break elif cur_node.value[1] <= node.value[1] and cur_node.next.value[1] > node.value[1]: #the situation add a node between 2 nodes node.next = cur_node.next cur_node.next = node break else: cur_node = cur_node.next # current node turn to the next one if can't add after this temporary one self.length += 1 # +1 to the length def removeFromQueue(self): out = self.root.next.value[0] # the value print out self.root.next = self.root.next.next self.length -= 1 # -1 to the length return out
true
ce0a1141d284844f940f9f534a46b852766c7a2a
tianmii/PythonLearning
/testdemy_warmup2.py
686
4.125
4
""" Fizzbuzz challenge print from 1 - 100 if number is divisible by 3, print "fizz" if number is divisible by 5, print "buzz" if number is divisible by 3 & 5, print "fizzbuzz" Bonus: Wrap it in a function """ # numbers = list(range(1, 11)) # print(numbers) # == 0 will mean the remainder is 0 # fizzbuzz needs to happen first because if % 3 only is first # you will only get Fizz on number 15 def fizzbuzz(): for number in range(1, 101): if number % 3 == 0 and number % 5 ==0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) fizzbuzz()
true
b0fade9767123cbd7edaabbd4aa1f7208ebabef4
tianmii/PythonLearning
/Proj1_99Bottles.py
773
4.15625
4
# 99 bottles # List of numbers, do not manually type them in, use a built in function # "Take one down, pass it around" but cannot manually type numbers into song # reach one bottle left, bottles becomes bottle # Blank line between each verse of the song bottles = 5 while bottles > 0: print("{current_num} bottles of beer on the wall, {current_num} bottles of beer.".format( current_num=bottles )) print("Take one down pass it around") bottles = bottles - 1 if bottles == 1: print("{current_num} bottle of beer on the wall!\n".format(current_num=bottles)) elif bottles > 1: print("{current_num} bottles of beer on the wall!\n".format(current_num=bottles)) else: print("No more bottles of beer on the wall!")
true
7e5793276877bea7cc3802e48bf9703978b8569b
alexkassil/Advent-of-Code-2017
/Day04/day4.py
1,432
4.28125
4
def valid(phrase): """ Checks if passphrase only contains distinct words. >>> valid('aa bb cc dd') True >>> valid('aa bb aa') False >>> valid('aa bb aaa') True """ words = [] series_of_words = phrase.split(' ') words.append(series_of_words.pop()) for word in series_of_words: if word in words: return False words.append(word) return True def valid_anagram(phrase): """ Checks if passphrase only contains words that aren't anagrams of each other. >>> valid_anagram('abcde fghij') True >>> valid_anagram('abcde xyz ecdab') False >>> valid_anagram('a ab abc abd abf abj') True >>> valid_anagram('iiii oiii ooii oooi oooo') True >>> valid_anagram('oiii ioii iioi iiio') False """ words = [] series_of_words = phrase.split(' ') words.append(''.join(sorted(series_of_words.pop()))) for word in series_of_words: word = ''.join(sorted(word)) if word in words: return False words.append(word) return True if __name__ == "__main__": f = open("input.txt") inpt = f.read().strip() f.close() total1 = 0 total2 = 0 phrases = inpt.split('\n') print(len(phrases)) for phrase in phrases: if valid(phrase): total1 += 1 if valid_anagram(phrase): total2 += 1 print(total1, total2)
false
ad924c2f93ef1016c783a9302fd5904fa253df2e
Moon-is-beautiful/zihao2021
/FindPrimeFactors.py
1,273
4.15625
4
# File: FindPrimeFactors.py # Student: zihao # UT EID:zh4473 # Course Name: CS303E # # Date Created:4/9/2021 # Date Last Modified: 4/9/2021 # Description of Program: find prime factors import math def isPrime(num): if(num<2 or num % 2 ==0): return(num==2) divisor=3 while(divisor<=math.sqrt(num)): if(num%divisor==0): return False else: divisor+=2 return True def findNextPrime(num): if(num<2): return 2 if(num%2==0): num-=1 guess=num+2 while(not isPrime(guess)): guess+=2 return guess def findPrimeF(num): if(isPrime(num)): return list([num]) else: factors=list() d=2 while(num>1): if(num%d==0): factors.append(d) num=num/d else: d=findNextPrime(d) return factors while(True): dababy=eval(input("Enter a positive integer (or 0 to stop): ")) if(dababy== 0): print("Goodbye!") break elif(dababy<0): print(" Negative integer entered. Try again.") elif(dababy==1): print(" 1 has no prime factorization.") else: print(" The prime factorization of 104 is:",findPrimeF(dababy))
true
20e98776300f1defb2b05b34cd7a5e46ba8c98d5
Moon-is-beautiful/zihao2021
/DaysInMonth.py
999
4.28125
4
# File: DaysInMonth.py # Student: zihao hong # UT EID:zh4473 # Course Name: CS303E # # Date Created: 2/25/2021 # Date Last Modified: 2/25/2021 # Description of Program: tells you how many days a month has. import math y=int(input("enter the year: ")) m=int(input("enter the month: ")) if (y%4==0): if(y%100==0): if(y%400==0): IsLeapYear=True else: IsLeapYear=False else: IsLeapYear=True else: IsLeapYear=False if m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12: n=31 else: if(m==2): if(IsLeapYear==True): n=29 else: n=28 else: n=30 if (m==1): w="January" if (m==2): w="February" if (m==3): w="March" if (m==4): w="April" if (m==5): w="May" if (m==6): w="June" if (m==7): w="July" if (m==8): w="August" if (m==9): w="September" if (m==10): w="October" if (m==11): w="November" if (m==12): w="December" print(w,y,"has",n,"days")
false
c36313aac54a00935964c671a29e37a2b0b43023
whyadiwhy/Awesome_Python_Scripts
/BasicPythonScripts/Grade Calculator/grade_calculator.py
1,572
4.125
4
def main(): print(" Enter the marks of English Hindi Math Science S.St Computer ") # subject name subjects = ["English ", "Hindi", "Math ", " Science", " S.St ", " Computer "] marks = [] # defining the marks variable total = 0 # initializing the variable # Taking inputs one by one for i in range(6): # Iteration of loop j = i print(" Enter the Marks of ", subjects[j], end=" ") marks.insert(i, input()) # Taking inputs marks one by one # Adding the markks for i in range(6): total = total + int(marks[i]) print(" Total marks Marks = ", total, " and ", end=" ") average = total / len(subjects) # Condition checking for grade if average >= 91 and average <= 100: print(" Grade is A1") elif average >= 81 and average <= 90: print(" Grade is A2") elif average >= 71 and average <= 80: print(" Grade is B1") elif average >= 61 and average <= 70: print(" Grade is B2") elif average >= 51 and average <= 60: print(" Grade is C1") elif average >= 41 and average <= 50: print(" Grade is C2") elif average >= 33 and average <= 40: print(" Grade is D") elif average >= 21 and average <= 32: print(" Grade is E1") elif average >= 0 and average <= 20: print(" Grade is E2") else: print("Inputs are not valid Kindly Give Correct Input") choice = int(input(" Enter 1 to continue and else to exit ")) if choice == 1: main() else: exit() main()
true
0781b67ced87f2f3d7d50cb0a251728ec02d3798
whyadiwhy/Awesome_Python_Scripts
/BasicPythonScripts/Password Validator/password_validator.py
1,734
4.4375
4
import string def passwordValidator(): """ Validates passwords to match specific rules : return: str """ # display rules that a password must conform to print('\nYour password should: ') print('\t- Have a minimum length of 6;') print('\t- Have a maximum length of 12;') print('\t- Contain at least an uppercase letter or a lowercase letter') print('\t- Contain at least a number;') print('\t- Contain at least a special character (such as @,+,£,$,%,*^,etc);') print('\t- Not contain space(s).') # get user's password userPassword = input('\nEnter a valid password: ').strip() # check if user's password conforms # to the rules above if not(6 <= len(userPassword) <= 12): message = 'Invalid Password..your password should have a minimum ' message += 'length of 6 and a maximum length of 12' return message if ' ' in userPassword: message = 'Invalid Password..your password shouldn\'t contain space(s)' return message if not any(i in string.ascii_letters for i in userPassword): message = 'Invalid Password..your password should contain at least ' message += 'an uppercase letter and a lowercase letter' return message if not any(i in string.digits for i in userPassword): message = 'Invalid Password..your password should contain at least a number' return message if not any(i in string.punctuation for i in userPassword): message = 'Invalid Password..your password should contain at least a special character' return message else: return 'Valid Password!' my_password = passwordValidator() print(my_password)
true
9712243047b978613c48ea9cec001eff4e249291
whyadiwhy/Awesome_Python_Scripts
/BasicPythonScripts/More Chocolates Please!!!/more_chocolates_please.py
1,275
4.28125
4
#take user input here # The Amount of money you have ----- money = int(input('Enter amount of money you have : ')) # The Price of each chocolate ----- price = int(input('Enter price of each chocolate : ')) # Number of wrapper, in exchange of which you will get the chocolates ----- wrappers = int(input('Enter for how many wrappers, shopkeeper gives you chocolates : ')) #Number of chocolates you will get in exchange of wrappers ----- choco_wrapper = int(input('Enter how many chocolates , will shopkeeper gives you for given number of wrappers : ')) # The Algorithm chocolates = money//price # Number of chocolates you will get with your money and price of chocolates number_of_wrappers = money//price # Number of wrappers when you will buy chocolates # Calculation for Extra chocolates in exchange of wrappers ----- while number_of_wrappers//wrappers!=0: chocolates = chocolates + ((number_of_wrappers//wrappers)*choco_wrapper) number_of_wrappers = ((number_of_wrappers//wrappers)*choco_wrapper) + (number_of_wrappers%wrappers) # Finally you get Extra Chocolates : print('---------------------------------------------------------------------------------------------------------') print('Yay you got',chocolates,'Chocolates 🍫🍫 . Enjoy')
true
18caedc6696d1b151e421e854915671b8b00f15a
airforcebrett/CSE1310-Intro-To-Programming
/Lectures & Notes/9-10-14loops.py
626
4.125
4
#Repition / loop statements 9/10/14 """Keep getting user input until they enter 0""" #user=1 #while user != 0: #user = int ( input( "Enter a number (stop with 0) ") ) # user = user * 2 #infinite loop ############################################# ## below loop with counter that allows you to repeat inputs for 3 times #i=0 #while i < 3 : # user=int(input("Enter a number ")) # i = i +1 #print(user) #print("bye") ########################################### i=0 while (i<=10) : n=int(input("enter an integer: (i= "+str(i)+"):")) print(n) i= i+1 print("done with the while loop")
true
08f527a1f362494ddd60fd6c751f46ffce6e4bf6
zicameau/PyQt5Tutorial
/introduction/DateAndTime/xmas.py
445
4.21875
4
#! /usr/bin/python3 """ This example calculates the number of days passed from the last Xmas and the number of days until the next xmas. """ from PyQt5.QtCore import QDate xmas1 = QDate(2016, 12, 24) xmas2 = QDate(2017, 12, 24) now = QDate.currentDate() daysPassed = xmas1.daysTo(now) print("{0} days have passed since last Xmas".format(daysPassed)) nofdays = now.daysTo(xmas2) print("There are {0} days until next Xmas".format(nofdays))
true
60884d69b34466a5d286c97124174bc7c32c8892
ChJL/LeetCode
/easy/1002. Find Common Characters.py
755
4.125
4
# 1002 Find Common Character ''' Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer. ''' ''' Example 1: Input: ["bella","label","roller"] Output: ["e","l","l"] ''' class Solution: def commonChars(self, A: List[str]) -> List[str]: from collections import Counter res = Counter(A[0]) for i in range(1,len(A)): res = res & Counter(A[i]) return res.elements() # note that counter elements() return a itertool, yet this method still works.
true
683af70388d612c37c171c810ed120a71439e76f
ChJL/LeetCode
/easy/27. Remove Element.py
1,423
4.125
4
# Tag: Two Pointers ''' Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example 1: Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2] Explanation: Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted. Example 2: Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3] Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length. SOL: Use a pointer, go through all the elements in the list, remove the elements if it's matched by val. ''' class Solution: def removeElement(self, nums: List[int], val: int) -> int: #count = len(nums) i=0 while i < len(nums): if nums[i] == val: #count -=1 nums.pop(i) else: i+=1 return len(nums)
true
a765b5c8d4e6fe98e721cd91ee33edaacf198e21
hkim150/Leetcode-Problems
/Top_100_Liked_Questions/21._Merge_Two_Sorted_Lists/solution.py
924
4.125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # use a dummy node for the newHead curr = dummyNode = ListNode() # while both have next while l1 and l2: # append the smaller node to the combined list if l1.val < l2.val: curr.next = l1 l1 = l1.next else: curr.next = l2 l2 = l2.next curr = curr.next # append the list that has not reached the end to the combined list curr.next = l1 if l1 else l2 # get the real head and delete the dummy node newHead = dummyNode.next del dummyNode return newHead
true
739c53c1f62258226e3ef618b472c1d999d29dfa
deba-331/Basic-Python
/dice_simulation.py
321
4.1875
4
import random max_value=6 min_value=1 roll_dice="yes" while roll_dice=='yes' or roll_dice=='y': print("rolling the dice") print("the values are") print(random.randint(min_value,max_value)) print(random.randint(min_value,max_value)) roll_dice=input("Want to roll again?")
true
f26677341e9ee2e001a042044ba05dd08bb0cda8
akshay-verma/Cracking-the-Coding-Interview
/string_compression.py
1,027
4.3125
4
""" Page 91 - Cracking the Coding Interview 1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z). """ def compressString(string): prevIndex = 0 newStr = [] count = 1 index = 1 while index <= len(string): newStr.append(string[prevIndex]) if index < len(string) and string[index] == string[prevIndex]: count += 1 prevIndex += 1 index += 1 else: newStr.append(str(count)) count = 1 prevIndex = index index += 1 return "".join(newStr) if __name__ == "__main__": inputStr = "aaaaabbccddeeffgghh" compressedStr = compressString(inputStr) print(compressedStr)
true
b223347300b7063f9c576ce04327507f6fcff86c
Josalas16/HackerRank
/Python Problems/Arithmetic_Operators.py
633
4.3125
4
# Arithmetic Operators # Task # Read two integers from STDIN and print three lines where: # 1. The first line contains the sum of the two numbers. # 2. The second line contains the difference of the two numbers (first - second). # 3. The third line contains the product of the two numbers. # Input Format # The first line contains the first integer, a. The second line contains the second integer, b. # Output Format # Print the three lines as explained above # Sample # 3 + 2 -> 5 # 3 - 2 -> 1 # 3 * 2 -> 6 if __name__ == '__main__': a = int(input()) b = int(input()) print(a + b) print(a - b) print(a * b)
true
46346e7e4122c237ce1b2409fc45c9cc293686ff
Josalas16/HackerRank
/Python Problems/Mod_Divmod.py
921
4.40625
4
# Mod Divmod # Problem # One of the built-in function of Python is divmod, which takes two arguments a and b and returns a tuple containing # the quotient of a/b first and then the remainder a. # For Example # print divmod(177,10) # (17,7) # Here the integer division is 177/10 -> 17 and the modulo operator => 7. # Task # Read in two integers, a and b, and print three lines. # The first line is the integer division a // b # The second line is the result of the modulo operator: a%b. # The third line prints the divmod of a and b # Input Format # The first line contains the first integer, a, and the second line contains the second integer, b. # Output Format # Print the result as described above # Sample Input # 177 # 10 # Sample Output # 17 # 7 # (17, 7) # Enter your code here. Read input from STDIN. Print output to STDOUT a = int(input()) b = int(input()) print(a // b) print(a % b) print(divmod(a,b))
true
5673ba3394f1b4c5369da2ca1232a871abe7c6fe
OKirill/algo_and_structures_python
/Lesson_2/6.py
1,409
4.15625
4
""" 6. В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, то вывести загаданное число. """ import random def quizz(number, guesses_count): if guesses_count == 10: return print('У вас не осталось попыток') print(f'Ваша {guesses_count + 1} попытка из 10') guess = int(input('Попробуйте угадать число: ')) if guess == number: return print('Вы победили') if guess > number: print("---------------------------------") print('Введите меньшее число') print("---------------------------------") elif guess < number: print("---------------------------------") print('Введите большее число') print("---------------------------------") guesses_count += 1 return quizz(number, guesses_count) number = random.randint(0, 100) quizz(number, 0)
false
a976a5d980f02a8513c993d516754abfae626bd4
OKirill/algo_and_structures_python
/Lesson_7/1.py
1,081
4.28125
4
""" 1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Сортировка должна быть реализована в виде функции. По возможности доработайте алгоритм (сделайте его умнее). """ import random quantity = 20 nums = [random.randint(-100, 100) for i in range(quantity)] print(f'Исходный массив: {nums}') def bubble_sort(nums): n = 1 while n < len(nums): sorted = True for i in range(len(nums) - n): if nums[i] < nums[i + 1]: nums[i], nums[i + 1] = nums[i + 1], nums[i] sorted = False if sorted: break n += 1 print(f'Отсортированный по убыванию: {nums}') bubble_sort(nums)
false
89d54c28783161dc1ddda54b500ea3a8a587ae59
tiffanydenny/python_problems
/movie_system/app.py
2,532
4.1875
4
from user import User import json import os def menu(): # Ask for user's name name = input("Enter your name: ") # Check if a file exists for user filename = "{}.txt".format(name) # If it exists, welcome them and load their data if file_exists(filename): with open(filename, 'r') as f: json_data = json.load(f) user = User.from_json(json_data) # If not, create a User object else: user = User(name) #Give them options: user_input = input("What would you like to do? Type corresponding letter: \n a: Add a movie \n" " b: See list of movies \n c: See list of watched movies \n d: Delete a movie \n w: Set a movie as watched \n s: Save \n q: Quit \n") while user_input != 'q': # Add a movie if user_input == 'a': movie_name = input("Enter the movie name: ") movie_genre = input("Enter the movie genre: ") user.add_movie(movie_name, movie_genre) # See list of movies elif user_input == 'b': for movie in user.movies: print("Name: {}, Genre: {}, Watched: {}".format(movie.name, movie.genre, movie.watched)) # Set a movie as watched elif user_input == 'w': movie_name = input("Enter the movie name to set as watched: ") user.set_watched(movie_name) # Delete a movie by name elif user_input == 'd': movie_name = input("Enter the movie name to delete: ") user.delete_movie(movie_name) # See list of watched movies elif user_input == 'c': for movie in user.watched_movies(): print("Name: {}, Genre: {}, Watched: {}".format(movie.name, movie.genre, movie.watched)) # Save and quit elif user_input == 's': with open(filename, 'w') as f: json.dump(user.json(), f) user_input = input("What would you like to do? Type corresponding letter: \n a: Add a movie \n" " b: See list of movies \n c: See list of watched movies \n d: Delete a movie \n w: Set a movie as watched \n s: Save \n q: Quit \n") def file_exists(filename): return os.path.isfile(filename) menu() # Write to JSON file # with open('movie_file.txt', 'w') as f: # json.dump(user.json(), f) # Load from JSON file # with open('movie_file.txt', 'r') as f: # json_data = json.load(f) # user = User.from_json(json_data) # print(user.json())
true
3910922fe8acdd198e2d0bc15e3cf236de41f46b
Khun-blip/Practicals
/prac_04/list_exercises.py
310
4.15625
4
num1=int(input("Number:")) num2=int(input("Number:")) num3=int(input("Number:")) num4=int(input("Number:")) num5=int(input("Number:")) avg=(num1+num2+num3+num4+num5)/5 if num1: print("The first number is ", num1) if num5: print("The last number is", num5) print("The average of the number is", avg)
true
7e2d8c393e2b503df7b49997055ada4a17d426f6
Chris-Barty-JCU/CP1404_PRACTICALS
/prac_05/word_occurences.py
834
4.46875
4
# Create occurrences dictionary occurrences_dict = {} # Set longest word length to 0 longest_word = 0 # Ask for the string to count the occurrences in string = input("Enter a string to count the occurrence of words in: ") # Split the string in to a list of words - Then sort alphabetically string_wordlist = string.split() string_wordlist.sort() # Iterate through word list - Creating dictionary and finding longest word for word in string_wordlist: word_length = len(word) if word_length > longest_word: longest_word = word_length occurrences_dict[word] = string_wordlist.count(word) longest_word += 2 # Iterate through dictionary and print each pair with neat formatting for item in occurrences_dict: word = "{} :".format(item) print("{:{}} {}".format(word, longest_word, occurrences_dict[item]))
true
9af07325f6281f322364849b907041b95ea3fba6
findAkash/Python-Lab-Exercise_1st_Sem
/Lab_Exercise_1/Lab_Exercise_1_Solutions/lab1 Q4.py
864
4.375
4
# 4. Given the integer N - the number of minutes that is passed since midnight - how many # hours and minutes are displayed on the 24h digital clock? # The program should print two numbers: the number of hours (between 0 and 23) # and the number of minutes (between 0 and 59). N = int(input('Enter the time passes since midnight in minute : ')) # it ask the user for input # function is used def time(): passed_time_in_hour = N // 60 remaining_min = N % 60 i = 24 # value is initialized for 24 hr while passed_time_in_hour >= 24: # loop is used to convert the hour which are greater or equal to 24 passed_time_in_hour = passed_time_in_hour - 24 # it subtracts the hour until it satisfied the condition return str(passed_time_in_hour) + ' ' + str(remaining_min) # integer is converted in string and concatenated print(time())
true
512767e54d405c53ab4fb603a6e0a72b34f4ae1f
findAkash/Python-Lab-Exercise_1st_Sem
/Lab_Exercise_1/Lab_Exercise_1_Solutions/lab1 Q10.py
435
4.3125
4
#10. Write a Python program to convert seconds to day, hour, minutes and seconds. second=int(input('Second : ')) min=0 hour=0 day=0 # class CoversionTime: # def __init__(self): # self.second=int(input('Enter time in second : ')) while second>=60: min+=1 second=second-60 while min>=60: hour+=1 min=min-60 while hour>=24: day+=1 hour=hour-24 print(day,' day',hour,' hr',min,' min',second, ' sec')
true
0b1c20ae0fd1e5b90d85ae525278b60a3ab1c490
findAkash/Python-Lab-Exercise_1st_Sem
/Lab_Exercise_2/Lab_Exercise_2_Solutions/lab2 Q3.py
238
4.53125
5
#3. Check whether the user input number is even or odd and display it to user. #user input user_input=int(input('Enter the number : ')) #conditions if user_input%2==0: print(user_input,'is even') else: print(user_input,'is odd')
true
326cb29cb80476561c6780a93ab994f39c432cbc
helen256/lab2_galayko
/temp2.py
497
4.28125
4
"""Завдання 2 (Обчислити період обертання планети навколо Сонця)""" r1 = float(input("Введіть радіус першої планети ")) t1 = float(input("Введіть період обертання першої планети ")) r2 = float(input("Введіть радіус першої планети ")) t2 = ((t1**2 * r2**2)**0.5)/r1**3 print("Період обертання другої планети дорівнює ", t2)
false
1d8ef37fc612b50fefa498ad0d92b3c3c4a6b04d
4lpinist/PythonApplication1
/PythonApplication1/PythonApplication1.py
476
4.1875
4
# Vowel counter # Counts the number of vowels in word inputted by the user print("Enter a word:") user_input = input() def count_vowels(word): length = len(word) num_vowels = 0 #initialize vowel counter to zero for i in range(0,length,1): if ( word[i]=='a' or word[i] == 'e' or word[i] == 'i' or word[i] == 'o' or word[i] == 'u'): num_vowels = num_vowels + 1 return num_vowels answer = count_vowels(user_input) print(answer)
true
1e6c9277d52fa9de866a15b6756b1565c8013499
physics91si/johanping-lab11
/list_comp.py
1,198
4.125
4
import string alphabet = string.ascii_lowercase #Returns a list of the first 10 letters of the alphabet [letter for letter in alphabet[:10]] #Returns a list of the first 10 letters of the alphabet except the sixth one. [letter for letter in alphabet[:5]] + [letter for letter in alphabet[6:10]] #Returns a list of the first 10 letters of the alphabet except the sixth one, each repeated #each 1 , 2, and 3 times: first = [letter + "," + letter*2 + "," + letter*3 for letter in alphabet[:5]] last = [letter + "," + letter*2 + "," + letter*3 for letter in alphabet[6:10]] print(first+last) #Returns a list of the first 10 letters of the alphabet except the sixth one, each repeated #each 1 , 2, and 3 times in a grid: first = [[letter + "," + letter*2 + "," + letter*3] for letter in alphabet[:5]] last = [[letter + "," + letter*2 + "," + letter*3] for letter in alphabet[6:10]] print(first+last) #Returns a list like the above, but if the number matches the index of the character mod 3 (e.g. 'c' #and 3, instead print a single capitalized version of that character: [str[0].upper() if (sublist.index(str)== alphabet.index(str[0])%3) else str for sublist in list for str in sublist]
true
153a334241a2733da2a4394eceba518f2ecd0861
ddian20/comp110-21f-workspace
/lessons/quiz_2_practice.py
1,371
4.1875
4
"""Quiz 2 practice function writing.""" # Write a function called odd_and_even. Given a list of ints, odd_and_even should # return a new list containing the elements that are odd and have an even index. def odd_and_even(x: list[int]) -> list[int]: i: int = 0 second_list: list[int] = [] while i < len(x): even_index: int = i % 2 odd_number: int = x[i] % 2 if even_index == 0 and odd_number != 0: second_list.append(x[i]) i += 1 return second_list # Write a function named vowels_and_threes. Given a string, vowels_and_threes should return a new string # containing the characters that are either at an index that is a multiple of 3 or a vowel (one or the other, not both). # You can assume that the input string is all lowercase, for simplicity. def vowels_and_threes(x: list[str]) -> list[str]: i: int = 0 list2: list[str] = [] multiple_of_three: int = i % 3 vowels: list[str] = ["a", "e", "i", "o", "u"] while i < len(x): if x[i] == vowels and multiple_of_three: list2 += "" # if x[i] != vowels or multiple_of_three != 0: # list2 += "" if x[i] == vowels: list2.append.x[i] else: if multiple_of_three == 0: list2.append.x[i] i += 1 return list2
true
bee4390467a6a37c6e3b74d7501c41b6bf45a21f
mukeshdevmurari/bcapythonprogs
/ifcondition.py
239
4.125
4
a = input("Enter any number") a = int(a) if a<0: print("Entered value is negative") elif a == 0: print("Entered value is zero") elif 0 < a <= 100: print("Entered value is between 1 to 100") else: print("Value is above 100")
true
430ccfeb354aeb8f145a6b925910015f97215ee6
miaomiaorepo/Homework-lede
/03/intro.py
677
4.25
4
print ("Hello world!") print ('hello world!') print (10) print (10 + 10) print ('hello' + 'world!') print ('hello ' + 'world!') # >>> str(10) # '10' print ('hello' + str(10)) print ('hello'+'10') print('hello, Soma') print('hello, ' + 'Soma') name = input("what's your name?") print('hello, ' + name) year_of_birth = input("what year were you born?") age = 2016 - int(year_of_birth) print("you are roughly " + str(age) + " years old") #or print("you are roughly", age, "years old") if age >= 30 or age > 100: print("cool") elif age >= 21: print("here is your beer") elif age < 0: print("you are an idiot") else: print("nope, sorry") print("goodbye")
false
c0765bcd1e1fa6d0768e31ff208739388ebe790d
Chittesh/pythonDataStructuresAndException
/list_sorting.py
1,194
4.3125
4
numbers = [0,1,2,3,4,5,6,7,8,9,10] # To revese - the original numbers gets reversed numbers.reverse() print(numbers) #[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] numbers = [0,1,2,3,4,5,6,7,8,9,10] #Iterator - withouot revesrion the numbers but if we want to print the revese order reversednumbers = reversed(numbers) for i in reversednumbers: print(i,end='') #10,9,8,7,6,5,4,3,2,1,0, numbers.reverse() numbers.sort() print(numbers) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers.reverse() print(numbers) #[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] #To get the sotred number but don't modify the numbers for i in sorted(numbers): print(i) ##[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #key filter sorting based on lenght of string numbers = ['zero','one','two','three','four','five','six','seven','eight','nine','ten'] for i in sorted(numbers,key=len): print(i,end=',') #one,two,six,ten,zero,four,five,nine,three,seven,eight, print() #reverse for i in sorted(numbers,key=len,reverse=True): print(i,end=',') #three,seven,eight,zero,four,five,nine,one,two,six,ten
true
1d3b379c7ae7df495de8e786441707a5dd3cd8a4
gwaxG/pypatterns
/structural/flyweight/flyweight.py
1,173
4.25
4
#!/usr/bin/env python3 # coding: utf-8 ''' Flyweight allows for objects to use sharing memory in order to decreace memory consumption. ''' class Tea: pass class BlackTea(Tea): pass class GreenTea(Tea): pass class TeaMaker: def __init__(self): self.tea = {} self.possible_teas = {'green': GreenTea, 'black': BlackTea} def make(self, pref): if pref not in self.tea.keys(): self.tea[pref] = self.possible_teas[pref]() return id(self.tea[pref]) class TeaShop: def __init__(self, tea_maker): self.orders = {} self.tea_maker = tea_maker def take_order(self, pref: str, table: int) -> None: self.orders[table] = self.tea_maker.make(pref) return self.orders[table] if __name__ == '__main__': tea_maker = TeaMaker() shop = TeaShop(tea_maker) print('Tea from the container {} '.format(shop.take_order('green', 1))) print('Tea from the container {} '.format(shop.take_order('green', 2))) print('Tea from the container {} '.format(shop.take_order('black', 3))) print('Tea from the container {} '.format(shop.take_order('black', 4)))
true
8f50fdbefaa53bead068a7d1d6608a2f57628423
bkalcho/python-crash-course
/icecreamstand.py
2,215
4.4375
4
# Author: Bojan G. Kalicanin # Date: 03-Oct-2016 # Model Ice Cream stand a specific kind of the restaurant # Author: Bojan G. Kalicanin # Date: 02-Oct-2016 # Creating class to model a Restaurant, and instantiation of the class # Calling methods and attributes of the object (class instance) class Restaurant(): """Trying to model real world restaurant.""" def __init__(self, restaurant_name, cousine_type): """Initialize restaurant_name and causine_type attributes.""" self.restaurant_name = restaurant_name self.cousine_type = cousine_type self.number_served = 0 def describe_restaurant(self): """Method that describes restaurant.""" print("The " + self.restaurant_name.title() + " offers " + self.cousine_type + " cousine to the guests.") def open_restaurant(self): """Method thad models opening of the restaurant.""" print("The " + self.restaurant_name.title() + " is open.") def set_number_served(self, number_served): """Method that sets number of customers you have served.""" self.number_served = number_served def increment_number_served(self, number_served): """Increment the number of served customers.""" self.number_served += number_served class IceCreamStand(Restaurant): """ IceCreamStand restaurant class, which models real-world Ice Cream Stand restaurant. """ def __init__( self, restaurant_name, cousine_type='ice creams'): """ Initialize parent class attributes and add IceCreamStand specific attributes. """ super().__init__(restaurant_name, cousine_type) self.flavors = [ 'strawberry', 'vanila', 'malaga', 'chocolate', 'blackberry', 'annanas', ] def display_flavors(self): """Method that displays list of flavors.""" print("The restaurant " + self.restaurant_name.title() + " can offer next ice cream flavors:") for flavor in self.flavors: print("- " + flavor) ice_car = IceCreamStand('dolly') ice_car.display_flavors()
true
717ef08780c19b7cb32a3b6dce9695f3fccd3f8e
bkalcho/python-crash-course
/common_words.py
634
4.1875
4
# Author: Bojan G. Kalicanin # Date: 07-Oct-2016 # Program that analyses files from input def count_word(filename, word): try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: # Choose to fail silently if information about exception # is not important for the user pass else: n_times = contents.lower().count(word) print("\nThe word '" + word + "' appears " + str(n_times) + " in the file '" + filename + "'!") w_name = 'the' filenames = ['alice.txt', 'little_women.txt'] for f_name in filenames: count_word(f_name, w_name)
true
badbfd67ba1e4e7bcac19c763f6835a5af8213de
bkalcho/python-crash-course
/restaurant.py
1,734
4.34375
4
# Author: Bojan G. Kalicanin # Date: 02-Oct-2016 # Creating class to model a Restaurant, and instantiation of the class # Calling methods and attributes of the object (class instance) class Restaurant(): """Trying to model real world restaurant.""" def __init__(self, restaurant_name, cousine_type): """Initialize restaurant_name and causine_type attributes.""" self.restaurant_name = restaurant_name self.cousine_type = cousine_type self.number_served = 0 def describe_restaurant(self): """Method that describes restaurant.""" print("The " + self.restaurant_name.title() + " offers " + self.cousine_type + " cousine to the guests.") def open_restaurant(self): """Method thad models opening of the restaurant.""" print("The " + self.restaurant_name.title() + " is open.") def set_number_served(self, number_served): """Method that sets number of customers you have served.""" self.number_served = number_served def increment_number_served(self, number_served): """Increment the number of served customers.""" self.number_served += number_served restaurant = Restaurant('hazienda','mexican') favorite_restaurant = Restaurant('casa nova', 'french') ethno_restaurant = Restaurant('zavicaj', 'serbian ethnic causine') restaurant.restaurant_name restaurant.cousine_type restaurant.describe_restaurant() restaurant.open_restaurant() restaurant.number_served = 150 restaurant.set_number_served(35) restaurant.increment_number_served(35) print("Number of served customers: " + str(restaurant.number_served)) favorite_restaurant.describe_restaurant() ethno_restaurant.describe_restaurant()
true
a4cbe042be40cb9d79544928d148eab8540c3b19
bkalcho/python-crash-course
/guest.py
339
4.21875
4
# Author: Bojan G. Kalicanin # Date: 06-Oct-2016 # Prompt the user for name, and write the name in a file guest.txt filename = 'guest.txt' with open(filename, 'w') as file_object: first_name = input("What is your first name? ") last_name = input("What is your last name? ") file_object.write(first_name.title() + " " + last_name.title())
true
e23d1431d5bbdcdee8e0cb47aee6473a1796ac18
fabri0176/pythonTest
/Ejercicios_20200124/1_Tipos_de_datos_simples/Ejercicio_9.py
696
4.1875
4
# http://aprendeconalf.es/python/ejercicios/tipos-datos.html # Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el número de años, y # muestre por pantalla el capital obtenido en la inversión. dineroInversion = input("Dinero a invertir:\t") dineroInversion = float(dineroInversion) interesAnual = input("Interes anual:\t") interesAnual = float(interesAnual) numAnyos = input("Número de años:\t") numAnyos = float(numAnyos) capitalObtenido = round(dineroInversion*(interesAnual/100+1)**numAnyos,2) print("De la inversion en ${} a interes {} en {} años, el capital obtenido es de {}".format(dineroInversion,interesAnual,numAnyos,capitalObtenido))
false
550e24b26f84718fd9041522f9182ca0a6a28b67
fabri0176/pythonTest
/Estructuras de Flujo/Ejercicio_1.py
558
4.15625
4
num_1 = float(input("Ingrese un número: ")) num_2 = float(input("Introduce otro número: ")) print("Seleccione la opción a mostrar") print("1 - Suma de dos números: ") print("2 - Resta de dos números") print("3 - Multiplicación de los números") opcion = int(input("Introduce una opción: ")) if opcion==1: print("la suma de num_1 + num_2 = ",num_1+num_2) elif opcion==2: print("la resta de num_1 - num_2 = ",num_1-num_2) elif opcion==3: print("La multiplicación de num_1 x num_2 = ",num_1*num_2) else: print("Opción no válida")
false
ececf9c0479ce6044ff6ccaec0bb40efd9a3caf6
dylanawhite92/Python-Automation
/Python Basics/Flow Control/swordfish.py
506
4.1875
4
# Infinite loop while True: # Prompt user input print('Who are you?') name = input() # Flow control statement to evaluate user input # Continue loop and prompt again, otherwise evaluate next step if name!= 'Joe': continue # Next step in loop, prompt user input for password # Then, break out of loop print('Hello, Joe. What is the password? (Hint: It is a fish.)') password = input() if password == 'swordfish': break print('Access granted.')
true
c885643bf01123963546d8fcefee29d2358ffdf9
WyattAlexander-001/RandomPassWordGenerator
/RandomPasswordGenerator.py
1,100
4.15625
4
""" Random Password Generator """ import random letters =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o','p','q', 'r', 's','t','u', 'v', 'w', 'x', 'y','z' 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '$', '#','&'] print('Welcome To The Password Generator') desired_letters = int(input('How many letters would you like?')) desired_numbers = int(input('How many numbers would you like?')) desired_symbols = int(input('How many symbols would you like?')) #PASSWORD STARTS AS EMPTY LIST password= [] for char in range(0, desired_letters ): password += random.choice(letters) for char in range(0, desired_numbers ): password += random.choice(numbers) for char in range(0, desired_symbols): password += random.choice(symbols) random.shuffle(password) passwordFinal = "" for char in password: passwordFinal += char print(f'Your desired password is: \n{passwordFinal}')
true
20119169efd9665d65a2e5e0521b96845419b3d1
al43hi58/breaking-the-code-al43hi58-master
/LetterToNumber.py
1,266
4.34375
4
############################################### # LetterToNumber.py # Vandenburg 2015 / De Borde 2017 ############################################## # INSTRUCTIONS ############################################################## # Your task is to write a program in Python that: # 1) Asks the user to type in a letter # 2) Finds the position of that letter in the alphabet # 3) Display that letter back to the user ############################################################## # Create a variable with all the letters in the alphabet alphabetbig = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" alphabetsmall = "abcdefghijklmnopqrstuvwxyz" # Ask the user to type in a letter letter = input("Please type a letter: ") # Find the position of the letter in the alphabet posbig = alphabetbig.find(letter) possmall = alphabetsmall.find(letter) # As the first position is 0, we need to add 1 posbig += 1 possmall += 1 if posbig == 1 and possmall == 1: posbig = "You " possmall = "didn't type anything, please type any letter" if not letter.isalpha(): posbig = "Please " possmall = "type a LETTER not anything else. " elif len(letter) > 1: posbig = "Please " possmall = "type ONE letter not any more. " #display the number back to the user print(posbig + possmall)
true
bdc659a352655cb76e95ee34614d5db3e9cc8850
Takashiidobe/learnPythonTheHardWayZedShaw
/ex33forLoop.py
308
4.125
4
def for_loop: numbers = [] for i in range(0, 6): print(f"At the top is {i}") numbers.append(i) print(f"At the bottom is {i}") print("Numbers now", numbers) print(f"at the bottom is {i}") print("The numbers") for num in numbers: print(numbers)
true
f84d0beaf50149eab4ad09b9103ca410228f0d19
Takashiidobe/learnPythonTheHardWayZedShaw
/ex20.py
1,186
4.375
4
#the imports to use argv from sys import argv #sets the amount of argvs (script + the file to change) script, input_file = argv #defines the function print_all as reading the file def print_all(f): print(f.read()) #defines rewinding the file as going back to the first line def rewind(f): f.seek(0) #defines printing a line as the line_count and readline def print_a_line(line_count, f): print(line_count, f.readline()) #sets current file to be the file we've opened now current_file = open(input_file) print("First let's print the whole file: \n") #print the whole file itself print_all(current_file) print("Now let's rewind, kind of like a tape.") #sets the file back to the beginning. rewind(current_file) print("Let's print three lines:") #sets the current line to be printed to the first line current_line = 1 #prints the first line of the file print_a_line(current_line, current_file) #sets the current line to one more than it was previously then it prints it current_line += 1 print_a_line(current_line, current_file) #sets the current line to one more than it was previously then it prints it current_line += 1 print_a_line(current_line, current_file)
true
fccc4be3d44d0be1e7a2dd05afde0841cabd99b3
akshatz/Backup
/Assignment/Assignment/question_2.py
911
4.46875
4
# Question 2: # Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. # Note: i=0,1.., X-1; j=0,1,¡­Y-1. # Example # Suppose the following inputs are given to the program: # 3,5 # Then, the output of the program should be: # [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] # Hints: # Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. """ No of both row elements and column elements to be taken as input """ row_num = int(input("Input number of rows: ")) col_num = int(input("Input number of columns: ")) multi_list = [[0 for col in range(col_num)] for row in range(row_num)] for row in range(row_num): for col in range(col_num): multi_list[row][col]= row*col print("List generated: ",multi_list)
true
b9ffe1ed1898b329ae9e4e364a6500bc34350e1c
Sicelo-Mduna-byte/PRE-BOOTCAMP-CODING-CHALLENGES
/Task 10.py
375
4.1875
4
def vowel_finder(string_entered_by_user): string = [] string.extend(string_entered_by_user) vowels = "aAeEiIoOuU" vowel_list = [] for i in string: if(i in vowels): vowel_list.append(i) vowels = (", " .join(vowel_list)) print("The following vowels are contained in the string: %s" % (vowels)) vowel_finder("Hello Egg")
false
32df1d0bb908f2fb1a502eb8fc7bb03d8995364b
raymondmar61/pythoncodecademy
/takingavacation.py
1,236
4.28125
4
def bigger(first, second): print(max(first, second)) return bigger bigger(10, 50) def hotel_cost(nights): return 140 * nights nightsstay = 3 print(hotel_cost(nightsstay)) def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 else: print(city+ " is not on the list.") return plane_ride_cost("San Jose") print(plane_ride_cost("Charlotte")) def rental_car_cost(days): if days >= 7: cost = (days * 40) - 50 return cost elif days >= 3: cost = (days * 40) - 20 return cost else: cost = (days * 40) return cost print(rental_car_cost(4)) city = "Los Angeles" days = 10 print(hotel_cost(days-1) + rental_car_cost(days) + plane_ride_cost(city)) #I can also create a function. Same total trip cost answer. I added spendingmoney to the function for a higher cost. #Notice the three functions returns the answer using "return" keyword. I call the three functions with print() def totaltripcost(city, days, spendingmoney): print(hotel_cost(days-1) + rental_car_cost(days) + plane_ride_cost(city) + spendingmoney) return spendingmoney = 1000 totaltripcost(city, days, spendingmoney)
true
bc70f99b24d875508c0b5980f61c5e28a6ea8c71
trifiasco/CPPS
/Python/CookBook/STLs/priority_queue.py
675
4.15625
4
from heapq import heappop, heappush ''' Info - Heaps are binary trees for which every parent node has a value less than or equal to any of its children - heap[0] is the smallest item, and heap.sort() maintains the heap invariant! (**MIN_HEAP by default**) - heapq.heappush(heap, item) - heapq.heappop(heap) - heapq.heappushpop(heap, item) - push item in heap, and then return the smallest item from the heap. - heapq.heapify(x) - transform a list(x) into heap ''' if __name__ == "__main__": # basic example h = [] for value in [1, 2, 3, 4, 5, 6]: heappush(h, value) heapsorted = [heappop(h) for i in range(len(h))] print(heapsorted) pass
true
7a627699e3804118d443906b886f42bb8a5ea2da
alpharishi/python
/Inputs.py
399
4.125
4
age = int(input("How old are you")) if age >= 65: print("you're quite old. make sure to take care of your health and execrise regularly.old is gold!") elif age <= 30: print(" youre very young.... keep active, stay connected, and enjoy the best moments of you life!") else: print(" youre middle aged, you might be getting older and have more struggles, but still remember to have fun")
true
0ddc24f9e48053b6e2192f268ac5822992d195f4
xingfengwxx/PythonLearnDemo
/Day07/list2.py
899
4.1875
4
#!/usr/bin/env python 3.7 # -*- coding: utf-8 -*- # @Time : 2019/7/5 16:55 # @Author : wangxingxing # @Email : xingfengwxx@gmail.com # @File : list2.py # @Software : PyCharm # @Description: """ 列表常用操作 - 列表连接 - 获取长度 - 遍历列表 - 列表切片 - 列表排序 - 列表反转 - 查找元素 """ def main(): fruits = ['grape', 'apple', 'strawberry', 'waxberry'] fruits += ['pitaya', 'pear', 'mango'] # 循环遍历列表元素 for fruit in fruits: print(fruit.title(), end=' ') print() # 列表切片 fruits2 = fruits[1:4] print(fruits2) # fruit3 = fruits # 没有复制列表只创建了新的引用 fruits3 = fruits[:] print(fruits3) fruits4 = fruits[-3:-1] print(fruits4) fruits5 = fruits[::-1] print(fruits5) if __name__ == '__main__': main()
false
dfee3205d667113f749340aced4bcb7a124c4c3e
xingfengwxx/PythonLearnDemo
/Day07/list1.py
896
4.1875
4
#!/usr/bin/env python 3.7 # -*- coding: utf-8 -*- # @Time : 2019/7/4 17:03 # @Author : wangxingxing # @Email : xingfengwxx@gmail.com # @File : list1.py # @Software : PyCharm # @Description: """ 定义和使用列表 - 用下标访问元素 - 添加元素 - 删除元素 """ def main(): fruits = ['grape', 'apple', 'strawberry', 'waxberry'] print(fruits) # 通过下标访问元素 print(fruits[0]) print(fruits[1]) print(fruits[-1]) print(fruits[-2]) # print(fruits[-5]) # IndexError # print(fruits[4]) # IndexError fruits[1] = 'apple' print(fruits) # 添加元素 fruits.append('pitaya') fruits.insert(0, 'banana') print(fruits) # 删除元素 del fruits[1] fruits.pop() fruits.pop(0) fruits.remove('apple') print(fruits) if __name__ == '__main__': main()
false
61e5d1ce6eb020daa8bd7c314b75f741c2740fda
code-afrique/bootcamps
/2019/quadratic_solver/quadratic_solver.py
1,593
4.21875
4
"""A program to solve quadratic equations""" from modules import math, print_step_by_step, graph def check_roots(a,b,c): """ This function checks the roots of a quadratic equation of the form ax^2 + bx + c = 0 Task: 1. First find the discriminant of the equation by using: discriminant = b*b - 4*a*c 2. If the discriminant is > 0 return the phrase 'real roots' Else if the discriminant is = 0 return phrase 'equal roots' Else if the discriminant is < 0 returnthe phrase 'complex roots' 3. Return the discriminant Hint: Use if-statements """ #step 1 //TODO discriminant = 0 #replace 0 with your own code #step 2: //TODO #step 3 //TODO #return discriminant def solve(a,b,c): """ This method solves a quadratic equation using the quadratic formula. A quadratic equation is one of the form: ax^2 + bx + c = 0 Requirements: a: integer b: integer c: integer Hint: Use the quadratic formula. You may also learn from how we found the discriminant above Tasks: 1: Find the discriminant 2. Compute the two roots, x1 and x2 by using the quadratic formula. For eg. x1 = (-b + math.sqrt(discriminant)/(2*a) 3. Print the step by step solution. Hint: Use the function called print_step_by_step 4. Draw the graph of the equation Hint: use the function called graph 5. return the value (x1,x2) as your answer """ #step 1 //TODO discriminant = 0 #replace 0 with your own code #step 2 //TODO x1 = 0 #replace 0 with your own code x2 = 0 #replace 0 with your own code #step 3 //TODO #step 4 //TODO #step 5 return (x1,x2)
true
045a0f57098887c3982920c35e73250518a044da
jemalicisou/MaratonaDataScience-
/EstruturasDecisão3.py
798
4.34375
4
# Terceira parte da lista de exercícios de Estrutura de Decisão #2-Faça um Programa que peça um número inteiro e determine se ele é par ou impar. Dica: utilize o operador módulo #(resto da divisão). print('') print('Determina se o número é par ou impar') numero = int(input('Insira aqui um número inteiro:')) if(numero % 2 == 0): print("O número é par!") else: print("Número é ímpar!") #3-Faça um Programa que peça um número e informe se o número é inteiro ou decimal. Dica: utilize uma função de #arredondamento. print('') print('Determina se um número é inteiro ou decimal') n1 = float(input('Digite um número :')) if(n1 % 100 == 0): print("O número é inteiro.") else: print("O número é decimal")
false
367f5f82352496a57598ad38dd07063e538eb220
jemalicisou/MaratonaDataScience-
/EstruturasDecisão2.py
2,693
4.25
4
# Segunda parte da Lista de Exercícios de Estrutura em Decisão de Python # 6 -Faça um Programa que leia três números e mostre o maior deles. print ('') print ('Imprime maior de três números') n1 = int (input ('Digite o primeiro número:') ) n2 = int (input ('Digite o segundo número:') ) n3 = int (input ('Digite o terceiro número:') ) if n1 > n2 and n1 > n3: print (n1) elif n2 > n1 and n2 > n3: print (n2) elif n3 > n1 and n3 > n2: print (n3) # 7 -Faça um Programa que leia três números e mostre o maior e o menor deles. print ('') print (' Imprime maior e o menor de três números') nu1 = int (input ('Digite o primeiro número:')) nu2 = int (input ('Digite o segundo número:')) nu3 = int (input ('Digite o terceiro número:')) maior = nu1 menor = nu1 if maior < nu2: maior = nu2 if maior < nu3: maior = nu3 if menor > nu2: menor = nu2 if menor > nu3: menor = nu3 print ('Maior: %d ' % maior) print ('Menor: %d ' % menor) # 8- Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, # sabendo que a decisão é sempre pelo mais barato. print ('') print (' Produto que você deve comprar!') p1 = int (input ('Digite o preço do primeiro produto:')) p2 = int (input ('Digite o preço do segundo produto:')) p3 = int (input ('Digite o preço do terceiro produto:')) if p1 < p2 and p1 < p3: print ('Você deve comprar o primeiro produto no valor de :%d' % p1) if p2 < p1 and p2 < p3: print ('Você deve comprar o segundo produto no valor de :%d' % p2) if p3 < p1 and p3 < p2: print ('Você deve comprar o terceiro produto no valor de :%d' % p3) # 9 -Faça um Programa que leia três números e mostre-os em ordem decrescente. print ('') print (' Ordenando números!') num1 = int (input ('Digite o primeiro numero:')) num2 = int (input ('Digite o segundo numero:')) num3 = int (input ('Digite o terceiro numero:')) lista_num = [num1, num2, num3] lista_num_sorted = sorted (lista_num) print('O numeros digitados foram:', lista_num) print ('A lista de numeros ordenadas é:',lista_num_sorted) # 10-Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-matutino ou V-Vespertino ou N- Noturno. # Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" ou "Valor Inválido!", conforme o caso. print('') print('Verifica o turno do estudante.') turno = str(input( 'Digite (M) Matutino, (V) Verspertino, (N) Noturno ').upper()) if turno == 'M': print('Bom dia!') elif turno == 'V': print('Boa Tarde!') elif turno == "N": print('Boa Noite!')
false
e9d7dd554d37d9f718cc15b2541dc4b527b700b1
gabrielsillva/Conversor-de-Texto
/Conversor de Texto/conversor.py
378
4.125
4
es = int(input('''Escolha o que deseja fazer com sua frase: (1) colocar frase em maiúsculo (2) colocar frase em minúsculo (3) colocar a primeira letra em maiúsculo\n ''')) text = str(input('Digite seu texto:')) if es == 1: a = text.upper() print(a) elif es == 2: b = text.lower() print(b) elif es == 3: c = text.capitalize() print(c)
false
7ad4ef0a75ed22d4824d1ba63908cbae949d6be0
kisorniru/pong-game-v2
/pong-v2.py
2,234
4.3125
4
# Simple Pong game in Python 3 for beginners # By @kisorniru # Part 1: Getting Started import turtle import os wn = turtle.Screen() wn.title("Pong v2 by @kisorniru") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) # Score score = 0 # Paddle Info paddle = turtle.Turtle() paddle.speed(0) paddle.shape("square") paddle.color("white") paddle.shapesize(stretch_wid=1, stretch_len=10) paddle.penup() paddle.goto(0, -250) # Ball Info ball = turtle.Turtle() ball.speed(0) ball.shape("circle") ball.color("white") ball.penup() ball.goto(0, 0) ball.dx = .2 ball.dy = -.2 # Pen pen = turtle.Turtle() pen.speed(0) pen.color("red") pen.penup() pen.goto(0, 250) pen.hideturtle() pen.write("Player : 0", align="center", font=("Courier", 24, "normal")) # Function def paddle_right(): x = paddle.xcor() x += 20 paddle.setx(x) def paddle_left(): x = paddle.xcor() x -= 20 paddle.setx(x) # Keyboard listen wn.listen() wn.onkeypress(paddle_right, "Right") wn.onkeypress(paddle_left, "Left") # Main game loop while True: wn.update() # Ball Movement ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # Paddle boundary checking if paddle.xcor() > 290: x = -290 paddle.setx(x) if paddle.xcor() < -290: x = 290 paddle.setx(x) # Ball boundary checking if ball.ycor() > 290: ball.sety(290) ball.dy *= -1 if ball.ycor() < -290: # ball.sety(-290) ball.goto(0, 0) ball.dy *= -1 os.system("aplay sound/finish.wav&") pen.clear() pen.color("red") pen.write("Player : 0", align="center", font=("Courier", 24, "normal")) if ball.xcor() > 390: ball.setx(390) ball.dx *= -1 if ball.xcor() < -390: ball.setx(-390) ball.dx *= -1 # Paddle and Ball Collisions if (-240 > ball.ycor() > -250) and (paddle.xcor() + 100 > ball.xcor() > paddle.xcor() - 100): ball.sety(-240) ball.dy *= -1 os.system("aplay sound/bounce.wav&") score += 1 pen.clear() pen.color("white") pen.write("Player : {}".format(score), align="center", font=("Courier", 24, "normal"))
false
651cb76bbb768f57b79104298adb5c35b3c44fa3
GDG-Buea/learn-python
/chpt7/Quadratic_equations.py
2,040
4.25
4
# This program is based on Quadratic equations # It prompts the user to enter values for a, b, and c and displays the result # based on the discriminant. # If the discriminant is positive, it displays the two roots. # If the discriminant is 0 , it displays one root. # Otherwise, it displays the message - The equation has no roots import math class QuadraticEquation: def __init__(self, a, b, c): self.__var1 = a self.__var2 = b self.__var3 = c def get_a(self): return self.__var1 def get_b(self): return self.__var2 def get_c(self): return self.__var3 def set_a(self, value_a): self.__var1 = value_a def set_b(self, value_b): self.__var2 = value_b def set_c(self, value_c): self.__var3 = value_c def calculate_discriminant(self): return (self.__var2 ** 2) - (4 * self.__var1 * self.__var3) def get_root1(self): return ((-self.__var2) + math.sqrt(self.calculate_discriminant())) / 2 * self.get_a() def get_root2(self): return ((-self.__var2) - math.sqrt(self.calculate_discriminant())) / 2 * self.get_a() def get_roots(self): if self.calculate_discriminant() > 0: print("The roots of this equation are: ", format(self.get_root1(), ".2f"), "and", format(self.get_root2(), ".2f")) elif self.calculate_discriminant() == 0: if self.get_root1() != 0: print("The root of this equation is: ", format(self.get_root1(), ".2f")) else: print("The root of this equation is: ", format(self.get_root2(), ".2f")) else: print("This equation has no real roots") def main(): value_of_a, value_of_b, value_of_c = eval(input("Enter the values for a, b and c of the quadratic equation " "e.g. 3, 4, 5: ")) user1 = QuadraticEquation(value_of_a, value_of_b, value_of_c) user1.get_roots() main()
true
9d6473c2a16c24b0f9c44e73f303863297e7eed8
GDG-Buea/learn-python
/chpt9/Rectanguloid.py
1,038
4.125
4
# This a program displays a rectanguloid, from tkinter import * # Import tkinter class Rectanguloid: def __init__(self): window = Tk() # Create a window window.title("Rectanguloid") # Set title width = 200 height = 150 canvas = Canvas(window, bg="white", width=width, height=height) canvas.pack() width = width * 0.9 - 30 height = height * 0.9 - 60 diff = min(width, height) * 0.4 # Draw the front rect canvas.create_rectangle(10, 60, 10 + width, 60 + height) # Draw the back rect canvas.create_rectangle(30, 60 - diff, 30 + width, 60 - diff + height) # Connect the corners canvas.create_line(10, 60, 30, 60 - diff) canvas.create_line(10, 60 + height, 30, 60 - diff + height) canvas.create_line(10 + width, 60, 30 + width, 60 - diff) canvas.create_line(10 + width, 60 + height, 30 + width, 60 - diff + height) window.mainloop() # Create an event loop Rectanguloid()
true
370047886fe77dc971975ba2ba94ae4350e49a2e
GDG-Buea/learn-python
/chpt3/Great_circle_distance.py
1,160
4.4375
4
# The great circle distance is the distance between # two points on the surface of a sphere. Let (x1, y1) and (x2, y2) be the geographical # latitude and longitude of two points. The great circle distance between the two # points can be computed using the following formula: # d = radius * arccos(sin(x 1 ) * sin(x 2 ) + cos(x 1 ) * cos(x 2 ) * cos(y 1 - y 2 )) # ___________________________________________________________________________________________________________ # This program prompts the user to enter the latitude and longitude of two points on the earth in degrees # and displays its great circle distance. import math , cmath x1, y1 = eval(input("Enter point 1 (latitude and longitude) in degrees: ")) x2, y2 = eval(input("Enter point 2 (latitude and longitude) in degrees: ")) x1 = math.radians(x1) x2 = math.radians(x2) y1 = math.radians(y1) y2 = math.radians(y2) averageRadiusOfEarth = 6371.01 A = math.sin(x1) * math.sin(x2) B = math.cos(x1) * math.cos(x2) C = math.cos(y1 - y2) greatCircleDistance = averageRadiusOfEarth * math.acos(A + B * C) # 41.5,87.37 print("The distance between the two points is: ", greatCircleDistance, "Km")
true
ed05761e49cca3587233af74bf27ca3c925dcdc3
GDG-Buea/learn-python
/chpt4/Two_points_in_a_rectangle.py
934
4.21875
4
# This program prompts the user to enter a point (x, y) and checks whether the point is within the rectangle # centered at ( 0 ,0 ) with width 100 and height 50 . It displays the point, the rectangle, and a message # indicating whether the point is inside the rectangle in the window, a import turtle x1, y1 = eval(input("Enter a point x,y: ")) width = 100 height = 50 turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.begin_fill() turtle.color("red") turtle.circle(3) turtle.end_fill() turtle.penup() turtle.goto(0, 0) turtle.pendown() turtle.forward(width) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.forward(width) turtle.right(90) turtle.forward(height) turtle.penup() turtle.goto(200, -150) turtle.pendown() d = ((0 - x1) * (0 - x1) + (0 - y1) * (0 - y1)) ** 0.5 if d < width or height: print("The dot is inside the circle") else: print("The dot is out of the circle") turtle.done()
true
fb165c0af6bd4fe85f15c9b33e9e324b9618643a
GDG-Buea/learn-python
/chpt2/Celsius_to_fahrenheit.py
250
4.4375
4
# This program reads a Celsius degree from the user, converts it to Fahrenheit and displays the result. celsius = eval(input("Enter a degree in celsius e.g 100: ")) fahrenheit = (9/5) * celsius + 32 print("Celsius is ", fahrenheit, "Fahrenheit")
true