blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
8444720849db0c2171c094f46c8593e96f4f3542
EugenKuzin/math-for-fedor-r
/teo/addition.py
801
4.125
4
#!/usr/bin/env python3 def successor(x: int) -> int: '''Return the next integer.''' return x + 1 def predecessor(x: int) -> int: '''Return the previous integer.''' return x - 1 def sum(a, b: int) -> int: '''Return the sum of given non-negative integers using recursion.''' return a if b == 0 else successor(sum(a, predecessor(b))) def main(): try: a = int(input('\t\t> ')) b = int(input('\t\t> ')) except: print('\n\t' + 'Enter integers!' + '\n') return main() if a < 0 or b < 0: print('\n\t' + 'Enter non-negative integers!' + '\n') return main() print('\n\t' + 'RESULT: ', sum(a, b), '\n') if __name__ == '__main__': print('\n\t' + 'Enter two non-negative integers you want to sum:' + '\n') main()
false
d43109a47056775be354e96ff28de941555ba6a5
sghwan28/PythonSelf-Learning
/Data Structure/Linked List/Q_Reversal.py
912
4.15625
4
from linked_list import Node ''' Question: Define a function to reverse a linked list The function will take in the head of the list as input and return the new head of the list ''' def reverse(head:Node): current = head previous = None next = None while current: # assign the next according to the original linked list next = current.next_node # Reverse the pointer current.next_node = previous # move to the next # update all parameters previous = current current = next return previous # Create a list of 4 nodes a = Node(1) b = Node(2) c = Node(3) d = Node(4) # Set up order a,b,c,d with values 1,2,3,4 a.next_node = b b.next_node = c c.next_node = d reverse(a) # Should have no AssertionError assert b.next_node.value == 1 assert c.next_node.value == 2 assert d.next_node.value == 3 assert a.next_node == None
true
af0f883c0b23d83f653309ebc7285c26ab5a198b
Andre-Williams22/SPD-1.4
/technical_interview_problems/most_frequent.py
828
4.25
4
# Most Frequently Occuring Item in Array #Example: list1 = [1, 3, 1, 2, 3, 1] # Output: => 1 def most_frequent(given_list): hashtable = {} # O(n) Space Complexity max_num = 0 # O(1) space => tracks the most occuring number max_count = 0 # O(1) space => tracks num of times number appears for i in given_list: #O(n) time if i in hashtable: # O(1) time hashtable[i] += 1 # O(1) time else: hashtable[i] = 1 # O(1) time if hashtable[i] > max_num: # O(1) time max_num = i # grabs key max_count = hashtable[i] # grabs value return max_num, max_count # for item in hashtable.values(): # if item > max_num: # max_num = item #return max_num array = [2, 5, 6, 3, 3, 5, 7, 5] print(most_frequent(array))
true
e788d3bf4f1da7321d9a3d4e96d8f96b719a5982
Tianchi1998/Massey-Assignments
/159.171 1A Question 1.py
565
4.15625
4
# The function below caculates the amount of money that should be repaid each week. def weekly_pay_back(loan_amount,number_of_weeks): result=loan_amount/number_of_weeks return result # The 7 and 8 lines ask the user to enter his information. loan_amount=int(input("Enter an amount: ")) number_of_weeks=int(input("Enter a number of weeks: ")) # Then we call the function and print the result. repay=weekly_pay_back(loan_amount,number_of_weeks) print("You must repay $%0.2f per week to repay a loan of $%d in %d weeks."%(repay,loan_amount,number_of_weeks))
true
493c73b4d9ac741382161a6239138923f7a76eab
Tokeshy/EpamPythonTraining
/01_DataTypes/Task 1.4.py
335
4.375
4
### Task 1.4 #Write a Python program to sort a dictionary by key. DefDict = {1: 2, 3: 4, 2: 9, 4:8} # as ex SortedDict = {} KeyList = [] for key, value in DefDict.items() : if key not in KeyList: KeyList.append(key) for SortedKey in sorted(KeyList): SortedDict[SortedKey] = DefDict[SortedKey] print(SortedDict) # as chk
true
3cd9f4d176b7843ac085568d13ebad1525da4828
Tokeshy/EpamPythonTraining
/02_Functions/Task 4.1.py
362
4.3125
4
### Task 4.1 # Implement a function which receives a string and replaces all `"` symbols # with `'` and vise versa. def Replacer (in_str): out_str = '' for ch in in_str: if ch == '"' : ch = "'" elif ch == "'": ch = '"' out_str = out_str + ch return out_str inp_str = input() print(Replacer(inp_str))
true
f43250a00288e6849c76dca071c8a84d218974ea
fahrettincakir/IZU-datacamp
/ornek6.py
740
4.125
4
######################## # 6.1 soyisim = input("Soyisminiz nedir? ") if soyisim[0] < "K": print("Sınava gireceğiniz sınıf EK 101.") elif soyisim[0] >= "K": print("Sınava gireceğiniz sınıf EK 201.") ######################## ######################## # 6.2 sayı = int(input("3 ile başlayan üç basamaklı bir pozitif bir sayı girin : ")) if sayı < 100: print("Yanlış. İki basamaklı bir sayı girdiniz.") elif sayı < 0: print("Yanlış. Negatif bir sayı girdiniz.") elif sayı > 100 and sayı < 300: print("Yanlış. 100 ile 299 arasında bir sayı girdiniz.") elif sayı > 400 and sayı < 1000: print("Yanlış. Sayınız çok büyük. 300 ile 400 arasında olmalı.") ########################
false
0f0e826c7e1d490b3636644cee05cf21e0168c18
rootthirtytwo/sandbox
/data_structure/queue.py
834
4.21875
4
class Queue: def __init__(self): self.queue = list() def add_item(self, item): if item not in self.queue: self.queue.insert(0, item) # self.queue.insert(len(self.queue), item) def delete_item(self): if len(self.queue) > 0: self.queue.pop() # self.queue.remove(self.queue[0]) def queue_len(self): return len(self.queue) def print_queue(self): if len(self.queue) > 0: return self.queue q = Queue() print("Push A ") q.add_item('A') print("Push B ") q.add_item('B') print("Push C ") q.add_item('C') print("Length of the queue ",q.queue_len()) print("Items in the queue ", q.print_queue()) print("\nPop an item from the queue", sep='\n') q.delete_item() print("Items in the queue after pop", q.print_queue())
false
ad89ae728159df741e30231ddb9527c5718ea69f
Bochkarev90/python2019
/turtle/task_9.py
759
4.375
4
import turtle import math turtle.shape('turtle') def draw_rectangle(n, radius): """ Draws a rectangle n - number of sides radius - circle's radius """ side_length = math.radians(360/(2*n)) * 2 * radius angle = 360 / n turtle.penup() turtle.goto(side_length, 0) turtle.pendown() turtle.left((180 - angle) / 2) for _ in range(n): turtle.left(360 / n) turtle.forward(side_length) turtle.right((180 - angle) / 2) def draw_rectangles(n, radius): """ Draws several rectangles n - number of rectangles radius - radius of the first circle """ r = radius for i in range(3, n+1): draw_rectangle(i, radius) radius += r draw_rectangles(10, 20)
false
eef06c93d884a33eabb2ccb7acd2ab0d71b1182b
Bochkarev90/python2019
/turtle/task_14.py
278
4.25
4
import turtle turtle.shape('turtle') def draw_star(n, size): """ Draws a star with n vertices. size - length of the star's side """ angle = 180 - 180 / n for _ in range(n): turtle.forward(size) turtle.left(angle) draw_star(15, 150)
true
2346e66a526ad1773ab916166bcc69f2d77b0b9a
belug23/Belug-s-Project-Euler-python-answers-in-TDD
/pe_001/pe_001.py
938
4.3125
4
# Problem 1 # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below 1000. def sum_of_multiple_of_3_and_5_under(limit: int) -> int: if limit < 0: raise ValueError("Minimum number must be 0") multiples = get_multiples_of_3_and_5_under(limit) return sum(multiples) def get_multiples_of_3_and_5_under(limit: int): multiples = [] for num in range(limit): if is_multiple_of_3_or_5(num): multiples.append(num) return multiples def is_multiple_of_3_or_5(value: int) -> bool: return is_multiple_of_3(value) or is_multiple_of_5(value) def is_multiple_of_3(value: int) -> bool: return value % 3 == 0 def is_multiple_of_5(value: int) -> bool: return value % 5 == 0 if __name__ == "__main__": print(sum_of_multiple_of_3_and_5_under(1000))
true
450a73aaf4e3e7ac0d71cc015d784e87d69394a1
LynnaOrm/PythonFundamentals
/String_and_List.py
838
4.25
4
#Find and Replace, replace day with month. words = "it's thanksgiving day. It's my birthday, too!" print words.find('day') newWord = words.replace('day','month') print newWord #Min and Max, print the min and max in a list. x = [2,54,-2,7,12,98] print min(x) print max(x) #First and Last, print the first and last values in a list. x = ["hello",2,54,-2,7,12,98,"world"] print x[0], x[len(x) -1] #New List sort your list then split your list in half. Push the list created from the first half to position of 0 of the list created from the second half. #output should be [-3, -2, 2 6, 7],10,12,19,32,54,98] x = [19,2,54,-2,7,12,98,32,10,-3,6] print x x.sort() print x first_list = x[:len(x)/2] second_list = x[len(x)/2:] print "first list", first_list print "second_list", second_list second_list.insert(0,first_list) print second_list
true
eca2a834d3860d5a5d2ed7d3bdd6bdff19ed0b1f
LynnaOrm/PythonFundamentals
/FindCharacters.py
490
4.125
4
#Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character. #hint every word containing the letter "o" word_list = ['Hello','world','my','name','is','Lynna'] char = 'o' def characters(word_list, char): new_list= [] for i in range(0, len(word_list)): if word_list[i].find(char) != -1: new_list.append(word_list[i]) print new_list characters(word_list, char)
true
246dfe73de2381ef10f837d60fbab0ffbc573306
code-drops/hackerrank
/Data structures/01. Arrays/04. Left Rotation.py
652
4.25
4
''' A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array , then the array [1,2,3,4,5] would become [3,4,5,1,2]. Given an array of n integers and a number,d , perform d left rotations on the array. Then print the updated array as a single line of space-separated integers., ''' if __name__ == '__main__': nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) a2 = [0 for i in range(len(a))] for k in range(len(a)): a2[k-d] = a[k] for i in a2: print(i,end=' ')
true
31e655bd56214fd451d7b7a3650f99df06f843b4
code-drops/hackerrank
/contest/Hack The Interview IV(Asia Pacific)/arrange students.py
1,819
4.28125
4
/* A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied: The students must be in order of non-decreasing height. Two boys or two girls must not be adjacent to each other. You have been given the heights of the boys in the array and the heights of the girls in the array . Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not. For example, let's say there are n=3 boys and n=3 girls, where the boys' heights are b=[5,3,8] and the girls' heights are g =[2,4,6]. These students can be arranged in the order [2, 3, 4, 5, 6, 8]. Because this is in order of non-decreasing height, and no two boys or two girls are adjacent to each other, this satisfies the conditions. Therefore, the answer is "YES". */ test_case = int(input()) for test in range(1,test_case+1): number = int(input()) boys = input() boys = boys.split(" ") boys = list(map(lambda x: int(x), boys)) boys = list(sorted(boys)) girls = input() girls = girls.split(" ") girls = list(map(lambda x: int(x), girls)) girls = list(sorted(girls)) final = [] while boys!=[] and girls!=[]: if boys[0]<girls[0]: final.append(boys[0]) final.append(girls[0]) boys.pop(0) girls.pop(0) else: final.append(girls[0]) final.append(boys[0]) boys.pop(0) girls.pop(0) for i in range(1, len(final)): if final[i - 1] <= final[i]: flag = True else: flag = False break if flag: print("YES") else: print("NO")
true
1421ac4a6580bdc60fdc0e05106f0828be93b937
code-drops/hackerrank
/Algorithms/01. Warmup/07. Staircase.py
419
4.375
4
''' Consider a staircase of size n=4: # ## ### #### Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size n. ''' n = int(input()) for i in range(n): for tab in range(n-i-1): print(' ',end='') for k in range(i+1): print('#',end='') print()
true
8f222e213fd69c171b553e1a6006b98fea65b34a
iamsiva11/Codingbat-Solutions
/string1/left2.py
324
4.21875
4
""" Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end. The string length will be at least 2. """ def left2(str): if len(str)<2: return str else: return str[2:]+str[:2] print left2('Hello') # 'lloHe' print left2('java') # 'vaja' print left2('Hi') # 'Hi'
true
bef196da12fbfa1af31ecb3c51ecf14e643a69a1
iamsiva11/Codingbat-Solutions
/list2/big_diff.py
1,151
4.15625
4
""" Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values. """ def big_diff(nums): #Edge Cases if(len(nums)<1): return [] if(len(nums)<2): return nums[0] if(len(nums)==2): #return min(nums[0],nums[1]) return abs(nums[0]-nums[1]) max_val=0 min_val=0 #block for Minimum value if (len(nums)>2): now_min=nums[0] now_min=min(nums[0],nums[1]) #i=2 for i in range(len(nums)): #i=2 if nums[i]<now_min: now_min=nums[i] #print now_min min_val=now_min # if (len(nums)>2): # #block for Maaximum value now_max=nums[0] now_max=max(nums[0],nums[1]) for i in range(len(nums)): #i=2 if nums[i]>now_max: now_max=nums[i] #print now_max max_val=now_max # print max_val # print min_val return max_val-min_val #comments #Should optimise unnecesary comparing of first 2 indexes in the loop print big_diff([10, 3, 5, 6]) # 7 print big_diff([7, 2, 10, 9]) # 8 print big_diff([2, 10, 7, 2]) # 8 print big_diff([3, 9])
true
a6e77d06f5b4ba618a8c06343dc132f179cb2890
iamsiva11/Codingbat-Solutions
/string1/first_two.py
452
4.1875
4
# Given a string, return the string made of its first two chars, # so the String "Hello" yields "He". If the string is shorter than length 2, # return whatever there is, so "X" yields "X", and the empty string # "" yields the empty string "". def first_two(str): first2=str[:2] if len(str)<2: return str return first2 print first_two('Hello') # 'He' print first_two('abcdefg') # 'ab' print first_two('ab') # 'ab' print first_two('') # 'ab'
true
40a8dd0eb042c746ccf292335555be50c545cbbc
Enfioz/pands-problems
/squareroot.py
316
4.21875
4
# Enter positive floating-point number as input # Output an approximation of its square root from math import sqrt def squareroot(x): return(sqrt(x)) x = float(input("Please enter a positive number: ")) ans = (sqrt(x)) y = format(ans, ".1f") print("The square root of %s is approx." % x, y) # push to github
true
b723e7816fe7a6a70df9dde60283c319009dfa26
viruskingkk/PyMiscellaneous
/AI_guess_number.py
549
4.1875
4
while True: try: num = int(input('Enter a number: ')) except ValueError: print ("The input must be a integer!") continue break guess = num / 1.3 middle = num / 2 step = 0 while guess != num: if num > guess: guess += middle print (("I guess: "), guess) elif num < guess: guess -= middle print (("I guess: "), guess) middle /= 2 if middle == 0: middle = 1 step += 1 print (("Aha! The answer is: "), guess) print (("I totally use %d steps.") % step)
true
ea95b3d2b93b3c8ecc05cf6c5d2bbf75858f7b87
Yihu4/Python_study
/2018_after_vacation/how_to_have_infinite_power/fibonacci_counting.py
436
4.15625
4
def fibonacci_counting(n): current = 0 after = 1 for i in range(n): current, after = after, current + after return current # 迭代 print(fibonacci_counting(36)) print(fibonacci_counting(5)) mass_of_earth = 5.9722 * 10**24 # kilograms print(2**10) mass_of_rabbit = 2 # 2 kilograms per rabbit n = 1 while fibonacci_counting(n) * mass_of_rabbit < mass_of_earth: n += 1 print(n, fibonacci_counting(n))
true
975a6b351292c23f64415f1eb6d0dce5c037dce0
hxtruong6/Python-bootcamp
/Generator/homework.py
970
4.5
4
# 1.Create a generator that generates the squares of numbers up to some number N def generates(N): for i in range(N): yield i**2 # 2.Create a generator that yields "n" random numbers between a low and high number (that are inputs). import random def rand_num(low,high, n): for x in range(n): yield random.randint(low,high) # 3.Use the iter() function to convert the string below into an iterator: def convert_string_to_iterator(s): _iter = iter(s) return _iter # 4 """ my_list = [1,2,3,4,5] gencomp = (item for item in my_list if item > 3) for item in gencomp: print(item) gencomp is a generator comprehension. It only return a value when a line code excute/call it Note: A list comprehension uses bracket [] instead of using bracket () likes a generator comprehension """ ######### if __name__== '__main__': # 1 # for x in generates(10): # print(x) # 2 for x in rand_num(1,100, 10): print(x)
true
21bdc00a5ac1049c82f844e61e8f291fde8b5181
arianafm/Python
/Básico/Ejercicios/menu.py
1,581
4.25
4
#Ejercicio de hacer un menú: # -Ingresa opción # -Sumar dos números # -Elevar un número a la potencia n # -Imprime los números pares del 1 al 100 # -Salir Calculadora = True bandera = True while Calculadora: print("Menú") print("1.- Suma dos números.") print("2.- Elevar número a la potencia n.") print("3.- Mostrar números pares del 1 al 100.") print("4.- Salir") num = int(input("Seleccione una opción:")) if num == 1: sum1 = int(input("Ingresa el primer número:")) sum2 = int(input("Ingresa el segundo número:")) sumresul = sum1 + sum2 print(sumresul) continuar = input("¿Deseas volver al menú?") if continuar == "si" or continuar == "Si": continue elif continuar == "no" or continuar == "No": break else: print("---------ERROR-------") break elif num == 2: pot1 = int(input("Ingresa el número:")) pot2 = int(input("Ingresa la potencia:")) potresul = pot1**pot2 print(potresul) continuar = input("¿Deseas volver al menú?") if continuar == "si" or continuar == "Si": continue elif continuar == "no" or continuar == "No": break else: print("---------ERROR-------") break elif num ==3: lista1 = [] lista2 = [] for x in range(1,101,1): lista1.append(x) for y in lista1: if y%2 == 0: lista2.append(y) print(lista2) continuar = input("¿Deseas volver al menú?") if continuar == "si" or continuar == "Si": continue elif continuar == "no" or continuar == "No": break else: print("---------ERROR-------") break elif num ==4: print("Hasta luego.") break
false
74e2ecd9ce622b5b82790f503058b6e5f3491f59
arianafm/Python
/Tareas/Tarea1/matrices.py
1,061
4.3125
4
#Elabora un programa que me permita realizar la suma de dos matrices de 3x3. Cada uno de los elementos de la matriz deberá ser ingresado por el usuario. Una matriz en Python puede implementarse con listas dentro de listas. def elementos(): #Listas por comprensión matriz =[[[] for i in range(3)] for i in range(3)] for i in range(3): for j in range(3): numero = int(input("Ingrese los elementos:")) matriz[i][j] = numero return matriz #print(*x): Desempaca la lista dentro de la llamada de impresión. def imprime(matriz): for x in matriz: print(*x) def suma(ma1,ma2): result = [[0,0,0], [0,0,0], [0,0,0]] for i in range(len(ma1)): for j in range(len(ma1[0])): result[i][j] = ma1[i][j] + ma2[i][j] return result print("___SUMA DE MATRICES___\n") print("Primer matriz:") matriz1 = elementos() #print(matriz1) imprime(matriz1) print("\n") print("Segunda matriz:") matriz2 = elementos() #print(matriz2) imprime(matriz2) print("\n") matrizfin = suma(matriz1,matriz2) print("Matriz resultante:") imprime(matrizfin)
false
97e1ba546f035f1f6891fdec5e681003f244936f
kavyatham/In-a-list-sum-of-numbers
/sum of the list of numbers.py
209
4.3125
4
Dict1 = {"name1":"50","name2":"60","name3":"70"} itemMaxValue = max(Dict1.items(), key=lambda x : x[1]) print('Max value in Dict: ', itemMaxValue[1]) print('Key With Max value in Dict: ', itemMaxValue[0])
false
11a11960a90ed8c7998f4bbf71dd8e90265b1442
nczapla/PHYS400
/Exercise.5.2.py
418
4.25
4
def is_triangle(a,b,c): if a>=b+c: print 'Not today junior!' else: if b>=a+c: print 'Not today junior!' else: if c>=a+b: print 'Not today junior!' else: print 'Houston we have lift off!' def is_triangle1(): print 'Pick three numbers greater than 0 to see if they can form a triangle' a=float(raw_input('a=?\n')) b=float(raw_input('b=?\n')) c=float(raw_input('c=?\n')) is_triangle(a,b,c)
false
659a6a1d5a2daea427240d774f144919606e51d7
gurgalex/pythonmathbook
/ch2/golden_fib.py
944
4.15625
4
"""Compares the fibonacci sequence to the golden ratio using a graph""" from matplotlib import pyplot as plt def fiblist(n): """Returns a list of n fibonacci numbers""" sequence = [i for i in fibseq(n)] return sequence def fibseq(n): """Yields the next fibonacci number""" # Set values for fib 1 and 2 first, second = 1, 1 # compute the next value of the fib sequence for x in range(n): # Only generate a certain amount of values yield first # avoid recursion depth limit first, second = second, first + second n = 100 fibs = fiblist(n) golden = [] for i, fib in enumerate(fibs): if (i == 0): continue else: ratio = fibs[i] / fibs[i-1] golden.append(ratio) x_axis = [x for x in range(1, 100)] # only 99 ratio values plt.title("Ratio between consecutive Fibonacci numbers") plt.xlabel("Seq num") plt.ylabel("Ratio") plt.plot(x_axis, golden) plt.show()
true
b7163fc8ddc4386c6f98665b327c7073c513ab73
TulebaevTemirlan/ICT_labs
/Task1/ex33.py
390
4.15625
4
number_of_breads = float(input("Enter the number of breads you want to buy: ")) discount = 60 price = 3.49 answer = number_of_breads * price * ((100 - discount) / 100) print("\nThe regular price is -- $ " + "{0:.2f}".format(int(number_of_breads * price))) print("The discount is -- " + str(discount) + " %") print("The total price with discount is -- $ " + "{0:.2f}".format(int(answer)))
true
fcad3fef0a680c9d900642c9ff2556a9f5ea95ee
TulebaevTemirlan/ICT_labs
/Task1/ex16.py
295
4.4375
4
# Hint: The area of a circle is area = πr2. # The volume of a sphere is volume= 4 3πr3. import math r = float(input("Enter the radius: ")) area = math.pi * (r**2) volume = math.pi * (r ** 3) print("\nThe area of a circle is " + str(area)) print("The volume of a sphere is " + str(volume))
true
362f8adc6335ea128392a3c2460f7fdfe8b15f7d
TulebaevTemirlan/ICT_labs
/Task1/ex28.py
321
4.15625
4
import math temperature = float(input("Enter the temperature of a wind in Celcius: ")) wind_speed = float(input("Enter the speed of a wind kilometers/hour: ")) WCI = 13.12+ 0.6215 * temperature - 11.37 * wind_speed**0.16 + 0.3965 * temperature * wind_speed**0.16 print("\nThe Wind Chill Index is: " + str(round(WCI)))
true
9a12ff9ff84c6c9e99035d19544678af1d77eab0
BrianCUNY/IS211_Assignment1
/assignment1_part2
459
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Coding assignment 1, P2""" class Book(object): author = " " title = " " def __init__(self, author, title): self.author = author self.title = title def display(self): bookinfo = '"{}, written by {}"'.format(self.title, self.author) print bookinfo BOOK_1 = Book('John Steinbeck', 'Of Mice and Men') BOOK_2 = Book('Harper Lee', 'To Kill a Mockingbird') BOOK_1.display() BOOK_2.display()
true
eb984ce3396e00273e331804620635d70dde108e
AdegokeFawaz/header
/Numbers.py
521
4.15625
4
#this code adds the first number and the second number first_number=4 second_number=4 print(first_number+second_number) #This code divides the first number and the second number first_number=16 second_number=2 print(first_number/second_number) #This code multiplies the first number and the second number first_number=4 second_number=2 print(first_number*second_number) #This code subtracts the first number and the second number first_number=16 second_number=8 print(first_number-second_number) Number(16) print(Number)
true
e1431f0ee27aa1b590a1cbd0039563baaa65cdef
wahabshaikh/problems-vs-algorithms
/problem_1.py
897
4.40625
4
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ try: if number == 0 or number == 1: return number start = 1 end = number while (start <= end): mid = (start + end) // 2 if mid ** 2 < number: res = mid start = mid + 1 elif mid ** 2 > number: end = mid - 1 else: return mid return res except: return "Negative numbers don't have real square roots" ''' Test case 1: Positive Numbers ''' print(sqrt(100)) # Output: 10 print(sqrt(99)) # Output: 9 ''' Test case 2: Zero ''' print(sqrt(0)) # Output: 0 ''' Test case 3: Negative Numbers ''' print(sqrt(-1)) # Output: Negative numbers don't have real square roots
true
f0cf672dad43443e587e08e37a2250f01312fa9c
shardul-shah/Project-Euler
/p4efficient.py
726
4.15625
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ from itertools import combinations_with_replacement def main(): domain = [] for i in range(100, 1000): domain.append(i) unique_multplication_list = list(combinations_with_replacement(domain, 2)) largestPalindrome = 0 for pair in unique_multplication_list: product = pair[0]*pair[1] if (str(product) == str(product)[::-1] and product>largestPalindrome): largestPalindrome = product print("The answer to problem 4 is: " + str(largestPalindrome) + ".") if __name__ == "__main__": main()
true
579b9ce5760116e18c8c367d116540f3196b74ec
mariahabiba078/python-code
/.github/workflows/fizzbuzz prb method1.py
530
4.28125
4
#So the problem is basically to give you the numbers 1 to 100, if the number is divisible by 3, print # 'Fizz', if divisible by 5, print 'Buzz', if divisible by 3 and 5, print 'FizzBuzz'. For other numbers # just print out the number itself." for fizzbuzz in range(100): if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0: print("fizzbuzz") continue elif fizzbuzz % 3 == 0: print("fizz") continue elif fizzbuzz % 5 == 0: print("buzz") continue print(fizzbuzz)
true
deeb87115360c28bf4ea428c637edfac3295040b
shenny88/python_casestudies
/cs4/7_factorial.py
282
4.21875
4
# 7. program which can compute the factorial of a given numbers. Use recursion # to find it. import sys def factorial(mynum): if mynum == 1: return 1 else: mynum = mynum * factorial(mynum -1) return(mynum) num = int(sys.argv[1]) print(factorial(num))
true
f01ff5ab3a092509e90471f44840c90a6fe0d257
mhayes2019/100-Days-of-Codeing-udemy
/day-3-1 Odd or Even.py
551
4.34375
4
# 🚨 Don't change the code below 👇 number = int(input("Which number do you want to check? ")) # 🚨 Don't change the code above 👆 #Write your code below this line 👇 #need to figure out if the number the user chose will come out zero after doing the modulous of 2, because any even number is divided by 2. if the number the user chose comes out to 0 then the number is even, if there is a remainder then the number is odd check_num = number % 2 if check_num == 0: print("Your number is even") else: print("Your number is odd")
true
47a78750a51d0fae96288905cac4f1a42212cc39
wgdcs/learnpython
/lec5/task_1.py
1,382
4.34375
4
print ("введите два числа, одно из которых четное, а другое - нечетное") number_1 = int (input ("введите первое число: ")) number_2 = int (input ("введите второе число: ")) # проверяем, является ли нечетным первое число is_number_1_odd = bool (number_1 % 2 == 1) # проверяем, является ли нечентным второе число is_number_2_odd = bool (number_2 % 2 == 1) # сообщаем о результатах проверки # перебираем все возможные варианты # если первое число - нечетное, а второе - четное if is_number_1_odd and not is_number_2_odd: print ("вы ввели нечетное число ", number_1) # если первое число четное, а второе - нечетное else: if not is_number_1_odd and is_number_2_odd: print ("вы ввели нечетное число ", number_2) # если оба числа - нечетные else: if is_number_1_odd and is_number_2_odd: print ("вы ввели два нечетных числа") # если оба числа - четные else: print ("вы не ввели ни одного нечетного числа")
false
7cfa9f704cd0090ce2252a10815b2493097db4d3
wgdcs/learnpython
/lec5/task_6.py
1,342
4.375
4
# По длинам трех отрезков, введенных пользователем, # определить возможность существования треугольника, # составленного из этих отрезков. # Если такой треугольник существует, то определить, # является ли он разносторонним, равнобедренным или равносторонним. a = float (input ("Введите первую сторону треугольника: ")) b = float (input ("Введите вторую сторону треугольника: ")) c = float (input ("Введите третью сторону треугольника: ")) is_exist = (a < b + c) and (b < a + c) and (c < a + b) if (is_exist): print ("Треугольник с такими сторонами существует") if a == b and b == c: print ("Этот треугольник равносторонний") elif (a == b and b != c) or (b == c and b != a): print ("Этот треугольник равнобедренный") else: print ("Этот треугольник разносторонний") else: print ("Треугольник с такими сторонами не существует")
false
5166c517b1686250fb957848922e64352a8c0e96
assafZaritskyLab/Intro_to_CS_SISE_2021-2022
/week_4/example_12.py
827
4.15625
4
### Question 3 - Students and grades students = [["yael", 87], ["yuval", 88], ["amir", 100]] print(students) # students = ("yael" : 87, "yuval": 88, "amir": 100) # students = ["yael": 87, "yuval": 88, "amir": 100] students = {"yael": 87, "yuval": 88, "amir": 100} # students = {("yael" : 87), ("yuval" : 88), ("amir" : 100)} students_l = [["yael", 87], ["yuval", 88], ["amir", 100]] students_d = {"yael": 87, "yuval": 88, "amir": 100} def get_grade_l(students, name): """students is a nested list, name is a string""" for stud in students: # main list if stud[0] == name: # sub list return stud[1] def get_grade_d(students, name): """students is a dictionary, name is a string""" return students[name] print(get_grade_l(students_l, 'yael')) print(get_grade_d(students_d, 'yael'))
false
bfdb276cd9717bc16c4b9de6ed6bd486c153f3d7
assafZaritskyLab/Intro_to_CS_SISE_2021-2022
/week_2/Example_12.py
577
4.21875
4
# # determine whether a number is prime or not # number = int(input("Enter a number larger than 1: ")) # is_prime = True # assuming the number is prime # # i in range(2, number) # i = 2 # while i < number: # check from 2 to number - 1 # if number % i == 0: # is_prime = False # i += 1 # i = i +1 # # if is_prime: # print("The chosen number is prime") # else: # print("The chosen number is not prime") # # print("s") # print("s") # print("s") # print(-11 % 2) # for (i=0; i< 4; i++) list = [1, 1, 2, 3] for i in range(0, len(list)): print(i)
true
c9b513abc057ff84ffd6d97bcca99b07d9d1849b
assafZaritskyLab/Intro_to_CS_SISE_2021-2022
/week_2/Example_13.py
391
4.25
4
# determine whether a number is prime or not number = int(input("Enter a number larger than 1: ")) is_prime = True # assuming the number is prime i = 2 while i < number and is_prime: # check from 2 to number - 1 if number % i == 0: is_prime = False i += 1 # i = i + 1 if is_prime: print("The chosen number is prime") else: print("The chosen number is not prime")
true
3c794c0ee8fc7308acae66fdd6006b50ee531bbb
tenguterror/personal-growth
/messingWithStrings.py
367
4.40625
4
# This will ask for the user name and print it out last then first. # This was done using string formatting(f strings) and string methods so is the user inputs in lower it will titlecase it print('Hello, what is you first name?') firstName = input().title() print('What is you last name?') lastName = input().title() print(f'Hello {lastName}, {firstName}.')
true
11fba9c4267e533ad849a9dc2458d88eb1c5e288
tejaswiniR161/fewLeetCodeSolutions
/Concepts/Sorting/Merge.py
1,311
4.375
4
#Merge sort uses the divide and conquer technique #time complexity is O(nlogn) #space however is array=input("Enter the numbers to sort them, enter space sepearted integers") array=array.split(" ") #for some reason remember this so, if you use list(array) it'll split even the spaces so spaces will also be in the result, like you saw that coming didn't you! #print(array) array=[int(i) for i in array] #print(array) def mergesort(array): if len(array)>1: mid=len(array)//2 # // for floor division left=array[:mid] print("Split left", left,end='') right=array[mid:] print("Split right", right,end='') left=mergesort(left) #print("All the ones on the left until the end : ",left,end='') right=mergesort(right) #print("All the ones on the right until the end : ",right,end='') array=[] #print("Here") while len(left)>0 and len(right)>0: #print("here") if left[0]<=right[0]: array.append(left[0]) left.pop(0) else: array.append(right[0]) right.pop(0) for j in left: array.append(j) for j in right: array.append(j) return array print(mergesort(array))
true
e748bfaff2149bcc6a08e7d7c47089efc08a0894
sanjipmehta/prime_number
/prime.py
237
4.21875
4
num=int(input("Enter the number:")) for x in range(2,num): if (x==2 or x==3 or x==5 or x==7): print(x,"is a prime number") elif(x%2!=0 and x%3!=0 and x%5!=0 and x%7!=0): print(x,"is a prime number") else: print(x,"is not prime")
true
1108bf3ed45627f8d1b0799300053a18337485aa
LeviMorningstar/Ex.-Estrutura-de-decisao
/Ex. 5(OK).py
1,318
4.1875
4
#Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar: #A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; #A mensagem "Reprovado", se a média for menor do que sete; #A mensagem "Aprovado com Distinção", se a média for igual a dez. print('Inicio do Programa.') print() valid_n1 = False valid_n2 = False while valid_n1 == False: n1 = input('Digite o valor da primeira prova: ') print() try: n1 = float(n1) if n1 >10: print('Erro, o valor nao pode ultrapassar 10') else: valid_n1 = True except: print() print('Erro, digite um valor valido.') print() while valid_n2 == False: n2 = input('Digite o valor da Segunda nota:') print() try: n2 = float(n2) if n2 >10: print('Erro, o valor nao pode ultrapassar 10') else: valid_n2 = True except: print('Erro, digite um valor valido.') media = (n1+n2) / 2 if media == 10: print('Aprovado com Distinção.') elif media >= 7: print('Aprovado.') else: print('Reprovado.') print() print('Fim do programa') print() input('Aperte enter para sair.')
false
bfb76e52a351bf9204af296325bca82da26cb5a0
adowdell18/HowMuchDoesItCostToPaintaTurtle
/paint-a-turtle.py
1,794
4.46875
4
#Computing area of shell import math diameter_shell = eval(input("Enter the diameter of the turtle's shell (in inches): ")) radius_inches_shell = diameter_shell/2 radius_feet_shell= radius_inches_shell/12 area_shell = (3.14* (radius_feet_shell)**2)/2 print("The area of the turtle's shell is ",area_shell, "in square feet") #Computing area of head diameter_head = eval (input("Enter the diameter of the turtle's head (in inches)): ")) radius_inches_head= diameter_head/2 radius_feet_head= radius_inches_head/12 area_head = (3.14 *(radius_feet_head)**2) print("The area of the turtle's head is ", area_head, "in square feet.") #Computing area of tail tail_length = eval(input("Enter the length of one side of the tail (in inches): ")) tail_feet_length = tail_length/12 area_tail = (1/4) * (3)**1/2 * (tail_feet_length)**2 print("The area of the turtle's tail is ", tail_feet_length, "in square inches.") #Computing area of leg leg_length = eval(input("Enter the length of the turtle's leg (in inches): ")) leg_feet_length = leg_length/12 area_leg = leg_feet_length**2 area_legs = area_leg * 2 print("The total area of both legs is ", area_legs, "in square feet.") #Computing area of entire turtle area_turtle= area_shell + area_head + area_tail + area_legs area_turtle_float = format(area_turtle,'0.2f') print("The turtle's area is ", area_turtle_float, "square feet.") #Calculating cost of paiting the turtle paint_needed = area_turtle*0.10 paint_needed_float= format(paint_needed,'0.2f') print ("You will need ", paint_needed_float, "gallons of paint.") cost_paint = 20 * paint_needed cost_paint_float = format(paint_needed,'0.2f') print("It will cost $" ,cost_paint_float,"to repaint the turtle.")
true
16ebd39c87c1a35e69c7074700a0d4908580c556
suareasy/project_euler-python
/solutions/001.py
404
4.3125
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def run() -> int: res = 0 n = 1000 for i in range( n ): if i%3 == 0 or i%5 == 0: res += i return res if __name__ == '__main__': print( run())
true
32e49bff29d0eda5af5608ead6c78bd440fd7c2f
sunny0910/Data-Structures-Algorithms
/stacks & queue/next_greater_element.py
1,860
4.375
4
def next_greater_element(array): """ This approach uses two for loops, one to iterate over every element and second to iterate over subsequent elements to find the next greater element. The time complexity for this approach is O(n^2) :param array: List :return: None """ for i in range(len(array)): found = False print(array[i], end=" - ") for j in range(i+1, len(array)): if array[j] > array[i]: found = True print(array[j]) break if not found: print(-1) def optimised_next_greater_element(array): """ This approach uses a stack to find the next greater element. It pushes the first element in the stack and processes the next elements in a way where if next element is greater than stack top, keep popping the stack top until stack top is lower than next element, then push the next element in the stack. For all the popped elements, next element is the next greater element and the lastly print -1 for elements remaining in the stack as they don't have a next greater element. Considering stack pop, push and comparison operations to be O(1), the time complexity of this approach is O(n) as it traverses the array only once. :param array: List :return: None """ stack = [] op = [-1] * len(array) stack.append(array[0]) for i in range(1, len(array)): if array[i] < stack[-1]: stack.append(array[i]) else: while stack and array[i] > stack[-1]: top = stack.pop() op[array.index(top)] = array[i] stack.append(array[i]) while stack: top = stack.pop() op[array.index(top)] = -1 print(op) a = [9, 7, 2, 4, 6, 8, 12, 1, 5] optimised_next_greater_element(a)
true
71497189bfae4f11e908d988842ec3adec70c55a
sunny0910/Data-Structures-Algorithms
/binary_trees/distance_between_nodes.py
1,269
4.28125
4
from binary_trees.path_to_node import path_to_node from binary_trees.binary_search_tree import BinarySearchTree def distance_between_nodes(root, a, b): """ Function to calculate the distance between two target nodes. Distance is the number of lines covered in the traversal till that node. :param root: Node :param a: Int #target node 1 :param b: Int #target node 2 :return: Int #distance """ path1 = [] path_to_node(root, a, path1) path2 = [] path_to_node(root, b, path2) if not path1 or not path2: return 0 i = len(path1) - 1 j = len(path2) - 1 while path1[i] == path2[j]: i -= 1 j -= 1 if i < 0 or j < 0: break return (i + 1) + (j + 1) if __name__ == "__main__": bst = BinarySearchTree() tree_nodes = [20, 8, 4, 12, 10, 14, 22, 25] """ Tree representation of above numbers 20 / \ 8 22 / \ \ 4 12 25 / \ 10 14 in-order traversal - 4, 8, 10, 12, 14, 20, 22, 25 """ for node_data in tree_nodes: bst.root = bst.insert(bst.root, node_data) x = distance_between_nodes(bst.root, 8, 14) print(x)
true
21386b540c4d1a0bcc0e97a2e9f546ed7efeb34c
sunny0910/Data-Structures-Algorithms
/binary_trees/width_of_tree.py
1,324
4.4375
4
from binary_trees.binary_search_tree import BinarySearchTree def max_width(root): """ Function to calculate width of a binary tree. Width is the maximum number of nodes at any level in a binary tree. This approach uses level order traversal and return maximum length of levels in a tree. :param root: Node :return: Int """ current_level = [root] next_level = [] max_width = len(current_level) while current_level: node = current_level.pop() if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) if not current_level: if len(next_level) > max_width: max_width = len(next_level) current_level, next_level = next_level, current_level return max_width if __name__ == "__main__": bst = BinarySearchTree() tree_nodes = [20, 8, 4, 12, 10, 14, 22, 25] """ Tree representation of above numbers 20 / \ 8 22 / \ \ 4 12 25 / \ 10 14 in-order traversal - 4, 8, 10, 12, 14, 20, 22, 25 """ for node_data in tree_nodes: bst.root = bst.insert(bst.root, node_data) x = max_width(bst.root) print(x)
true
dca3ffd56ae472f37a3b3d73b1c84790d24d3c9c
sunny0910/Data-Structures-Algorithms
/binary_trees/zigzak_traversal.py
2,066
4.4375
4
from binary_trees.binary_search_tree import BinarySearchTree from binary_trees.print_level import print_level from binary_trees.height_of_btree import height def zigzak(root, clockwise): """ Function to print the zig-zak traversal of a binary tree. This function prints new levels by traversing the tree again and again, hence it's not a optimal approach. :param root: Node :param clockwise: Bool #direction of traversal :return: None """ ltr = clockwise for i in range(1, height(root)+1): print_level(root, i, ltr) ltr = not ltr print() def zigzak_using_bfs(root): """ Function to print the zig-zak traversal of a binary tree. The function uses two queues to store the nodes at current level and nodes at next level. If the current level nodes are empty it swaps the current level and next level arrays. The direction of zig-zak traversal can be changed by using a boolean parameter to decide the insertion of left node or right node into the next level array. :param root: Node :return: None """ current_level = [root] next_level = [] while current_level: node = current_level.pop() print(node.data, end=" ") if node.right: next_level.append(node.right) if node.left: next_level.append(node.left) if not current_level: current_level, next_level = next_level, current_level print() if __name__ == "__main__": bst = BinarySearchTree() tree_nodes = [20, 8, 4, 12, 10, 14, 22, 25] """ Tree representation of above numbers 20 / \ 8 22 / \ \ 4 12 25 / \ 10 14 in-order traversal - 4, 8, 10, 12, 14, 20, 22, 25 """ for node_data in tree_nodes: bst.root = bst.insert(bst.root, node_data) print("Clockwise Zigzak traversal") zigzak(bst.root, True) print("Anti-Clockwise Zigzak traversal") zigzak(bst.root, False)
true
f843b65dec038a2c8db23ebb0200dd9503651273
sunny0910/Data-Structures-Algorithms
/matrix/matrix_path.py
1,681
4.28125
4
def path_exits(a): """ Function to check if a matrix path exists from top to bottom :param a: List # Matrix :return: String """ if 1 not in a[0]: return 'safe' q = [[] for i in range(len(a))] for i in range(len(a)): for j in range(len(a[0])): if a[i][j] == 1: q[i].append((i, j)) i = 0 for one_level in q: level_result = 0 for element in one_level: i, j = element flow = [(i+1, j-1), (i+1, j), (i+1, j+1)] if i+1 < len(a) and all(node not in q[i+1] for node in flow): level_result += 1 if level_result == len(one_level): return 'safe' return 'unsafe' def path_exists_recur(a): """ Recursive function to check if a matrix path exists from top to bottom :param a: List :return: String """ def recur(a, i, j): """ Call the function recursively on left, right and bottom elements :param a: List :param i: Int :param j: Int :return: Bool # If path exists """ if i == len(a)-1 and a[i][j] == 1: return True if i < 0 or j < 0 or i > len(a)-1 or j > len(a[0])-1 or a[i][j] == 0: return False return recur(a, i+1, j-1) or recur(a, i+1, j) or recur(a, i+1, j+1) q = [] for index, ai in enumerate(a[0]): if ai == 1: q.append((0, index)) for i in q: x = recur(a, i[0], i[1]) if x: return 'unsafe' return 'safe' a = [ [0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1] ] print(path_exits(a)) print(path_exists_recur(a))
true
fc63aaa4ee0d2fb7da70c8046653fd67393f541e
dlfosterii/python-105
/exercise1.py
399
4.25
4
#prompt user for a single grocery item # -append it toa the 'grocieres' list #in an infinate loop, prompt the user, prompt the user for an item # -append the item to the list # -print()the list after you add the item #to exit out of the loopm oress Ctrl-C groceries = [] while True: item = input(f'Enter an item for your grocery list: ') groceries.append(item) print(groceries)
true
1d774247fe076f3c0648b0c1505ce9462de0822f
emord/project-euler
/python/prob51-60/prob55.py
1,692
4.25
4
#!/usr/bin/python3 """ If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. Not all numbers produce palindromes so quickly. For example, 349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 That is, 349 took three iterations to arrive at a palindrome. Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. How many Lychrel numbers are there below ten-thousand? NOTE: Wording was modified slightly on 24 April 2007 to emphasise the """ import cProfile def isPalindrome(num): return str(num) == str(num)[::-1] def isLychrel(num): for i in range(50): num += int(str(num)[::-1]) if isPalindrome(num): return False return True def main(): result = 0 for i in range(1, 10001): if isLychrel(i): result += 1 print(result) if __name__ == '__main__': cProfile.run('main()')
true
d213e7854b1fa806a55c1dad42715b3501929252
emord/project-euler
/python/prob1-10/prob2.py
961
4.21875
4
#!/usr/bin/python3 """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ import cProfile import libeuler def main(): # naive way #result = 0 #fib = libeuler.fibonacci(maxnum=4*10**6) #for x in fib: # if x % 2 == 0: # result += x #print(result) #better way # calculate every third term (known to be odd) #a = n-2 b = n-1 a = 2 b = 8 result = 10 while b < 4*10**6: result += 4*b + a #even numbers follow this recurrence relation c = 4*b + a a = b b = c result -= b # the last number will be more than 4 million print(result) if __name__ == '__main__': cProfile.run('main()')
true
a0a3edd8c43a194f367fad6e177673bdda541666
adrielleAm/ListaPython
/ClasseTV.py
1,577
4.4375
4
''' 2) Classe TV: Faça um programa que simule um televisor criando-o como um objeto. O usuário deve ser capaz de informar o número do canal e aumentar ou diminuir o volume. Certifique-se de que o número do canal e o nível do volume permanecem dentro de faixas válidas. ''' class tv: def __init__(self, canal, volume): self.canal = canal self.volume = volume @property def canal(self): return self.__canal @canal.setter def canal(self, numero): num = numero if num >= 2 and num <= 65: self.__canal = num else: print("Canal Inválido") @property def volume(self): return self.__volume @volume.setter def volume(self, numero): num = numero if num >= 0 and num <= 100: self.__volume = num else: print("O volume deve ser entre 0 e 100") def mudaCanal(self): num = int(input("CANAL: ")) self.canal = num def mudaVolume(self): num = int(input("VOLUME: ")) self.volume = num def __str__(self): return "CANAL:" + str(self.canal) + " \nVolume: " + str(self.volume) def main(): objTv = tv(2, 10) while True: print(objTv) print("MENU TV ---------") print("1 - mudar canal") print("2 - mudar volume") opcao = input("Selecionar:") if opcao == "1": objTv.mudaCanal() elif opcao == "2": objTv.mudaVolume() else: print("Opção válida!") main()
false
2073778e6dbd3912e543ac5f464be40e81ca5f4f
adrielleAm/ListaPython
/EstruturaRepeticao_3.py
394
4.21875
4
''' Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. ''' user = input("Nome de usuario: ") senha = input("Senha: ") while senha == user: senha = input("Digite uma senha diferente do nome de usuário: ") print("Usuário: " + user + "\nSenha: " + senha)
false
739ae13d86f18ce54b47007fc31abb8bab8e6ac2
adefowoke/coffee-machine
/task/machine/coffee_machine.py
2,928
4.125
4
# create inputs for the machine materials # initialize machine resources water, milk, coffee_beans, cups, money = 400, 540, 120, 9, 550 def remaining(): global water, milk, coffee_beans, cups, money # water += 0 # milk += 0 # coffee_beans += 0 # cups += 0 # money += 0 # if money >= 1: print(f"\nThe coffee machine has:\n" f"{water} of water\n" f"{milk} of milk\n" f"{coffee_beans} of coffee beans\n" f"{cups} of disposable cups\n" f"${money} of money") action_user() def action_user(): print("\nWrite action (buy, fill, take, remaining, exit):") user_action = input() if user_action == "buy": buy() if user_action == "fill": fill() if user_action == "take": take() if user_action == "remaining": remaining() if user_action == "exit": exit_p() def buy(): print("\nWhat do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:") user_2 = input() if user_2 == "1": espresso() if user_2 == "2": latte() if user_2 == "3": cappuccino() if user_2 == "back": action_user() def espresso(): global water, milk, coffee_beans, cups, money es_water = 250 if water >= es_water: print("I have enough resources, making you a coffee!") water -= 250 coffee_beans -= 16 money += 4 cups -= 1 else: print("sorry, not enough water!") action_user() def latte(): global water, milk, coffee_beans, cups, money l_water = 350 if water >= l_water: print("I have enough resources, making you a coffee!") water -= 350 milk -= 75 coffee_beans -= 20 money += 7 cups -= 1 else: print("sorry, not enough water!") action_user() def cappuccino(): global water, milk, coffee_beans, cups, money c_water = 200 if water >= c_water: print("I have enough resources, making you a coffee!") water -= 200 milk -= 100 coffee_beans -= 12 money += 6 cups -= 1 else: print("sorry, not enough water!") action_user() def fill(): print("\nWrite how many ml of water do you want to add:") w = int(input()) print("Write how many ml of milk do you want to add:") m = int(input()) print("Write how many grams of coffee beans do you want to add:") b = int(input()) print("Write how many disposable cups of coffee do you want to add:") c = int(input()) global water, milk, coffee_beans, cups, money water += w milk += m coffee_beans += b cups += c action_user() def take(): global money print("\nI gave you $" + str(money)) money -= money action_user() def exit_p(): exit() def main(): action_user() # remaining() main()
true
9bad3f9582f4a8a85af82d0e0e6b3a7be9ca02ca
thhuynh91/Python_Practice
/Even_Fibonacci_numbers.py
478
4.46875
4
#The Fibonacci number is generated by adding the previous two terms. #For example: below is list of Fibonacci numbers: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #Find the sum of the even-valued terms by considering the terms in Fibonacci sequence whose value do not exceed a given "n" def Fibo(n): total = 0 f1 = 0 f2 = 1 for i in range(n): while f2 < n: if f2%2 == 0: total += f2 f1, f2 = f2, f1 + f2 return(total)
true
4451f145fdc6ae45deb38c1eefb6756e569ec56e
barnybug/aoc2020
/day12.py
1,660
4.1875
4
#!/usr/bin/env python from typing import NamedTuple class Coordinate(NamedTuple): x: int = 0 y: int = 0 def __add__(self, d): return Coordinate(self.x + d.x, self.y + d.y) def __mul__(self, n): return Coordinate(self.x * n, self.y * n) def turn(self, sign): return Coordinate(-sign * self.y, sign * self.x) N = Coordinate(0, -1) S = Coordinate(0, 1) E = Coordinate(1, 0) W = Coordinate(-1, 0) COMPASS = {'N': N, 'S': S, 'E': E, 'W': W,} class Ship: def __init__(self, d, waypoint=False): self.pos = Coordinate() self.d = d self.waypoint = waypoint def turn(self, times, sign): for _ in range(times): self.d = self.d.turn(sign) def forward(self, n): self.pos += self.d * n def move(self, delta): if self.waypoint: self.d += delta else: self.pos += delta def instruction(self, line): c = line[0] n = int(line[1:]) if c in COMPASS: self.move(COMPASS[c] * n) elif c in 'LR': self.turn(n//90, -1 if c == 'L' else 1) elif c == 'F': self.forward(n) def manhattan(self): return abs(self.pos.x) + abs(self.pos.y) def part1(data): ship = Ship(d=E) for line in data.splitlines(): ship.instruction(line) return ship.manhattan() def part2(data): ship = Ship(d=E*10 + N, waypoint=True) for line in data.splitlines(): ship.instruction(line) return ship.manhattan() if __name__ == '__main__': data = open('input12.txt').read() print(part1(data)) print(part2(data))
false
762b19a44435df63dcf0f404c5e16d3013e2efd3
xxiang13/Courses
/MITx_Intro_to_CS_Programming/Lec6_prob10_numValue_inDict.py
391
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 16 @author: Xiang Li """ def howMany(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. ''' sumValue = 0 for i in aDict.keys(): sumValue = sumValue + len(aDict[i]) return sumValue #%%test howMany({ 'a': [1,2,3], 'b': [1], 'c': [1,2]})
false
47e8ec41897b4d624f36816d17ed35ae7e2c4a0d
lisahachmann/SoftDesSp15
/toolbox/word_frequency_analysis/frequency.py
2,452
4.5625
5
""" Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string def get_word_list(file_name): """ Reads the specified project Gutenberg book. Header comments, punctuation, and whitespace are stripped away. The function returns a list of the words used in the book as a list. All words are converted to lower case. """ # new_book = [] f = open(file_name, 'r') lines = f.readlines() current_line = 0 book = [] while lines[current_line+1].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1: current_line += 1 lines = lines[current_line+1:] for line in lines: book.append(line.strip().lower().split(" ")) return book def get_top_n_words(word_list, n): """ Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring. word_list: a list of words (assumed to all be in lower case with no punctuation n: the number of words to return returns: a list of n most frequently occurring words ordered from most frequently to least frequentlyoccurring """ word_popularity = {} all_values = [] pop_words = [] for line in word_list: #creates dictionary of words and how many times they appear in text for word in line: if ','or '' or '.' or '?' or '!' not in word: if word in word_popularity: val = word_popularity.get(word) val += 1 word_popularity[word] = val else: word_popularity[word] = 1 for key in word_popularity: #sorts the amount the words appear, most to least all_values.append(word_popularity[key]) all_values.sort() biggest_values = all_values[::-1] #take only the top n words top_n_words = biggest_values[0:n] for value in top_n_words: #find the words that correspond to these values for key in word_popularity: if word_popularity.get(key) == value: pop_words.append([key, value]) else: continue return pop_words #uncomment to just test this function #print get_word_list("mobydick.txt") #second function, using the first print get_top_n_words(get_word_list("mobydick.txt"), 50)
true
8c60e30f5fcc54b61ba1fdba88413a84f0871bcf
gabrielfern/concurrent-programming
/pythonic-way/async-gen.py
1,079
4.15625
4
#!/usr/bin/python3 # simples execucao assincrona usando python generators # Gabriel Fernandes # gera a quantidade desejada de numeros pares # tam :: tamanho da sequencia desejada def pares(tam): n = 0 while n < tam: yield 2*n n += 1 # gera a quantidade desejada de numeros impares # tam :: tamanho da sequencia desejada def impares(tam): n = 0 while n < tam: yield 2*n + 1 n += 1 # gera a quantidade desejada de numeros pares e impares # tam :: tamanho da sequencia desejada def pares_impares(tam): gen_pares = pares(tam//2 + tam%2) gen_impares = impares(tam//2) for par in gen_pares: yield par yield next(gen_impares) def main(): print('Gerando somente pares:') for n in pares(10): print(n, end=' ') print('\n') print('Gerando somente impares:') for n in impares(10): print(n, end=' ') print('\n') print('Gerando pares e impares ao "mesmo tempo":') for n in pares_impares(10): print(n, end=' ') print() if __name__ == '__main__': main()
false
462dbe269a345d5bd7b08bf70c1375304a5c0b66
sajeendragavi/Learn-Python-Programming-Masterclass
/9_/dictionary_2.py
2,048
4.125
4
# fruit = {"orange" : "a sweet, orange, citrus fruit", # "apple" : "good for making cider", # "lemon" : "a sour, yellow citrus fruit", # "grape" : "a small, sweet fruit growing in bunches", # "lime" : "a sour, green citrus fruit", # "apple" : "round and crunchy"} # # # print(fruit) # # print(fruit) # print(fruit.items()) # f_tuple = tuple(fruit.items()) # print(f_tuple) # # for snack in f_tuple: # item, description = snack # print(item + " is " + description) # print(dict(f_tuple)) #Modify the programme so that the exits is a dictionary rather than a list, #with the keys being the numbers of the locations and the values being #dictionaries holding the exits (as they do at present ).No change should #be needed to the actual code. #once that is working,create another dictionary that contains word that #playes must use.these words will be the keys.and their values will be #a single letter that the program can use to determine which way to go. locations = {0: "You are sitting in front of a computer learning python ", 1: "you are standig at the end of a road before a small brick building ", 2: "you are at the top of a hill", 3: "You are inside a building, a well house for a small stream ", 4: "you are in a valley besides a stream", 5: "You are in the forest"} exits = [{"Q" : 0}, {"W" : 2, "E": 3, "N": 5, "s": 4,"Q": 0}, {"N":5 , "Q": 0}, {"W":1 , "Q": 0}, {"N":1 , "W":2 , "Q": 0}, {"W":2 , "S" :1 , "Q": 0}, ] loc = 1 while True: availableExits = ", ".join(exits[loc].keys()) print(locations[loc]) if loc == 0: break direction = input("Available exits are " + availableExits + " ").upper() print() if direction in exits[loc] : loc = exits[loc][direction] else: print("You can not go in the direction")
true
11733fa8741a2aef2b526bcbd370dafb0e89d468
esizemore/Homework-1
/Sizemore_hw1_prob2
521
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 29 16:39:13 2017 @author: elizabethsizemore """ #Elizabeth Sizemore #HW 1 prob 2 from math import pi,pow #Newton's Gravitational constant (m^3/kg*s^2) G=6.67E-11 #Mass of the Earth (kg) M=5.97E24 #Radius of Earth (m) R=6371000 t=int(input("Please enter how frequently the satelite should orbit the planet (in minutes):")) T=t*60 #equation for altitude (m) h=pow(((G*M*(pow(T,2)))/(4*(pow(pi, 2)))), (1/3)) - R print ('The altitude in meters is:',h)
false
a56c6317f6cc132023f3eb645b7b580b0d67afaf
Dpoudel18/Data-Structures-in-Python
/distinct_elements.py
344
4.1875
4
# A python function to print all the distinct elements of the array. def distinct_elements(my_array): for i in range(len(my_array)): repeat = 1 for j in range(0, i): if (my_array[i] == my_array[j]): repeat = 2 break if (repeat == 1): print(my_array[i])
true
f777d76072a405e156c3c9fd7041eeb3dc068764
jwhitish/learning-python
/strong-pw-detection.py
863
4.15625
4
#simple password strength checker import re userPW = str(input("Enter a password: ")) if len(userPW) < 8: print('Password is not long enough') else: lowerTest = re.compile(r'[a-z]+') test1 = lowerTest.findall(userPW) if len(test1) > 0: print('has lower alpha') upperTest = re.compile(r'[A-Z]+') test2 = upperTest.findall(userPW) if len(test2) > 0: print('has upper alpha') numTest = re.compile(r'\d+') test3 = numTest.findall(userPW) if len(test3) > 0: print('has number') print('Password is secure.') else: print('Password does not contain a number') else: print('Password does not contain upper case letter') else: print('Password does not contain lower case letter')
true
635c389c37e5d467b4fce7ff7b41ee9831a7394c
mragipaltuncu/hogwarts
/player.py
1,591
4.25
4
def choose_character(): """Choose your character""" name = input("What is your name student ?: ") print("") print("It is our choices {0}, that show us who we truly are,\nfar more than our abilities -- Albus Dumbledore".format(name)) print("") while True: print("Which Hogwarts House do you want to choose?") print(""" 1-Gyriffindor 2-Slytherin 3-Ravenclaw 4-Hufflepuff """) building = input("Choose : ") if building == "1": building = "Gyriffindor" break elif building == "2": building = "Slytherin" break elif building == "3": building = "Ravenclaw" break elif building == "4": building = "Hufflepuff" break else: print("Choose wisely!") return (name,building) house_mottos = {"Gyriffindor":"Their daring, nerve and chivalry set Gryffindors apart", "Slytherin":"Slytherin will help you on your way to greatness", "Hufflepuff":"Those patient Hufflepuffs are true and unafraid of toil", "Ravenclaw":"Wit beyond measure is man's greatest treasure"} class Player(): def __init__(self,name="Player's Name",building="Player's Building"): self.name = name self.building = building """ # will add item system in the future # player actions def take_item(self,item): if item not in self.items: print("Added ",item,"to your items") self.items.append(item) return items else: print("You already have that item!") return None def drop_item(self,item): if item in self.items: print("Dropped ",item) self.items.remove(item) return items else: print("You don't have that item") return None """
false
6e83c0ca10ad51d8347fe4398ed02b3590937ac9
kgisl/pythonFDP
/code/mergesort.py
1,184
4.1875
4
import itertools # http://j.mp/zipLongest def mergesort(series): '''iterative mergesort implementation @author kgashok @param series is a sequence of unsorted elements @returns a list containing sorted elements Testable docstring? https://docs.python.org/2/library/doctest.html >>> mergesort([5, 4, 2, 8, 1, 3, 7, 6]) [[5], [4], [2], [8], [1], [3], [7], [6]] [[4, 5], [2, 8], [1, 3], [6, 7]] [[2, 4, 5, 8], [1, 3, 6, 7]] [1, 2, 3, 4, 5, 6, 7, 8] ''' def merge(A, B): merged = [ (A if A[0] < B[0] else B).pop(0) for _ in A + B if len(A) and len(B) ] + A + B return merged iseries = iseries = [[i] for i in series] while len(iseries) > 1: # print("\n", iseries) print(iseries) ilist = iter(iseries) iseries = [merge(a, b) if b else a for a, b in itertools.zip_longest(ilist, ilist)] return iseries[0] print("1st test") print(mergesort([5, 4, 2, 8, 1, 3, 7, 6])) print("2nd test") print(mergesort([1, 2, 3, 4, -1, -100, 290, 22, 5])) if __name__ == "__main__": # import doctest # doctest.testmod() pass
true
b7baef09673eec4a7b58cd57df5722a796cea33d
dmathews98/NumRec
/Unit3/bisecttest.py
1,235
4.125
4
''' Test class for Unit 3 - Exercise 1: The Bisection Method ''' from functions import Functions from bisectclass import Bisect def main(): initx = -4 finalx = 4 numpoints = 500 error = 0.00001 rootsf = [] rootsg = [] rootsh = [] run = Functions(initx, finalx, numpoints) run.plotf() #roots by inspect; [-3, -2], [1, 2], [3, 4] run.plotg() #root by inspect; [0, 1] run.ploth() #roots by inspec; [-0.5, 0.5], [1, 1.5], [2, 2.5], [3, 3.5] bis = Bisect(-3, -2, error) rootsf.append(bis.iterationf(-3, -2)) bis = Bisect(1, 2, error) rootsf.append(bis.iterationf(1, 2)) bis = Bisect(3, 4, error) rootsf.append(bis.iterationf(3, 4)) bis = Bisect(0, 1, error) rootsg.append(bis.iterationg(0, 1)) bis = Bisect(-0.1, 0.1, error) rootsh.append(bis.iterationh(-0.1, 0.1)) bis = Bisect(1, 1.5 , error) rootsh.append(bis.iterationh(1, 1.5)) bis = Bisect(2, 2.5, error) rootsh.append(bis.iterationh(2, 2.5)) bis = Bisect(3, 3.5, error) rootsh.append(bis.iterationh(3, 3.5)) print('The roots of f(x) are ' + str(rootsf)) print('The roots of g(x) are ' + str(rootsg)) print('The roots of h(x) are ' + str(rootsh)) main()
false
654a1a70c8d49597f2e74c1ff4ea1b3c7e4ba05a
erjimrio/Curso-CPP
/Comparativa Python/Ejercicio9-Condicionales.py
531
4.3125
4
"""8. Escribe un programa que lea de la entrada estándar tres números. Después debe leer un cuarto número e indicar si el número coincide con alguno de los introducidos con anterioridad.""" num1 = int(input('Digite num1: ')) num2 = int(input('Digite num2: ')) num3 = int(input('Digite num3: ')) num4 = int(input('Digite num4: ')) if num4 == num1 or num4 == num2 or num4 == num3: print('El cuarto número Coincide con uno de los anteriores') else: print('El cuarto número No coincide con ninguno de los anteriores')
false
c645f9a710fe8622e644a3c73a93481f00b85bac
erjimrio/Curso-CPP
/Comparativa Python/Ejercicio2-Tablas.py
382
4.3125
4
"""2. Realiza un programa que defina una matriz de 3x3 y escriba un ciclo para que muestre la diagonal principal de la matriz. 1 2 3 1 4 5 6 -> 5 7 8 9 9 """ numeros = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # imprime diagonal principal for r in range(0, 3): for c in range(0, 3): if r == c: print(numeros[r][c], ' ', end='')
false
6d04801541acf2d7423ab05be1624ed5fd2bd639
kt3k/codesprint5
/special-multiple/solution.py
541
4.125
4
#! /usr/bin/env python def main(): T = input() for i in range(T): N = input() print special_multiple(N) # generate sequence of positive integers of only 9 and 0 digits def gen(): i = 1 while True: # transform binary representation to special 0,9-sequence # ex. 99 -> "0b1100011" -> "1100011" -> "9900099" -> 9900099 yield int(bin(i)[2:].replace('1', '9')) i += 1 def special_multiple(m): for n in gen(): if n % m == 0: return n main()
false
961b618935e47a24fff62e37ada5bebba1308de8
ShiyuCheng2018/ISTA130-Intro-To-Programming
/assignments/assignment_3/try.py
482
4.34375
4
''' pseudocode: 1. define the function name and the argument: String 1.1 assign an empty string to a variable name called result 1.2 loop through the string that passed in as a local variable cha 1.21 assign double times cha to the result 1.3 print result to check if its expected 1.4 return the result! ''' def double_str(m_string): result = '' for cha in m_string: result += cha * 2 print(result) return result double_str('dog')
true
056c6013e5b051a8a890117c4ccebbebcf0ac49d
weiwenliang666/learning
/传递参数.py
1,442
4.34375
4
''' 值传递:传递的不可变类型 string、tuple、number是不可变的 ''' ''' 引用传递:传递的可变类型 list、dict、set是可变的 ''' '''关键字参数 概念:允许函数调用时参数的顺序与定义时不一致 ''' #使用关键字参数 def myPrint(str,age): print (str,age) myPrint(age = 18, str = 'Today is good day') '''默认参数 概念:调用函数时,如果没有传递参数,则使用默认参数 ''' '''不定长参数 概念:能处理比定义时更多的参数 加了星号*的变量存放所有未命名的变量参数,如果在函数调用时没有指定参数,它就是一个空元组 加了双星号**的变量存放代表键值对的参数字典,如果在函数调用时没有指定参数,他就是一个空字典 ''' '''匿名函数 概念:不适用def这样的语句定义函数,使用lambda来创建匿名函数 特点: 1.lambda只是一个表达式,函数体比def简单 2.lambda主体是一个表达式,而不是代码块,仅仅只能怪在lambda中封装简单的逻辑 3.lambda函数有自己的命名空间,且不能访问自有参数列表之外的或全局命名空间里的参数 4.虽然lambda是一个表达式且看起来只能写一行,与C和C++内联函数不同。 格式:lambda 参数1,参数2,……参数n:expression ''' def func1(A,B,C): print (A,B,C) func1 (3,21,1)
false
fa76b3b7e329162fafea995c657b5b7517c80155
SherazKhan/DS-rep
/Utils/Visualization/box_plot.py
2,041
4.15625
4
# -*- coding: utf-8 -*- """ This file contains function(s) for creating box plots. Created on Thu Aug 10 09:05:23 2017 @author: imazeh """ import numpy as np import matplotlib.pyplot as plt def create_box_plot(df, x_discrete_variable, y_cont_variable, with_outliers=True, all_possible_x_vals=None, plt_title=None): """ Plot a box-plot of a continuous variable for each value of a discrete variable. Input: df (Pandas DataFrame): Should contain both variables as columns. x_discrete_variable (str): The column's name in df. y_cont_variable (str): The column's name in df. with_outliers (bool): Controls whether outliers will be displayed in the plot or not. all_possible_x_vals (list): A sorted list of discrete values for the x-axis in the plot. If None (default), will plot only values which are present in df. If all_possible_x_vals is provided, all values in this list will be plotted on the x-axis (even if there will be no box to plot). plt_title (str): A title for the plot. Output: The plot is plotted, not returned. """ if all_possible_x_vals: x_discrete_values = all_possible_x_vals else: x_discrete_values = sorted(df[x_discrete_variable].unique().tolist()) boxes_vals = [np.asarray(df[y_cont_variable][df[x_discrete_variable] == x]) for x in x_discrete_values] if with_outliers: sym = None else: sym = '' plt.boxplot(boxes_vals, sym=sym) plt.xticks(range(1, len(x_discrete_values)+1), [str(int(x)) for x in x_discrete_values]) plt.xlabel(x_discrete_variable) plt.ylabel(y_cont_variable) if plt_title: plt.title(plt_title) plt.show() # if __name__ == '__main__': # df = placeholder # x_discrete_variable = placeholder # y_cont_variable = placeholder # create_box_plot(df, x_discrete_variable, y_cont_variable)
true
839642c0f8764508a721f7a6a5a4dadb94a26a01
M-Usman-Tahir/PythonPrograms
/Problem Set 2 Task 4.py
1,764
4.125
4
# Programming Fundamentals # Problem Set 2 # Submitted By: Sundas Noreen # Task 4 # Using Tuples to test our program on a variety of choices of Package Sizes. print("\nProblem Set 2, Task 4") bestSoFar = 0 # Keeping track of largest number of McNuggets that cannot be bought in exact quantity. Combination_1 = (6,9,20) # Tuple that contain given Package Size of 6,9,20 that is given. Combination_2= (5,10,14) # Tuple that contains other combinations of Package sizes. Combination_3 = (9,12,14) Combination_4= (20,12,9) Combination_5 = (15,8,6) Combination_6 = (21,15,19) Choices = (Combination_1,Combination_2,Combination_3,Combination_4,Combination_5,Combination_6) test = len(Choices) def is_n_solveable(n,packages): # n is the total number of nuggets. a = 0 # Initializing the multiples of each package size. b = 0 c = 0 for a in range(10): if packages[0]*a + packages[1]*b + packages[2]*c == n: return 1 for b in range(10): if packages[0]*a + packages[1]*b + packages[2]*c == n: return 1 for c in range(10): if packages[0]*a + packages[1]*b + packages[2]*c == n: return 1 return 0 def Variety (packages): # Take Tuple as an argument and will check for highest number that cannot be bought in exact quantity. for n in range(1, 150): if is_n_solveable(n, packages): bestSoFar = bestSoFar + 1 else: bestSoFar = 0 if bestSoFar == packages[0]: print ("\nGiven package sizes", packages[0], ",", packages[1], " and", packages[2], ", the largest number of McNuggets that cannot be bought in exact quantity is:", n-packages[0]) for i in range(test): #Checking all the Choices. Variety(Choices[i])
true
a10496cbfb02d3aec8cb034bb2b4f121a541b45e
M-Usman-Tahir/PythonPrograms
/Tuples and Lists Assignment.py
842
4.5625
5
#Tuples and List by Sundas Noreen #Writing a function that emulates the builtin zip function. #It will take iterables and return a list of tuples. #Each tuple will contain one element from each of the iterables passed to the function. def My_Function(x,y): # Defining the Function with two Input Parameters. Record_List=[] #A list that will be holding the tuples returned.It is initially empty. for i in range(len(x)): #Iterating over one parameter. Tuple=(x[i],y[i]) #writing a tuple with corresponding elements from each parameter. Record_List.insert(i,Tuple) #Insert tuple to the Record_List. return Record_List #Return the Record List. result=My_Function([1,2,3],'abc') #calling the Function print(result) #Printing the Result
true
43fcedf50771bf61bfc70072c53ca04c1580662d
prajapati123476/clean-code-challenge
/challenge-7/largest_element.py
462
4.625
5
# Python3 program to print the largest element # in a list # Input Constraint: array_size >= 5 list_size = 0 # Input until Constraint satisfied while list_size < 5: list_size = int(input("Input size: ")) # Declare empty list elements = list() # Read list from user for i in range(list_size): num = int(input('Input list: ')) elements.append(num) # max (inbuilt in Python) returns maximum element from a structure print(f'The largest is: {max(elements)}')
true
454e460f003c75ec9c5fa4123d428afb1370a5d2
prajapati123476/clean-code-challenge
/challenge-9/count_vowel_words.py
904
4.40625
4
# Python3 program to count the number of words # in input string that start with a vowel # Input Constraint: max_string_size = 500 import sys # Count num of words starting with vowel in param def count_vowel_words(check_string): count = 0 # Generate list of words, on basis of ' ' list_of_words = check_string.split(' ') # check each word in the list for word in list_of_words: # For extra spaces if len(word) == 0: continue # 0th index contains the first letter for each # word. Converting to lowercase ensures that capitals # are counted too if word[0].lower() in ['a', 'e', 'i', 'o', 'u']: count += 1 print(f'Count: {count}') # __main__ code string = input('Enter String: ') # If input constraint violated, exit. Also exit on empty string if len(string) > 500 or len(string) == 0: print('Error: Invalid lenght of string') sys.exit(1) count_vowel_words(string)
true
acf3c0030603d0f6ccadada5af951d738fb47134
BW1ll/Projects
/Python/python_crash_course/Chapter 4/4.3-4.9.py
425
4.125
4
for i in range(1, 21): print(i) nums = [value for value in range(1,1_000_000)] print(nums) print(min(nums)) print(max(nums)) print(sum(nums)) odd_nums = list(range(1, 21, 2)) for num in odd_nums: print(num) multiple3 = list(range(3, 31, 3)) for num in multiple3: print(num) cubes1 = list(range(1, 11)) for value in cubes1: print(value**3) cubes = [value**3 for value in range(1, 11)] print(cubes)
true
0ab2aed573e8d75fcd62f649574e971c382bb224
SubhadeepSen/Python-Core-Basics
/4_Methods/3_Map_Filter.py
668
4.1875
4
def square(num): return num**2; numbers = [1,2,3,4,5,6,7,8]; #Using for loop for n in numbers: print("Square of {} is {}".format(n, square(n))); #Using map() function we can map a function to a list of elements #map(functionNeedsToBeExecuted, listOfElemetns) #returns map object print(map(square, numbers)); for n in map(square, numbers): print(n); squares = list(map(square, numbers)); print("Squares List", squares); def even_square(num): if num%2==0: return num; #Using filter() function #filter(functionNeedsToBeExecuted, listOfElemetns) even_squares = list(filter(even_square, squares)); print("Even Squares List", even_squares);
true
33bb208d1b854e9c01ea723f1831fb473f252783
SubhadeepSen/Python-Core-Basics
/1_DataTypes/String_operation.py
1,430
4.53125
5
name = "Subhadeep Sen"; print("Name: ", name); #Length of a given string length = len(name); print("Length: ", length); #Character at particular index name_0 = name[0]; print("Name[0]: ", name_0); name_5 = name[5]; print("Name[5]: ", name_5); #Substring # str[startIndex:lastIndex] firstName = name[0:9]; print("First Name: ", firstName); #Substring from startIndex to last of the string # str[startIndex:] lastName = name[10:]; print("Last Name: ", lastName); #Substring with step size # str[startIndex:lastIndex:stepSize] steppedName = name[0:9:2]; print("Stepped Name: ", steppedName); #Read string from the end lastChar = name[-1]; print("Last Character: ", lastChar); last_5_Char = name[-5]; print("Last 5th Character: ", last_5_Char); #Reverse String reverse_name = name[::-1]; print("Reverse Name: ", reverse_name); #String concatenation firstName = "Sunny"; concatedString = "Hello " + firstName + ", how are you?"; print(concatedString); #String is immutable #Uncomment the below line and you will see, #TypeError: 'str' object does not support item assignment #name[0] = "K"; #String formatting print("You name is {name}".format(name="Subhadeep Sen")); print("You name is {name} and age is {age}".format(name="Subhadeep Sen", age=25)); name="Subhadeep Sen"; age=25; print("You name is {0} and age is {1}".format(name, age)); salary = 25312.45975; print("You name is {0} and age is {1} and salary is {2:5.2f}".format(name, age, salary))
true
8f98824fdc04655806e918583498749abb515bcf
rzhao04/wave-2
/month name to number of days.py
290
4.1875
4
month = str month = raw_input ("what is month: ") if (month in ["january", "march", "may", "july", "august", "october", "december"]): print ("31 days") if (month in ["april", "june", "september", "november"]): print ("30 days") if (month == "february"): print ("28 or 29 days")
true
d5e5fb6e29e682d8e21f55bef8c16171768a4d44
fixitcode/Hello-python
/Fifo.py
1,102
4.25
4
# coding: utf-8 # In[16]: '''A queue follows FIFO (first-in, first-out). FIFO is the case where the first element added is the first element that can be retrieved. Consider a list with values [1,2,3]. Create functions queueadd and queueretrieve to add and pop elements from the list in FIFO order respectively. After each function call, print the content of the list. Add 7 to the queue and then follow the FIFO rules to pop elements until the list is empty.''' # Function to add an element in to queue def QueueAdd(lfifo,n): lfifo.append(n) #Function to pop an element from queue in fifo order def QueueRetrieve(lfifo): pop = lfifo.pop(0) print ('Item popped from the queue: %d '%pop) fifo=[1,2,3] # Extra code to add user provided input in queue #n=raw_input("Please enter number to add in queue ") #n.strip() #QueueAdd(fifo,n) QueueAdd(fifo,7) print ("Queue after adding element: {}\n".format(fifo)) while True: if fifo: QueueRetrieve(fifo) print('Remaining Queue {}\n'.format(fifo)) else: print("Queue is empty") break
true
0240ac7b4e98d5bf5a77247acd82bd4845b05638
lordzizzy/leet_code
/04_daily_challenge/2021/01-jan/week3/longest_palindromic_substring.py
2,376
4.28125
4
# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3609/ # Longest Palindromic Substring # Given a string s, return the longest palindromic substring in s. # Example 1: # Input: s = "babad" # Output: "bab" # Note: "aba" is also a valid answer. # Example 2: # Input: s = "cbbd" # Output: "bb" # Example 3: # Input: s = "a" # Output: "a" # Example 4: # Input: s = "ac" # Output: "a" # Constraints: # 1 <= s.length <= 1000 # s consist of only digits and English letters (lower-case and/or upper-case) from typing import Callable from termcolor import colored class Solution: def longestPalindrome(self, s: str) -> str: return self.longestPalindrome_expand_from_center(s) def longestPalindrome_expand_from_center(self, s: str) -> str: def expand(s: str, left: int, right: int) -> str: n = len(s) while left >= 0 and right < n and s[left] == s[right]: left -= 1 right += 1 return s[left + 1 : right] res = "" for i in range(0, len(s)): # for the odd case of "aba" s1 = expand(s, i, i) # for the even case of "abba" s2 = expand(s, i, i + 1) # select whichever is the biggest s1 = s1 if len(s1) > len(s2) else s2 res = res if len(res) > len(s1) else s1 return res SolutionFunc = Callable[[str], str] def test_solution(s: str, expected: str) -> None: def test_impl(func: SolutionFunc, s: str, expected: str) -> None: r = func(s) if len(r) == len(expected): print( colored( f"PASSED {func.__name__} => Longest palindromic substring for {s} is {r}", "green", ) ) else: print( colored( f"FAILED {func.__name__} => Longest palindromic substring for {s} is {r} but expected {expected}", "red", ) ) sln = Solution() test_impl(sln.longestPalindrome_expand_from_center, s, expected) if __name__ == "__main__": test_solution(s="babad", expected="bab") test_solution(s="cbbd", expected="bb") test_solution(s="a", expected="a") test_solution(s="ac", expected="a")
true
2c66d493db17934dd11fcb234879c2973389c5e6
lordzizzy/leet_code
/04_daily_challenge/2021/01-jan/week3/count_sorted_vowel_strings.py
2,456
4.21875
4
# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3607/ # Count Sorted Vowel Strings # Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. # A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. # Example 1: # Input: n = 1 # Output: 5 # Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"]. # Example 2: # Input: n = 2 # Output: 15 # Explanation: The 15 sorted strings that consist of vowels only are # ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. # Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet. # Example 3: # Input: n = 33 # Output: 66045 # Constraints: # 1 <= n <= 50 from termcolor import colored class Solution: def __init__(self): self.cache = {} def countVowelStrings(self, n: int): r = self.count(n, 5) # print(self.cache) return r def count(self, n: int, c: int): if n == 1: return c # case of any string N that starts with "u" is always 1 if c == 1: return 1 total = 0 n -= 1 # we only need to loop from 2 <= c <= 5 because when c == 1, the result is just 1 while (c > 1): key = n * 10 + c if r := self.cache.get(key): total += r else: r = self.cache[key] = self.count(n, c) total += r c -= 1 # finally just add 1 for the c == 1 case return total + 1 def test_Solution(n: int, expected: int): s = Solution() count = s.countVowelStrings(n) if count == expected: print(colored( f"PASSED - Vowel string count for size {n} is {count}", "green")) else: print(colored( f"FAILED - Vowel string count for size {n} is {count} but expected {expected}", "red")) if __name__ == "__main__": # default solution using dict for cache test_Solution(n=1, expected=5) test_Solution(n=2, expected=15) test_Solution(n=3, expected=35) test_Solution(n=4, expected=70) test_Solution(n=5, expected=126) test_Solution(n=6, expected=210) test_Solution(n=7, expected=330) test_Solution(n=33, expected=66045)
true
c3ddb3bf94ebf1718c478cc0f1dbf22e6f36c684
lordzizzy/leet_code
/04_daily_challenge/2021/04-apr/week4/power_of_three.py
2,113
4.40625
4
# # https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/596/week-4-april-22nd-april-28th/3722/ # Power of Three # Given an integer n, return true if it is a power of three. Otherwise, return # false. # An integer n is a power of three, if there exists an integer x such that n == # 3x. # Example 1: # Input: n = 27 # Output: true # Example 2: # Input: n = 0 # Output: false # Example 3: # Input: n = 9 # Output: true # Example 4: # Input: n = 45 # Output: false # Constraints: # -231 <= n <= 231 - 1 # Follow up: Could you solve it without loops/recursion? # https://leetcode.com/problems/power-of-three/solution/ from typing import Callable from termcolor import colored import math class Solution: def isPowerOfThree(self, n: int) -> bool: return self.isPowerOfThree_int_limitations(n) def isPowerOfThree_int_limitations(self, n: int) -> bool: return n > 0 and 3 ** 19 % n == 0 def isPowerOfThree_iterative(self, n: int) -> bool: if n < 1: return False while n % 3 == 0: n //= 3 return n == 1 def isPowerOfThree_log(self, n: int) -> bool: return (math.log10(n) / math.log10(3)) % 1 == 0 SolutionFunc = Callable[[int], bool] def test_solution(n: int, expected: bool) -> None: def test_impl(func: SolutionFunc, n: int, expected: bool) -> None: r = func(n) if r == expected: print( colored( f"PASSED {func.__name__} => {n} is a power of 3 is {r}", "green" ) ) else: print( colored( f"FAILED {func.__name__} => {n} is a power of 3 is {r}, but expected is {expected}", "red", ) ) sln = Solution() test_impl(sln.isPowerOfThree_int_limitations, n, expected) test_impl(sln.isPowerOfThree_iterative, n, expected) test_impl(sln.isPowerOfThree_log, n, expected) if __name__ == "__main__": test_solution(n=27, expected=True) test_solution(n=1024, expected=False)
true
705f19655e764983cd30ec9cc85fa1c1b71d058d
lordzizzy/leet_code
/04_daily_challenge/2021/07-july/week4/beautiful_array.py
2,660
4.1875
4
# https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/611/week-4-july-22nd-july-28th/3829/ # Beautiful Array # An array nums of length n is beautiful if: # nums is a permutation of the integers in the range [1, n]. # For every 0 <= i < j < n, there is no index k with i < k < j where 2 * # nums[k] == nums[i] + nums[j]. # Given the integer n, return any beautiful array nums of length n. There will # be at least one valid answer for the given n. # Example 1: # Input: n = 4 # Output: [2,1,4,3] # Example 2: # Input: n = 5 # Output: [3,1,2,5,4] # Constraints: # 1 <= n <= 1000 # explanations for this tricky problem # https://leetcode.com/problems/beautiful-array/discuss/1368125/Detailed-Explanation-with-Diagrams.-A-Collection-of-Ideas-from-Multiple-Posts.-Python3 from typing import Callable, List from termcolor import colored class Solution: # Time complexity: O(N) # Space complexity: O(N) def beautifulArray_divide_and_conquer_oddeven_recursive(self, n: int) -> List[int]: def divide_and_conquer(l: List[int]) -> List[int]: if len(l) < 3: return l odd = l[::2] even = l[1::2] return divide_and_conquer(odd) + divide_and_conquer(even) return divide_and_conquer(list(range(1, n + 1))) # Time complexity: O(N) # Space complexity: O(N) def beautifulArray_divide_and_conquer_oddeven_iterative(self, n: int) -> List[int]: res = [1] while len(res) < n: res = [i * 2 - 1 for i in res] + [i * 2 for i in res] return [i for i in res if i <= n] SolutionFunc = Callable[[int], List[int]] def test_solution(n: int, expected: List[int]) -> None: def test_impl(func: SolutionFunc, n: int, expected: List[int]) -> None: res = func(n) if res == expected: print( colored( f"PASSED {func.__name__} => Beatiful array of length {n} is {res}", "green", ) ) else: print( colored( f"FAILED {func.__name__} => Beatiful array of length {n} is {res} but expected {expected}", "red", ) ) sln = Solution() test_impl(sln.beautifulArray_divide_and_conquer_oddeven_recursive, n, expected) test_impl(sln.beautifulArray_divide_and_conquer_oddeven_iterative, n, expected) def main() -> None: test_solution(n=3, expected=[1, 3, 2]) test_solution(n=4, expected=[1, 3, 2, 4]) test_solution(n=5, expected=[1, 5, 3, 2, 4]) if __name__ == "__main__": main()
true
8eed14a8dec53b19bc3f644868f4646c1cda8935
JudoboyAlex/python_fundamentals1
/exercise6.2.py
1,667
4.4375
4
# You started the day with energy, but you are going to get tired as you travel! Keep track of your energy. # If you walk, your energy should increase. If you run, it should decrease. Moreover, you should not be able to run if your energy is zero. # ...then, go crazy with it! Allow the user to rest and eat. Do whatever you think might be interesting. # Congrats for making it this far! distance_count = 0 energy = 100 while distance_count >= 0 and energy >= 0: print("Do you want to run or walk or go home?") action = input() if action == "walk": print("Distance from home is {}km. Your current energy level is {}".format(distance_count + 1, energy + 30)) distance_count += 1 energy += 30 elif action == "run": print("Distance from home is {}km. Your current energy level is {}".format(distance_count + 5, energy - 50)) distance_count += 5 energy -= 50 elif action == "rest": print("Good idea. Relax your body. Your energy level got boosted to {}".format(energy + 35)) energy += 35 elif action == "go home": print("Good job! Sprint back to home now hahaha!") break else: print("You entered wrong command") if energy <= 0: print("You are out of energy. Do you want to rest?(yes or no)") action2 = input() if action2 == "yes": print("Ok, you are good to go. Your energy level recovered to {}".format(energy + 35)) energy += 35 elif action2 == "no": print("Just make sure take it easy") break else: print("You entered wrong command")
true
15de37c13d5b459e5cd75ec427a4345ec6d2294f
Lukas-N/Projects
/L5.py
429
4.15625
4
Bottles = int(input("How many green bottles are there: ")) while Bottles > 1: print(Bottles, "green bottles hanging on the wall, and if one green bottle were to accidently fall, there would be", (Bottles -1), "green bottle(s) hanging on the wall") Bottles = Bottles -1 print("1 green bottle hanging on the wall, if that one green bottle shall accidently fall, there would be no green bottles hanging on the wall")
true
4d1ca25ab9bd4f77a4a415fdd9dd14db66f2e4c5
Rishik999/BSc_IT_Python
/pracs/unit_1/prac_1c_fibonacci.py
311
4.1875
4
# PYTHON PROGRAM TO GENERATE FIBONACCI SERIES # user input num = int(input("Enter a number: ")) # initializing variables old = 0 new = 1 count = 0 # while loop to run until counter reaches the given number while count <= num: next = old + new print(old) old = new new = next count += 1
true
5f91500b1d550a84eb01f20e8af063f2273e8192
Rishik999/BSc_IT_Python
/pracs/unit_1/prac_1b_odd_even.py
313
4.4375
4
# PYTHON PROGRAM TO CHECK IF THE NUMBER IS EVEN OR ODD # user input num = input("Please enter a number: ") # using modulus operator to check if the remainder is 0 i.e. if it is divisible by 2 if int(num) % 2 == 0: print("Entered number is an even number") else: print("Entered number is an odd number")
true
6c14e816e6bd5251daec42c8d71c3fd00c474981
Rishik999/BSc_IT_Python
/pracs/unit_4/prac_4c_clone_list.py
344
4.4375
4
# PYTHON PROGRAM TO CLONE A LIST # initializing lists list_1 = [44, 54, 22, 71, 67, 89, 20, 99] list_2 = [] # empty list to store elements from list_1 # for loop to iterate list_1 for x in list_1: list_2.append(x) # append each element (x) from list_1 to list_2 # output print("Original list: ", list_1) print("Cloned list: ", list_2)
true
59270649836a6f75ba96305618e67b36535a7af8
Rishik999/BSc_IT_Python
/pracs/unit_7/prac_7a_class_student.py
851
4.3125
4
# CLASS STUDENT TO STORE AND DISPLAY INFORMATION class Student: # The __init__ is a special method used to initialise any class # The parameters passed in the init method are necessary to create an instance of that class def __init__(self, first, last, score): self.first = first self.last = last self.score = score # This method returns the fullname of the student by concatinating self.firts and self.last def get_fullname(self): fullname = self.first + " " + self.last return fullname # initializing 2 instances of class Student student_1 = Student('Virat', 'Kohli', 78) student_2 = Student('Jasprit', 'Bumrah', 88) # output print("{} has scored {}%".format(student_1.get_fullname(), student_1.score)) print("{} has scored {}%".format(student_2.get_fullname(), student_2.score))
true
469f876e7eb620c0875414d8444c3e246977dec9
Ghroznak/python_practice
/hangman.py
1,608
4.1875
4
# Hangman import random def make_a_word(strng): #create a def or remove it again? revert strng to secret_word if removed. word_File_path = '/Users/RogerMBA/PycharmProjects/Hangman/english3.txt' f = open('english3.txt', 'r') lines = f.readlines() for index, line in enumerate(lines): lines[index] = line.strip('\n') strng = lines[random.randint(1, len(lines))] strng = strng.upper() print(strng) return strng make_a_word(secret_word) reveal_word = ["_"] * len(secret_word) used_letter = [] wrong_letter = [] win_condition = list(secret_word) win_condition = ' '.join(win_condition) def compare(strng): if not strng.isalpha() or len(strng) > 1: print("Please guess only one letter at a time! Try again!") elif strng in used_letter: print("The letter >> " + str(strng) + " << has already been used. Try again!") elif strng in secret_word: print("You found a letter! " + str(strng) + " was in the word!") used_letter.append(strng) for index, value in enumerate(secret_word): if value == strng: reveal_word[index] = strng the_word = ' '.join(reveal_word) if the_word == win_condition: print("You figured it out! Congratulations!") exit() else: print("So far you revealed this much of the word " + str(the_word)) else: used_letter.append(strng) wrong_letter.append(strng) attempts = 10 - len(wrong_letter) print("That letter was not in the word. Try again!\n You have " + str(attempts) + " attempts left!") if attempts == 0: print("\nYou lost you klutz!") exit() while 1: guess = input("Guess a letter: ") guess = guess.upper() compare(guess)
true
026bb3b7be0ea9e4d0577e90096a3edd68b8015b
sunny-g/ud036
/lesson2/lesson2a.py
2,399
4.4375
4
''' lesson 2 - building a movie website build a site that hosts movie trailers and their info steps: 1. we need: title synopsis release date ratings this means we need a template for this data, ex: avatar.show_info(), toyStory.show_trailer() but we dont want to use separate modules/files for each movie CLASSES learning classes by drawing shapes classes is a lot like a blueprint same blueprint can be used to make similar buildings objects are examples of the class blueprint turtle module Turtle class a neatly packaged box turtle.Turtle() calls the function __init__ w/in class Turtle creates a new instance of Turtle and inherits all of the methods webbrowser.open() vs turtle.Turtle() the first calls a function the second calls the init func, which allocates memory and creates an obj steps to make multiple squares that make a circle 1. build a square 2. for n < 360/tiltangle, tilt by some amount and build another square ''' import turtle def drawThings(): redbox = turtle.Screen() redbox.bgcolor("red") # brad = turtle.Turtle() # brad.shape("turtle") # brad.color("blue") # brad.speed(60) sunny = turtle.Turtle() sunny.shape("turtle") sunny.color("black") sunny.speed("3") ''' draws a series of squares that make a circle num = 1 tiltAngle = 6 tilts = 360 / tiltAngle drawSquare(brad) while num < tilts: brad.right(tiltAngle) drawSquare(brad) num += 1 ''' drawSunnysName(sunny) redbox.exitonclick() # angie = turtle.Turtle() # angie.shape("arrow") # angie.color("yellow") # drawCircle(angie) def drawSunnysName(person): # draws the letter 'S' person.left(90) person.circle(100, 270) person.circle(-100, 270) # moves the turtle to draw the next letter person.penup() person.forward(100) person.right(90) person.forward(600) person.pendown() # draws the letter 'G' person.left(90) person.penup() person.circle(200, 45) person.pendown() person.circle(200, 315) person.left(90) person.forward(200) def drawSquare(someTurtle): for i in range(1, 5): someTurtle.forward(100) someTurtle.right(90) def drawCircle(someTurtle): someTurtle.circle(100) main()
true
7a305cdf89b311875b172dc6c4e74188ab6b0355
greenfox-zerda-lasers/bereczb
/week-04/day-3/09.py
504
4.15625
4
# create a 300x300 canvas. # create a square drawing function that takes 1 parameter: # the square size # and draws a square of that size to the center of the canvas. # draw 3 squares with that function. from tkinter import * def draw_square(a): canvas.create_rectangle(150 - a / 2, 150 - a / 2, 150 + a / 2, 150 + a / 2) root = Tk() width = 300 height = 300 canvas = Canvas(root, width = width, height = height) canvas.pack() draw_square(200) draw_square(100) draw_square(12) root.mainloop()
true