blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ad192701a9d26d6324acd9d85ec8af2711fd1b8a
linpeijie-python/linpeijiecode
/python_practice/demo1.py
1,832
4.15625
4
""" 题目: 一个多回合制游戏,每个角色都有hp 和power, hp代表血量,power代表攻击力,hp的初始值为1000, power的初始值为200。打斗多个回合 定义一个fight方法: my_hp = my_hp - enemy_power enemy_hp = enemy_hp - my_power 谁的hp先为0,那么谁就输了 """ """ 思路: 1、自定义一个关键字函数,后续调用关键字函数可以输入对应的角色血量值和角色的攻击力 2、定义方法fight,游戏规则: 初始化回合数 角色血量=初始血量-对方攻击力 每一轮攻击完成后使用while(true)进行比较,判断是否有角色血量为0 如果有角色血量为0,则break输出对应结果 """ #自定义关键字函数 def fight(my_hp,enemy_hp,my_power,enemy_power): # 初始化战斗回合 fight_round = 1 while True: # 计算我的剩余血量 my_hp = my_hp - enemy_power #输出当前轮次我剩余血量值 print("第", fight_round, "轮后,我的剩余血量是:", my_hp) # 计算敌人的剩余血量 enemy_hp = enemy_hp - my_power #输出当前轮次敌人剩余血量值 print("第", fight_round, "轮后,敌人的剩余血量是:", enemy_hp) # 计算战斗汇合 fight_round = fight_round + 1 # 判断谁先输 # 我的血量是否<=0 if my_hp <= 0: #如果我的血量<=0,输出我输了 print("我输了!") #成立则跳出循环并且结束 break #判断敌人血量是否<=0 elif enemy_hp <= 0: # 如果敌人的血量<=0,输出我赢了 print("我赢了!") # 成立则跳出循环并且结束 break # 调用自定义函数 fight(1000,800,200,200)
false
504d10f25cf93020095f593154fda4f8f0b296e8
AbrahamdelaMelena/PC4Datux
/MODULO 02/Modulo_02_Ej_01_Abraham_dela_Melena.py
2,829
4.25
4
""" Realizar una función que permita la carga de n alumnos. Por cada alumno se deberá preguntar el nombre completo y permitir el ingreso de 3 notas. Las notas deben estar comprendidas entre 0 y 10. Devolver el listado de alumnos. """ encabezado = ["NOMBRE", "APELLIDO", "NOTA 01", "NOTA 02", "NOTA 03"] lista_alumno = [] contador = 0 def Alumnos(): rpta = "si" contador = 0 not1 = 11 not2 = 11 not3 = 11 while rpta != "no": nom = (input("Ingrese el nombre del alumno: ")) for i in nom: if i.isdigit(): nom = input("El nombre no puede tener numeros, ingreselo nuevamente") ape = (input("Ingrese el apellido del alumno: ")) for i in ape: if i.isdigit(): ape = input("El apellido no puede tener numeros, ingreselo nuevamente") if not1 > 10: while not1 > 10: print("Ingrese una nota de 0 a 10") try: not1 = int(input("Ingrese la primer nota del alumno: ")) except ValueError: print("No puede ingresar letras en este campo, vuelva a ingresar solo numeros") not1 = int(input("Ingrese la primera nota del alumno entre 0 y 10")) if not2 > 10: while not2 > 10: print("Ingrese una nota de 0 a 10") try: not2 = int(input("Ingrese la segunda nota del alumno: ")) except ValueError: print("No puede ingresar letras en este campo, vuelva a ingresar solo numeros") not2 = int(input("Ingrese la segunda nota del alumno entre 0 y 10")) if not3 > 10: while not3 > 10: print("Ingrese una nota de 0 a 10") try: not3 = int(input("Ingrese la tercera nota del alumno: ")) except ValueError: print("No puede ingresar letras en este campo, vuelva a ingresar solo numeros") not3 = int(input("Ingrese la tercera nota del alumno entre 0 y 10")) lista_alumno.append(nom) lista_alumno.append(ape) lista_alumno.append(not1) lista_alumno.append(not2) lista_alumno.append(not3) lista_alumno.append("<---->") print(encabezado) print(lista_alumno) #No se me ocurrio otra forma de hacer que el programa continue y ya le habia dado demasiadas vueltas :´v not1 = 11 not2 = 11 not3 = 11 contador = contador + 1 print(f"Ha ingresado los datos de {contador} alumnos, desea continuar?") rpta = input("Ingrese si o no") if rpta == "no": break Alumnos()
false
042f57686f14c99820de9f91218d3a7ff4b994e5
katel85/Labs-pands
/labsweek07/quizB.py
726
4.28125
4
# the with statement will automatically close the file # when it is finished with it with open("test-b.txt", "w") as f: data = f.write("test b\n") # returns the number of chars written print (data) #with open("test-b.txt", "w") as f2: # open file again # data = f2.write("another line\n") # print (data) # in the first program when the text file is created called test-b and the input data = f.write"test b\n' creates # 7 chars. when the file is opened again and named f2 the date is updated to f2.write("another line\n"). # Both files were also opened with "w" allowing the programmer to read in data. # The amount of chars here has now changed to 13. so the program when run will print out # 7 # 13 #
true
261280bfba8cf9a15f3168a46132b3fc46068910
katel85/Labs-pands
/labsweek06/week06-functions/Menudisplay.py
716
4.28125
4
# Write a program that will keep displaying menu until the user chooses to quit. Call a function for A called do add() # call a function for V if the user chooses to view called do view(). # Catherine Leddy def displaymenu () : print("what would you like to do?") print("\t(a) Add a new student") print("\t(v) View students") print("\t(q) Quit") choice = input("type one letter (a/v/q):").strip() return choice def doAdd() : print("in adding") def doView() : print("in viewing") choice=displaymenu() while(choice != 'q') : if choice =='a': doAdd() elif choice =='v': doView() elif choice !='q': print('\n\nPlease select either a,v or q') choice=displaymenu()
true
53d6088de5a24a7a52af91768dc30bf34a58ce5e
katel85/Labs-pands
/labsweek02/Lab2.2/hello2.py
787
4.25
4
# ask for name and set up for reading out name in response to prompt # Kate Leddy name= input('What is your name') print ('Hello ' + name) #first pose the question this is the input # In order to save the answer to the question it must be saved as "name " = input age= int(input('Hey what is your age?:')) newNumber = age - 5 print ( ' your age is {} wow you are so young you could pass for {} ' .format (age, newNumber)) # want to add an additional age but I get newage= str (age - 5) incorrect formatting in code # fix: needed to put int before the input # prob File ".\readkate.py", line 11 # fix I needed to close the brackets at the end of line 11!!! place= input( 'where do you like to go on holidays ?') print (' {} is an amazing place to go on holidays !' .format (place))
true
b4d45800e40d2fc5e1c661aacb32960a63ded9a4
shayroy/ChamplainVR
/Week 7/Class1/Class_review.py
902
4.3125
4
class Shape: colour = "" # colour is an attribute of Shape # Constructor def __init__(self, input_colour): # variable colour that we input # how do we set the colour to the input_colour. We have to use Self.colour = input_colour self.colour = input_colour # if we want shape to do something # action here is to delcare yourself def declare_yourself(self): print("I am a shape and my colour is " + self.colour) # remember self is always required. # self refers to method variable. In this case, self.colour. # pass colour in brackets to the object triangle1. Instantiation triangle1 = Shape("Green") # To have triangle1 declare itself: triangle1.declare_yourself() # delete an object with del # del triangle1 # triangle1.declare_yourself() # If you uncomment the previous 2 lines you should give error as triangle1 has been deleted
true
faad8b7f53bde558d0c5f720dc7d5a2cc41b3cad
shayroy/ChamplainVR
/Assignments/Order_System_Team/Input_From_User.py
2,290
4.125
4
from Item import Item from Order import Order answer_string = "" users_new_order = Order() while answer_string != "FIN": answer_string = input("\nWhat do you want to do next?"+ "\n\tTo add a new item to your order type 'ADD'"+ "\n\tTo delete any item from your order type: 'DEL'"+ "\n\tTo complete your order type: 'FIN'"+ "\n\n\t\tPlease, type your choice HERE: >> ").upper() if answer_string == "ADD": print("\nPlease, give the following information: \n") while True: try: sku = int(input("Please, input the 8 digits of the item's SKU. >> ")) while len(str(sku)) != 8: sku = int(input("Please, check the item's SKU, it should contain 8 digits. >> ")) break except ValueError: print("This field accepts only digits from 0 to 9 ") name = input("Please, input the item's name >> ").title() while True: try: price = float(input("Please, input the item's price >> ")) break except ValueError: print("This field accepts only digits from 0 to 9 and a decimal point.") is_taxable = input("Is this item taxable? (Y/N) >> ").upper() while True: if is_taxable == "Y": taxable = True break elif is_taxable == "N": taxable = False break else: print("Your input is not valid, please, try again.") is_taxable = input("Is this item taxable? (Y/N) >> ").upper() new_item = Item(sku, name, price, taxable) users_new_order.add_item(new_item) elif answer_string == "DEL": print(users_new_order.print_order_summary()) sku_to_delete = int(input("Please, enter the SKU of item you want to delete >> ")) users_new_order.remove_item(sku_to_delete) print(users_new_order.print_order_summary()) elif answer_string == "FIN": print(users_new_order.print_order_summary()) else: print("It seams that you've chosen non-existent option. Please, try again.")
true
380772852b0996806e2594b22a2af4e08efdc47a
shayroy/ChamplainVR
/Week 10/Class1/TestDir.py
484
4.28125
4
import os dirname = "TestDir" def create_dir_if_not_existing(name): """Checks the existance of a directory and creates it if necessary.""" if not os.path.isdir(name): # if not statement is negation of if statement. # can also use and add another part, such as another if not os.mkdir(name) print("Directory " + name + "created.") else: print("The supplied name is a directory that already exists.") create_dir_if_not_existing(dirname)
true
95e1950dc090d4fa0d7caa575ea2fcad4115d91b
shayroy/ChamplainVR
/Week 3/Class 1/review strings.py
451
4.34375
4
#Uppercase, Titlecase, lowercase, length and replacement are important. #for length "The Length of the string is x". #for replacement, he would like us to change all "!" to ".". myString = input(">") print(myString.upper()) print(myString.title()) print(myString.lower()) print(">the length of the entered string is " + str(len(myString))) print(myString.replace("!", ".")) #can concantonate more than one print(myString.upper().replace("!", "."))
true
56ba88a7773b328e42b979090c850a25865a4db9
shayroy/ChamplainVR
/Week 5/Class1/iterate_over_list.py
602
4.375
4
# see printing all keys and values slide #for x in countries: # print(x) # # to print keys, values and items (which prints both keys and values): countries = {'us': 'USA', 'fr': 'France', 'uk': 'United Kingdom'} for k, v in countries: print(k,v) print ("------------") for i in countries.items(): print(i[1]) print("----------") for a, b in countries.items(): print(a, b) print("-----------") for a in countries.keys(): print(a) print("-----------") for v in countries.values(): print(v) # The printouts do not seem to always be what I expect
true
69e99ef3541c8affa35caba01b26ff8454bbb1fb
saikumargu/EDA
/Functions.py
1,234
4.3125
4
#Functions def square(num): out = num**2 return(out) square square(7) square(9) q = square(4) print("Square of number is "+str(q)) def factorial(n): if n>1: return n*factorial(n-1) else: return n fact = factorial(5) print(fact) def factorial(n): if n>1: return n*factorial(n-1) else: return n fact = factorial(5) print(fact) print(type(factorial)) print(type(fact)) def addition(*args): print(args) return(sum(args)) print(addition(4,5,6,7,8,9)) print(addition(1,2)) def add_num(a,b): print(a,b) c=a+b return(c) add_num(4,5) x = add_num(5,6) x def my_function(country ): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") def my_function(country = "China"): print("I am from " + country) # lambda Function #A lambda function is a small anonymous function. #A lambda function can take any number of arguments, but can only have one expression. x = lambda a : a + 10 print(x(5)) x = lambda a, b : a * b print(x(5, 6)) x = lambda a, b, c : a + b + c print(x(5, 6, 2))
true
f535ff6aac32d39c32f89a6b16b87e9337e85bce
edelvandro/Python
/condicionais/exer036.py
946
4.1875
4
''' Escreva um programa para aprovar um empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou então empréstimo será negado. ''' valor_casa = float(input('Digite o valor da casa:R$ ').strip()) salario = float(input('Digite o valor do salário:R$ ').strip()) anos = int(input('Digite em quantos anos deseja pagar: ').strip()) valor_parcela = valor_casa / (anos * 12) valor_maximo = salario * (30 / 100) if valor_parcela >= valor_maximo: print( ' "FINANCIAMENTO NEGADO" O valor da parcela será de R${:.2f} e excede ao máximo permitido que é de R${:.2f}.' .format(valor_parcela, valor_maximo)) else: print('Parabéns seu emprestimo foi aprovado, o valor da parcela será de: R${:.2f} reais.'.format(valor_parcela))
false
d1ce9a494bac48ded881380bfaf3ba9479f27298
deeprane1/Basics
/setexer.py
889
4.5625
5
#Sets - Exercise #1. Check if ‘Eric’ and ‘John’ exist in friends #2. combine or add the two sets #3. Find names that are in both sets #4. find names that are only in friends #5. Show only the names who only appear in one of the lists #6. Create a new cars-list without duplicates friends = {'John','Michael','Terry','Eric','Graham'} my_friends = {'Reg','Loretta','Colin','John','Graham'} cars =['900','420','V70','911','996','V90','911','911','S','328','900'] print("Eric" in friends and "John" in friends) print(friends.union(my_friends)) #OR print(friends | my_friends) print(friends.intersection(my_friends)) #OR print(friends & my_friends) print(friends.difference(my_friends)) #OR print(friends - my_friends) print(friends.symmetric_difference(my_friends)) #OR print(friends ^ my_friends) cars_no_dupl = list(set(cars)) print(cars_no_dupl)
true
de67e0e3476b1aa3783ee7081906c585f54ef152
deeprane1/Basics
/ifelexer.py
569
4.1875
4
mode = input('Enter math operation(+,-,*,/) or f for Celsius to Fahrenheit conversion: ') a = float(input('Enter first number: ')) if mode.lower() == 'f': print(f'{a} Celsius is equivalent to {(a*9/5)+32 } fahrenheit') else: b = float(input('Enter second number: ')) if mode == '+': print(f'Answer is: {a + b}') elif mode == '-': print(f'Answer is: {a - b}') elif mode == '*': print(f'Answer is: {a * b}') elif mode == '/': print(f'Answer is: {a / b}') else: print('Input error!')
false
7c0b21f3e2d15be9b90b025696abb5379ee11627
thulethi/grokking-algorithms
/python/selection_sort.py
445
4.25
4
# Sort an array from smallest to largest def find_smallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selection_sort(arr): new_arr = [] for i in range(len(arr)): smallest_index = find_smallest(arr) new_arr.append(arr.pop(smallest_index)) return new_arr print(selection_sort([3, 0, 2, 1]))
true
ad520839492f31eaf65efc14bbcb2b36c219bf02
reazwrahman/DataStructureAndAlgorithmProblems
/search and sort algorithms/selection_sort.py
1,065
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 1 17:04:56 2020 @author: Reaz selection sort algorithm Documentation: We start by assuming that the first element is the smallest one. Then we look for something smaller in the list. If we find a smaller number we swap it with our assumed value. And we do this sequentially thru the whole list. Again, like bubble sort it's not important that we have hit each element individually. The ordering will take care of itself automatically as long as we move sequentially thru the indexes """ a=[96,5,1,4,2,84,13,2,21,3] for i in range (len(a)): for j in range (i+1,len(a)): if a[j]<a[i]: temp=a[i] a[i]=a[j] a[j]=temp print (a) ''' this algorithm also works, this was my first try #for i in range (len(a)): # smallest=a[i] # for j in range (i,len(a)): # if a[j]<smallest: # smallest=a[j] # a[j]=a[i] # a[i]=smallest # print (a) # # #print (a) '''
true
0591afafec2c5e60f43e9972ecedca6a0ba5f4c2
Hieumoon/C4E_Homework
/Session05/Homework/Homework5_exercise3.py
319
4.375
4
# Write a Python function that draws a square, named draw_square, takes 2 arguments: length and color, where length is the length of its side and color is the color of its bound (line color) import turtle def draw_square(length,colorr): color(colorr) for i in range(4): forward(length) left(90)
true
05ea50b9397485c4184faa0d2deda49a799eff84
gagemm1/Machine-Learning-Experimentation
/Regression/Simple Linear Regression/your work.py
2,197
4.375
4
""" simple linear regression: y = b(0) + b(1)*x(1) just like the equation for a slope y = mx + b just keep in mind which is the dependent/independent variables """ #first we'll pre-process the data just like we did before # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) # Feature Scaling will be taken care of by the library we're using below from sklearn.linear_model import LinearRegression #create an object from the LinearRegression class regressor = LinearRegression() #fit and transform the data (taken care of by the LinearRegression class) regressor.fit(X_train, y_train) #predicting the test set results (we're creating a vector of predicted salaries) #this is where it all comes together to predict salaries for the employees, after this is just visualizing the results to get a better grip on them y_pred = regressor.predict([[1.5]]) #visualizing the training set using the matplotlib.pyplot as plt plt.scatter(X_train, y_train, color='green') plt.scatter(X_test, y_pred, color = 'red') #plt.plot makes (at least one of it's functions) a solid line #so it's plt.plot('x coordinates','y coordinates', other stuff) plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Training set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') #plt.show signifies this is the end of the graph and we want to plot/show it. It's necessary with mutiple graphs plt.show() # Visualising the Test set results, c is color plt.scatter(X_test, y_test, c = 'green',marker='^') plt.scatter(X_test,y_pred, c = 'red',marker='^') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Test set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
true
35d749186a281eb328afd537249683d56b2be334
SummerGautier/sorting-algorithms
/bubblesort.py
1,908
4.21875
4
#Description: Recursive and Iterative Bubble Sort Implementations #Author: Summer Gautier #Date: May 10th 2020 import unittest #Recursive def recursiveSort(listOfItems:list, size: int)-> list: if(size == 1): return listOfItems #do a single pass of the bubble sort algorithm for index,item in enumerate(listOfItems): #if this is the last array index, skip this iteration if(index == (len(listOfItems)-1)): continue #if the item is greater than the next, it needs to swap if(item > listOfItems[index + 1]): swapRequired = True listOfItems = swap(listOfItems, index, index + 1) return recursiveSort(listOfItems, size-1) #Iterative def iterativeSort(listOfItems: list) -> list: while(True): swapRequired: bool = False for index,item in enumerate(listOfItems): #if this is the last array index, skip this iteration if(index == (len(listOfItems)-1)): continue #if the item is greater than the next, it needs to swap if(item > listOfItems[index + 1]): swapRequired = True listOfItems = swap(listOfItems, index, index + 1) if(swapRequired == False): break return listOfItems #helper method def swap(listOfItems: list, firstIndex: int, secondIndex: int) -> list: temp: int = listOfItems[firstIndex] listOfItems[firstIndex] = listOfItems[secondIndex] listOfItems[secondIndex] = temp return listOfItems #TEST SORT METHODS class SortTest(unittest.TestCase): def test(self): sampleList: list = [7,5,28,16,9,14,25] self.assertEqual(iterativeSort(sampleList), [5,7,9,14,16,25,28]) self.assertEqual(recursiveSort(sampleList, len(sampleList)), [5,7,9,14,16,25,28]) if __name__ == '__main__': print(str(unittest.main()))
true
7a71d9c7da2476f52ca1f6070bbfb5449945ba1e
JOYFLOWERS/joyflowers.github.io
/github unit 1/Mod 5/sierra_python_module04-master orig/1_function_basics.py
1,655
4.4375
4
# Function Basics # function # A function is a named series of statements. # function definition # A function definition consists of the new function's name and a block of statements. # function call # A function call is an invocation of the function's name, causing the function's statements to execute. # def # The def keyword is used to create new functions. #Here is an example: def print_cake_area(): pi_val = 3.14159265 cake_diameter = 12.0 cake_radius = cake_diameter / 2.0 cake_area = pi_val * cake_radius * cake_radius print(str(cake_diameter) + ' inch cake is ' + str(cake_area) + ' inches squared') print_cake_area() # The function call jumps execution to the function's statements. # After the last statement, execution returns to the original location. # Check out the following example and see if you can predict/trace how the function is executed. def print_face(): face_char = 'o' print(' ', face_char, ' ', face_char) # Print eyes print(' ', face_char) # Print nose print(' ', face_char*5) # Print mouth print('Say cheese!') print_face() print('Did it turn out ok?') ###Challenge Activity 1### # print_pattern() prints 5 characters. Call print_pattern() twice to print 10 characters. Example output: #***** #***** # def print_pattern(): # print('*****') # ''' Your solution goes here ''' ###Challenge Activity 2### # Define print_shape() to print the below shape. Example output: # *** # *** # *** # ''' Your solution goes here ''' # print_shape()
true
1f61dc59136c46a693da96873504486e6a95b767
JOYFLOWERS/joyflowers.github.io
/github_unit_1/Mod_4/collz.py
797
4.5625
5
# Joy Flowers # 09/24/19 # This program shows the Collatz sequence. If the number is even, # divide it by 2 (no remainder) and if it is odd, multiply by 3 and add 1. # Also, make sure that only an integer is entered. while True: try: number = int(input('Enter number: ')) break except ValueError: #Make sure it is an integer print('Enter an integer, try again') def collatz(): #function is collatz global number #number is passed out of the function if (number % 2) == 0: #if the number is even number = number // 2 else: #if the number is odd number = number * 3 + 1 print(number) return number while number != 1: number = collatz()
true
3ff95f1a91d0cc957e4f43c1eadee7552b12bf5d
sruthinamburi/K2-Foundations
/selectionsort.py
417
4.21875
4
#sorts a list in ascending order using selection sort strategy list = [6,2,1,4,6,0] length = len(list) def selectionsort(list): for i in range (0, length-1): minval = i for j in range(i+1, length): if list[j] < list[minval]: minval = j if minval!=i: list[i],list[minval] = list[minval],list[i] selectionsort(list) print(list)
true
e7a553e8a77ddb5963c6d7e71fdaf4c7f82b42af
zhanggiene/LeetCode
/88.py
843
4.21875
4
#merge sorted array ''' the trick is to sort from behind. [1,2,3,0,0,0] sort from behind so that there will always be spaces [3,4,5] ''' class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ i=m+n-1 while(i>=0): number=0 #print(n) if n==0: #print("break") break elif m==0: number=nums2[n-1] n-=1 else: if nums1[m-1]>nums2[n-1]: number=nums1[m-1] m-=1 else: number=nums2[n-1] n-=1 nums1[i]=number i-=1 #print(nums1)
true
5011667bc901aa2fd7e45f1979f4eb0e6fd29c10
Silentsoul04/my_software_study
/SSAFY/week8_SQL,STRING/Day4/홍길동/ex.py
854
4.375
4
# 파일명 변경 금지 # 아래에 클래스 Point와 Circle을 선언하세요. class Point: def __init__(self, x, y): self.x=x self.y=y class Circle: def __init__(self,center,r): self.center=center self.r=r def get_area(self): return round(3.14*self.r*self.r,2) def get_perimeter(self): return round(3.14*2*self.r,2) def get_center(self): return (self.center.x,self.center.y) def print(self): print(f'Circle: ({self.center.x}, {self.center.y}), r: {self.r}') # 아래의 코드는 수정하지마세요. p1 = Point(0, 0) c1 = Circle(p1, 3) print(c1.get_area()) print(c1.get_perimeter()) print(c1.get_center()) c1.print() p2 = Point(4, 5) c2 = Circle(p2, 1) print(c2.get_area()) print(c2.get_perimeter()) print(c2.get_center()) c2.print()
false
e54852934ecb9d757819bbdf4fd8f46d92d36426
maydhak/project-euler
/028.py
1,258
4.25
4
""" Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ """ Logic: By drawing an 11 x 11 spiral I noticed that the numbers on the diagonals could be obtained by adding even numbers (2, 4, 6, etc) in sets of 4 (so four increases of 2, then four increases of 4, then four increases of 6, and so on). The code generates the numbers on the diagonals in this way (the largest number will be the size of the spiral, squared) and then adds all the numbers up. """ def solution28(size): # Finds the sum of the numbers on the diagonals of a size by size spiral formed by starting with 1 # and moving to the right in a clockwise direction diagonal_nums = {1} num = 1 incrementer = 2 while num < size**2: counter = 4 while counter > 0: num += incrementer diagonal_nums.add(num) counter -= 1 incrementer += 2 return sum(diagonal_nums) print(solution28(1001))
true
01257b2968f85147cc8809e6a1fd387340bd42a8
maydhak/project-euler
/009.py
1,007
4.1875
4
""" Problem 9: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ """ Before writing the solution, here is what I came up with: Known equations/inequalities: 1) a + b + c = 1000 (problem statement) 2) a^2 + b^2 = c^2 (definition of Pythagorean triplet) 3) a + b > c (definition of a triangle) 4) a < b < c (problem statement) Therefore, c = 1000-a-b, so a+b > 1000-a-b. Then 2a+2b > 1000, so a+b > 500 and c < 500. """ def solution9(): for c in reversed(range(1, 500)): # c < 500 for a in range(1, 1000-c): # the max value of a is 500 since b > 0 if a**2 + (1000-c-a)**2 == c**2: # b = (1000-c-a) since a + b + c = 1000 return a*(1000-c-a)*c, a, (1000-c-a), c # first return value is the product, followed by the values of a, b, c print(solution9())
true
8eccdb60130b928fc5639bb141425c10c6da70f9
maydhak/project-euler
/019.py
2,022
4.21875
4
""" You are given the following information, but you may prefer to do some research for yourself. - 1 Jan 1900 was a Monday. - Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? """ # Logic: determine whether or not the year is leap. We only care about the first of the month, so add the number # of days for that month. Check if that day is a Sunday (taking Sunday as the 7th day of the week, then just # check if days_sum % 7 == 0) and if so, add 1 to the sum. Repeat for all years in the 20th century. months_and_days = { "jan": 31, "feb": 28, "mar": 31, "apr": 30, "may": 31, "jun": 30, "jul": 31, "aug": 31, "sep": 30, "oct": 31, "nov": 30, "dec": 31, } def leap_year(year): leap = False if year % 100 == 0: if year % 400 == 0: leap = True elif year % 4 == 0: leap = True months_and_days['feb'] = 29 if leap else 28 return months_and_days['feb'] def solution19(): num_of_sundays = 0 year = 1900 days_sum = 1 for year in range(year, 2001): leap_year(year) for month in months_and_days: days_sum += months_and_days[month] if year == 1900: # the problem only cares about 1 Jan 1901 onwards pass elif days_sum % 7 == 0: num_of_sundays += 1 year += 1 return num_of_sundays print(solution19()) # In hindsight, because dicts are unordered, was it just luck that Python correctly iterated over the dictionary each # time? Because really, the order in which the number of days in the month are added to the sum affects whether or not # the program correctly determines if the day of the week is a Sunday.
true
fc1bdcfb3d3a14ba0c31a005ef9cc5870cbd6e7c
jhoncbox/PythonPractice
/Bootcamp/Regular Expressions -re/regularExpressions.py
2,863
4.375
4
import re # example with searching patterns using re.search() patterns = ['term1','term2'] text = 'this is a string with term1, and term1, but not the other term' for pattern in patterns: print('searching for "%s" in: \n"%s"' % (pattern, text),) # check for match if re.search(pattern, text): print("\n") print('Match was found. \n') else: print("\n") print('No Match was found. \n') match = re.search(patterns[0], text) print(match.start()) print(match.end()) # ----------------------------------------------- # RE also has a split function, e.g. split_term = '@' phrase = 'is your email jhoncbox@gmail.com?' print(re.split(split_term,phrase)) # ----------------------------------------------- # RE can be used to extrac a list of the matches print(re.findall('match','here is a match match, another match')) # and we can create a function that implement this modules. def multi_re_find(patterns,phrase): ''' takes in a list of regular patterns Prints a list of all matches ''' for pattern in patterns: print("searching the phrase using the re check: %s" % pattern) print(re.findall(pattern,phrase)) print("\n") test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd' test_patterns = [ 'sd*', # s followed by zero or more d's 'sd+', # s followed by one or more d's 'sd?', # s followed by zero or one d's 'sd{3}', # s followed by three d's 'sd{2,3}', # s followed by two to three d's ] multi_re_find(test_patterns,test_phrase) #------------------------------------------------ test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd' test_patterns = ['[sd]', # either s or d 's[sd]+'] # s followed by one or more s or d multi_re_find(test_patterns,test_phrase) # ----------------------------------------------- test_phrase = 'This is an example sentence. Lets see if we can find some letters.' test_patterns=['[a-z]+', # sequences of lower case letters '[A-Z]+', # sequences of upper case letters '[a-zA-Z]+', # sequences of lower or upper case letters '[A-Z][a-z]+'] # one upper case letter followed by lower case letters multi_re_find(test_patterns,test_phrase) # ------------------------------------------------- test_phrase = 'This is a string with some numbers 1233 and a symbol #hashtag' test_patterns=[ r'\d+', # sequence of digits r'\D+', # sequence of non-digits r'\s+', # sequence of whitespace r'\S+', # sequence of non-whitespace r'\w+', # alphanumeric characters r'\W+', # non-alphanumeric ] multi_re_find(test_patterns,test_phrase)
true
1136b377930e250ef2d9e8233e3a71e81130c9a0
nukarajusundeep/myhackerrank
/Forked_Solutions/Indeed_Prime_Codesprint/ultimate_question.py
1,670
4.46875
4
""" 42 is the answer to "The Ultimate Question of Life, The Universe, and Everything". But what The Ultimate Question really is? We may never know! Given three integers, a, b, and c, insert two operators between them so that the following equation is true: a (operator1) b (operator2) c = 42. You may only use the addition (+) and multiplication (∗) operators. You can't change the order of the variables. If a valid equation exists, print it; otherwise, print This is not the ultimate question. Input Format A single line consisting three space-separated integers: a, b, and c. Constraints: 0 <= a , b, c <= 42 Output Format: Print the equation with no whitespace between the operators and the three numbers. If there is no answer, print This is not the ultimate question. Note: It is guaranteed that there is no more than one valid equation per test case. Sample Input Example 1: 12 5 6 Example 2: 10 20 12 Example 3: 5 12 6 Sample Output Example 1: 12+5*6 Example 2: 10+20+12 Example 3: This is not the ultimate question """ import itertools import sys a, b, c = raw_input().strip().split(' ') a, b, c = [int(a),int(b),int(c)] def is_ultimate_question(x, y, z): operators = ['+', '*'] for i in itertools.combinations_with_replacement(operators, 2): expression1 = (str(x) + '%s' + str(y) + '%s' + str(z)) % (i[0], i[1]) expression2 = (str(x) + '%s' + str(y) + '%s' + str(z)) % (i[1], i[0]) if eval(expression1) == 42: return expression1 elif eval(expression2) == 42: return expression2 return "This is not the ultimate question" print is_ultimate_question(a, b, c)
true
c601f6260a9263573713d4c14c39a535da8f3d52
EasterGeorge/PythonGames
/madlibs.py
698
4.4375
4
"""" The program will first prompt the user for a series of inputs a la Mad Libs. For example, a singular noun, an adjective, etc. Then, once all the information has been inputted, the program will take that data and place them into a premade story template. You’ll need prompts for user input, and to then print out the full story at the end with the input included. """ noun = input("Noun: \n") verb_1 = input(" First verb \n") verb_2 = input(" Second Verb \n") verb_3 = input(" Third verb \n") adjective = input(" Adjective \n") print("I am a " + noun + " who " + verb_1 + " and " + verb_2 +" occassionally \n") print(" I act " + adjective + " all the time to " + verb_3 + "myself")
true
6f80000495ab222d1e73fd054f9793862992b09f
khang-le/unit4-05
/U4_05.py
729
4.25
4
#!/usr/bin/env python3 # Created by: Khang Le # Created on: Sep 2019 # This program does some calculation def main(): # comment su = 0 user_input = input("Enter how many time u want to add numbers: ") print("") # process & output try: user_number = int(user_input) for loop_counter in range(user_number): us_entered_number = int(input("Enter a number to add:")) if us_entered_number < 0: continue else: su = su + us_entered_number print("The sum of numbers are:{}".format(su)) except Exception: print("This is not an integer") if __name__ == "__main__": main()
true
b8bf4db6efd89d3b3e44af0324263683f6094b10
zsannacsengeri/Happines-calculator
/Happiness_calculator.py
2,898
4.125
4
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("This program is going to calculate your happiness!") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("You should go though 7 questions.\nPlease select 1, 2 or 3 for answer and press enter\nfor the next question.") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") q_1 = int(input("\n1. Do you want to be happy?\n\n 1: Yes, I am on my way\n 2: Too late\n 3: I do not think about happiness \n\n Your answer is: ")) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") q_2 = int(input("\n2. Do you have goals in your life?\n\n 1: I have clear goals\n 2: I am working on it\n 3: I think it is not my cup of tea \n\n Your answer is: ")) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") q_3 = int(input("\n3. Could you make more effort for better life?\n\n 1: This is what I am doing\n 2: I am looking for my way\n 3: I do not care about happiness, I do not have time for this at all \n\n Your answer is: ")) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") q_4 = int(input("\n4. Do you have hobby?\n\n 1: My hobby is my job\n 2: My hobby helps me relax\n 3: I do not have a hobby \n\n Your answer is: ")) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") q_5 = int(input("\n5. Do you believe in something?\n\n 1: I believe in myself\n 2: I believe in destiny\n 3: I do not believe nothing \n\n Your answer: ")) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") q_6 = int(input("\n6. Do you make decision on your own?\n\n 1: Easier to deal with things which I choose for myself\n 2: I do not have a choice\n 3: Let come what may \n\n Your answer is: ")) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") q_7 = int(input("\n7. Have you learnt something new recently?\n\n 1: I believe in a lifelong learning policy \n 2: I would like to, but I have not started yet\n 3: I do not like new things \n\n Your answer is: ")) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") happiness_meter = (q_1 + q_2 + q_3 + q_4 + q_5 + q_6 + q_7) if(happiness_meter <= 10): print("\nHello Sunshine, your happiness meter is", happiness_meter, ":" "'The more you give the more you receive.'") elif(happiness_meter >= 11 and happiness_meter <= 17): print("\nHello Dr. Skeptical, your happiness meter is", happiness_meter, ":" "'Fear less, love more.'") elif(happiness_meter >= 18 and happiness_meter <= 21): print("\nHello my dearest Grinch, your happiness meter is", happiness_meter, ":" "\n\n'Do not think about what might go wrong, think about what could be right.'") print("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
true
344f6de3fc5a30b875e2c016b8bb4a3680c8367b
hirenpat/Python
/problem_set_1/ps1c.py
1,240
4.1875
4
#ps1c starting_salary = float(input('Enter the starting salary: ')) saving_rate = 0 total_cost = 1000000 semi_annual_raise = 0.07 portion_down_payment = 0.25*total_cost monthly_salary = starting_salary/12 r = 0.04 number_of_months = 0 total_salary = 0 while number_of_months < 36: if number_of_months % 6 == 0: monthly_salary = monthly_salary + (monthly_salary*semi_annual_raise) total_salary = total_salary + monthly_salary number_of_months += 1 # print('Total salary: ', total_salary) # print('portion down payment: ', portion_down_payment) high = 100 low = 0 mid = int((high + low) / 2) Steps_in_bisection_search = 0 total_saving = (total_salary * (mid/100)) if total_salary < portion_down_payment: print('It is not possible to pay the down payment in three years.') else: while abs(portion_down_payment - total_saving) > 100: Steps_in_bisection_search += 1 if portion_down_payment < total_saving: high = mid else: low = mid mid = ((high + low) / 2) total_saving = (total_salary * (mid/100)) saving_rate = mid print('Steps in bisection search: ', Steps_in_bisection_search) print('Best savings rate: ', saving_rate/100)
true
16939702bb50a76028cc8a7130d0a27b81fa585a
declanohara123/Weekly-Tasks
/Integer/Interger.py
370
4.375
4
# file where if you input a number, the program halves it if it is even, but tripples itand adds one if the number is odd a = int(input("Please enter a positive integer: ")) b = int (2) print (a , end=' ') while a > 1: if a % b == 0: a /= 2 print (a, end=' ') else: a = (a * 3) + 1 print (a, end=' ') print ("Thank you")
true
2d96707effcd964401025d837e181ed5da4cfb4c
bunshue/vcs
/_4.python/test02_if_else.py
1,635
4.125
4
# for-loop while-loop if-else print("語法 : while") a = 0; story = ""; while a < 10: a = a + 1; story += "hello" + " " #print("hello") #print(""); #空白一行 print(story) print("語法 : if-else") ans = input("Are you all right? ") if ans == "Yes": print("Great") elif ans == "yes": print("Yahoo") else: print("Fine") print("語法 : input") userName = input("What is your name? ") message = input("請輸入一個訊息(輸入exit離開)") while message != "exit": print(userName + ": " + message) message = input("Enter a message: ") print("語法 : 輸入帳號密碼") id = input("請輸入帳號 : (david)") print("使用者 : "+id) password = "123" pAttempt = input("請輸入密碼 : (123)") while pAttempt != password: print("密碼錯誤") pAttempt = input("請輸入密碼 : (123)") print("密碼正確, 歡迎 " + id+ " 使用") print("語法 : 取得數字") number = int(input("請輸入一個數字 : ")) print("取得數字" + str(number)) for nn in range(number): print(nn) #print("") print("List測試"); days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for index in range(len(days)): print('index = ', str(index), ', day = ', days[index]) for letter in 'Hello Python': print('Current Letter :', letter) for letter in "Hello Python": if letter == 'h': pass #空指令 else: print('Current Letter :', letter) print("語法 : if-else") ans = input("Are you all right? ") if ans == "Yes": print("Great") elif ans == "yes": print("Yahoo") else: print("Fine")
false
272677d325e0890413ce815d4dd57a7330e272ab
bunshue/vcs
/_4.python/test00_syntax3_set.py
2,385
4.21875
4
set1 = {"green", "red", "blue", "red"} # Create a set print(set1) set2 = set([7, 1, 2, 23, 2, 4, 5]) # Create a set from a list print(set2) print("Is red in set1?", "red" in set1) print("length is", len(set2)) # Use function len print("max is", max(set2)) # Use max print("min is", min(set2)) # Use min print("sum is", sum(set2)) # Use sum set3 = set1 | {"green", "yellow"} # Set union print(set3) set3 = set1 - {"green", "yellow"} # Set difference print(set3) set3 = set1 & {"green", "yellow"} # Set intersection print(set3) set3 = set1 ^ {"green", "yellow"} # Set exclusive or print(set3) list1 = list(set2) # Obtain a list from a set print(set1 == {"green", "red", "blue"}) # Compare two sets set1.add("yellow") print(set1) set1.remove("yellow") print(set1) import random import time print('set 和 list 速度比較') NUMBER_OF_ELEMENTS = 50000 # Create a list lst = list(range(NUMBER_OF_ELEMENTS)) random.shuffle(lst) # Create a set from the list s = set(lst) # Test if an element is in the set startTime = time.time() # Get start time for i in range(NUMBER_OF_ELEMENTS): i in s endTime = time.time() # Get end time runTime = int((endTime - startTime) * 1000) # Get test time print("To test if", NUMBER_OF_ELEMENTS, "elements are in the set\n", "The runtime is", runTime, "milliseconds") # Test if an element is in the list startTime = time.time() # Get start time for i in range(NUMBER_OF_ELEMENTS): i in lst endTime = time.time() # Get end time runTime = int((endTime - startTime) * 1000) # Get test time print("\nTo test if", NUMBER_OF_ELEMENTS, "elements are in the list\n", "The runtime is", runTime, "milliseconds") # Remove elements from a set one at a time startTime = time.time() # Get start time for i in range(NUMBER_OF_ELEMENTS): s.remove(i) endTime = time.time() # Get end time runTime = int((endTime - startTime) * 1000) # Get test time print("\nTo remove", NUMBER_OF_ELEMENTS, "elements from the set\n", "The runtime is", runTime, "milliseconds") # Remove elements from a list one at a time startTime = time.time() # Get start time for i in range(NUMBER_OF_ELEMENTS): lst.remove(i) endTime = time.time() # Get end time runTime = int((endTime - startTime) * 1000) # Get test time print("\nTo remove", NUMBER_OF_ELEMENTS, "elements from the list\n", "The runtime is", runTime, "milliseconds")
true
87b85139e726c696a6ba31f6f48f45d59cbfd9b1
bunshue/vcs
/_4.python/_example/word_count/CountOccurrenceOfWordsFromFile.py
1,111
4.125
4
print('統計英文單詞出現的次數') # Count each word in the line def processLine(line, wordCounts): line = replacePunctuations(line) # Replace punctuations with space words = line.split() # Get words from each line for word in words: if word in wordCounts: wordCounts[word] += 1 else: wordCounts[word] = 1 # Replace punctuations in the line with space def replacePunctuations(line): for ch in line: if ch in '~@#$%^&*()_-+=~"<>?/,.;!{}[]|': line = line.replace(ch, " ") return line filename = 'C:/_git/vcs/_1.data/______test_files1/wordCounts1.txt' infile = open(filename, "r") # Open the file wordCounts = {} # Create an empty dictionary to count words for line in infile: processLine(line.lower(), wordCounts) #print(wordCounts) pairs = list(wordCounts.items()) # Get pairs from the dictionary items = [[x, y] for (y, x) in pairs] # Reverse pairs in the list items.sort() # Sort pairs in items for i in range(len(items) - 1, len(items) - 11, -1): print(items[i][1] + "\t" + str(items[i][0]))
true
7c8398aea4cbb08cea8b4dab14015a529b502fca
bunshue/vcs
/_4.python/__code/tkinter-complete-main/2 layout/2_4_place.py
1,506
4.25
4
import tkinter as tk from tkinter import ttk # window window = tk.Tk() window.title('Place') window.geometry('400x600') def button1_click(): print('你按了Button 1') def button2_click(): print('你按了Button 2') # widgets label1 = ttk.Label(window, text = 'Label 1', background = 'red') label2 = ttk.Label(window, text = 'Label 2', background = 'blue') label3 = ttk.Label(window, text = 'Label 3', background = 'green') button = ttk.Button(window, text = 'Button', command = button1_click) # layout label1.place(x = 300, y = 100, width = 100, height = 200) label2.place(relx = 0.2, rely = 0.1, relwidth = 0.4, relheight = 0.5) label3.place(x = 80, y = 60, width = 160, height = 300) button.place(relx = 1, rely = 1, anchor = 'se') # frame frame = ttk.Frame(window) frame_label = ttk.Label(frame, text = 'Frame label', background = 'yellow') frame_button = ttk.Button(frame, text = 'Frame Button', command = button2_click) # frame layout frame.place(relx = 0, rely = 0, relwidth = 0.3, relheight = 1) frame_label.place(relx = 0, rely = 0, relwidth = 1, relheight = 0.5) frame_button.place(relx = 0, rely = 0.5, relwidth = 1, relheight = 0.5) # exercise # create a label and place it right in the center of the window # the label should be half as wide as the window and be 200px tall exercise_label = ttk.Label(window, text = 'exercise label', background = 'orange') exercise_label.place(x = 200, rely = 0.5, anchor = 'center', relwidth = 0.5, height = 200) # run window.mainloop()
true
83d4e602122ee0e6739c0cf7da40f4be20d9987d
bunshue/vcs
/_4.python/__old/turtle/turtle05.py
1,618
4.1875
4
import turtle def drawShape(sides, length): #畫多邊形 angle = 360.0 / sides for side in range(sides): turtle.forward(length) turtle.right(angle) def moveTurtle(x, y): turtle.penup() turtle.goto(x, y) turtle.pendown() def drawSquare(length): #畫正方形 drawShape(4, length) def drawTriangle(length): #畫三角形 drawShape(3, length) def drawCircle(length): #畫圓形 drawShape(360, length) turtle.forward(100) #直走100步 turtle.right(90) #右轉90度 turtle.forward(50) #直走50步 turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(50) turtle.right(90) repeats = 0 while repeats < 360: #走一步轉一度 turtle.forward(1) turtle.right(1) repeats = repeats + 1 length = 0 angle = 90 while length < 200: turtle.forward(length) turtle.left(angle) length = length + 10 #sides = int(input("Enter the number of sides for your shape: ")) #畫八邊形 sides = 8 angle = 360.0 / sides length = 400.0 / sides for side in range(sides): turtle.forward(length) turtle.right(angle) #turtle.done() #最後再用 moveTurtle(160, 0) #畫實心八邊形 sides = 8 angle = 360.0 / sides length = 400.0 / sides turtle.fillcolor("red") turtle.begin_fill() for side in range(sides): turtle.forward(length) turtle.right(angle) turtle.end_fill() #turtle.done() #最後再用 drawShape(4, 10) moveTurtle(60, 30) drawShape(3, 20) drawShape(4, 10) drawSquare(30) drawCircle(1) drawCircle(2) drawTriangle(60) turtle.done() #最後用
true
30807fcce80097c000a86deebc2e42d7cd8be82a
ramoso5628/CTI110
/P5T2_ FeetToInches_OctavioRamos.py
550
4.3125
4
# Feet to Inches # 9 July 2019 # CTI-110 P55T2- Feet to Inches # Octavio Ramos # One foot equals 12 inches. # Write a program that will take a number of feet as an arguement and returns the number in inches # The user will be prompted to add the number in feet and the result will display in inches. inches_per_foot = 12 def main(): feet = int(input("Enter a number of feet: ")) print(feet, "equals to", feet_to_inches(feet), "inches.") def feet_to_inches(feet): return feet * inches_per_foot main()
true
73dead08d7bb52ea1630d57635be2cafc51b3102
anyuhanfei/anyuhanfei-python-study
/other/python进阶实例/类与对象/派生内置不可变类型.py
902
4.28125
4
''' 派生内置不可变类型并修改其实例化行为 ''' ''' 定义一种新类型的元组,对于传入的迭代对象,只保留int类型且值大于0的元素 要求IntTiple是内置tuple的子类. tuple元组是__new__()魔法方法创建出来的,所以在__init__()魔法方法执行时,这个元组已经完成了创建 ''' class IntTuple(tuple): ''' 新类型的元组,对于传入的迭代对象,只保留int类型且值大于0的元素 ''' def __new__(cls, iterable): ''' 最先执行,筛选数据并创建元组 ''' g = (x for x in iterable if isinstance(x, int) and x > 0) return super(IntTuple, cls).__new__(cls, g) def __init__(self, iterable): ''' 调用父类init方法 ''' super(IntTuple, self).__init__() if __name__ == '__main__': t = IntTuple([1, -1, 3, 5, ('a', 'b'), 'c']) print(t)
false
d3c7854ad3340fe0e0f36ed75101931c2d5c6e3f
anyuhanfei/anyuhanfei-python-study
/other/python进阶实例/数据结构/元组元素命名.py
912
4.3125
4
''' 为元组中的每个元素命名,提高程序可读性 ''' ''' 学生信息系统中数据为固定格式:(名字,年龄,性别,邮箱地址) 学生数量很大,为了减少存储开销,对每个学生信息用元组表示 访问时,使用序列索引(index)访问,大量序列索引降低程序可读性,如何解决? ''' student = ('Jim', 18, 'male', '1234567@qq.com') ''' 方法1:定义常量,常量赋值为这些序列索引值(类似其他语言的枚举类型) ''' NAME, AGE, SEX, EMAIL = range(4) print(student[AGE]) # student[1] ''' 方法2:使用标准库中collections.namedtuple代替内置tuple ''' from collections import namedtuple s_tuple = namedtuple('student', ['name', 'age', 'sex', 'email']) # 参数:元组名称,序列对应的元素名 student = s_tuple(name='Jim', age=16, sex='male', email='1234567@qq.com') print(student.name)
false
3603e8d09abd206f6466342826bdf1a9a31505f9
sulaiman666/Learning
/Language/Python/Input_Name.py
304
4.375
4
name = input("Enter your name: ") # If you want to take input from user you can use input function age = int(input("Enter your age: ")) # If you want a specific type of input from user you need to declare input fucntion as an integer print("Your name is:", name) print("Your age is:", age, "years old")
true
bacc9c68453826669e10d5a78270b9067996ccec
BramWarrick/Movie_Database
/media.py
1,284
4.375
4
# Lesson 3.4: Make Classes # Mini-Project: Movies Website # In this file, you will define the class Movie. You could do this # directly in entertainment_center.py but many developers keep their # class definitions separate from the rest of their code. This also # gives you practice importing Python files. import webbrowser class Movie(): """ This class provides a way to store movie related information""" def __init__(self, movie_title, movie_storyline, poster_image_url, trailer_youtube_url, release_year): """Initialize instance of class Movie Args: movie_title: Title of movie for instance of class movie_storyline: Brief summary of plot poster_image_url: location for image, refcatored to be local trailer_youtube_url: url for the movie's official trailer release_year: year of the movie's release in the United States """ self.title = movie_title self.storyline = movie_storyline self.poster_image_url = poster_image_url self.trailer_youtube_url = trailer_youtube_url self.release_year = release_year def show_trailer(self): """Opens movie's youtube trailer in web browser""" webbrowser.open(self.trailer_youtube_url)
true
7fcb3486f0cf81f8bd5634494af8c86b3f8eb7f5
Sakshi2000-hash/Python-Dictionary
/UI.py
2,009
4.1875
4
import tkinter from tkinter import * from tkinter import messagebox import json data = json.load(open("data.json")) window = Tk() window.title("Find Your Words Here!") def search(): val = word_value.get() val = val.lower() if val in data: display_text.insert(END,data[val]) word = val.capitalize() messagebox.showinfo("Meaning of "+word+": ",data[val]) print(data[val]) elif val == "": messagebox.showwarning("Warning","Enter word") elif val == " ": messagebox.showerror("Warning","You entered no word") else: display_text.insert(END,"This mini dictionary has no word like you want. AS you Entered wrong word ") messagebox.showerror("Warning","This mini dictionary has no word like you want . AS you Entered wrong want") display_text.delete("1.0", "end") window.geometry('300x500') window.configure(background = "green yellow") head = Label(window ,text = "MINI DICTIONARY",bg = "black",fg = "green yellow",height = 4,width = 400,pady= 0,font = ("bold",16)) #for displaying the message head.place(relx=0.5, rely=0.1,anchor=CENTER) word = Label(window,text = "Enter the word you want the meaning off:",bg = "green yellow",font = ("bold",12)) word.place(relx = 0.5,rely = 0.3,anchor=CENTER) word_value = Entry(window,width = 30) word_value.place(relx = 0.5,rely = 0.37,anchor = CENTER) #this is the button which will search the value search = Button(window ,text="Search",bg = "black",fg = "green yellow",padx = 6 ,pady =3 ,width= 13,command=search) #submit button search.place(relx=0.5,rely=0.5,anchor=CENTER) display=Label(window,text = "Your Word Means ",fg = "black",bg = "green yellow",font = ("bold",12)) display.place(relx = 0.5,rely = 0.74,anchor = CENTER) display_text = Text(window,height = 6,width=38,bg = "black",fg = "green yellow",font = ("bold",11)) display_text.place(relx = 0.5,rely = 0.9,anchor = CENTER) window.mainloop()
true
759e1a1dfc6292b7a431ed7b0d17facf1dd592bd
yamendrasinganjude/200244525045_ybs
/day2/ConsecutiveNumSumRowWise.py
234
4.28125
4
''' 1 3 5 7 9 13 ... so on consecutive odd numbers suppose user gives row 2 then 3 + 5 = 8 so 8 is output ''' def row_wise_sum(num): return num ** 3 num = int(input("Enter a Num: ")) print("Sum is ",row_wise_sum(num))
false
d2122d9b06ae294a210c17cd9fdb01a924931855
yamendrasinganjude/200244525045_ybs
/day1.1/kidsAgeCheckAllowedOrNot.py
245
4.1875
4
''' its simple kids school eg: if kids between 8 to 12 then they are allowed otherwise not allowed ''' num = int(input("enter ur age:")) if num >= 8 and num <= 12: print("Welcome, U r allowed....") else: print("U r not allowed....")
true
9b231303febda81772454967e97fa2d156d3dd60
yamendrasinganjude/200244525045_ybs
/day8/LambdaSquCube.py
330
4.25
4
''' 5. Write a Python program to square and cube every number in a given list of integers using Lambda. ''' lst = list(map(int, input().split())) print("List :\n", lst) squareList = list(map(lambda x: x*x, lst)) print("Square Of List :\n", squareList) cubeList = list(map(lambda x: x**3, lst)) print("Cube of List :\n", cubeList)
true
4487065cbefc89779baad509f1ca5901556b3682
Ripsnorter/edX--6.00.1x-CompSci-2013
/L6_Problem_02.py
605
4.15625
4
''' L6 Problem 2 ------------ Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple'). ''' def oddTuples(aTup): i = 0 newTup = () for index in aTup: if i%2 == 0: newTup += (index,) i += 1 return newTup #Test Code oddTuples((2, 2, 15, 18, 20)) oddTuples((1, 1, 12, 0, 2, 19, 20, 18))
true
e22751d4d5f9f513b0ca93d77c1ca404f6c8447e
DrBuddyO1/UT-MCC-VIRT-DATA-PT-08-2021-U-B
/Module-3_Python_Fundamentals/1/04-Ins_List/Solved/lists.py
606
4.3125
4
# Create a variable and set it as an List myList = ["Jesse","Tarana",5] # Adds an element onto the end of a List myList.append("Matt") # Returns the index of the first object with a matching value # Changes a specified element within an List at the given index myList[0] # Returns the length of the List # Removes a specified object from an List myList.remove("Jesse") print(myList) # Removes the object at the index specified myList.pop(2) print(myList) # Creates a tuple, a sequence of immutable Python objects that cannot be changed myTuple=(1,2,"A") print(myTuple) myList[1]=0 print(myList)
true
8598d58efd83583615f0a13fd4874c6b2a43010d
Rui-FMF/FP
/Aula04/dates.py
1,923
4.28125
4
# This function checks if year is a leap year. # It is wrong: 1900 was a common year! def isLeapYear(year): return (year%4 == 0 and year%100 != 0 ) or (year%100 == 0 and year%400 == 0) # A table with the days in each month (on a common year). # For example: MONTHDAYS[3] is the number of days in March. MONTHDAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # This function has a semantic error: February in a leap year should return 29! # Correct it. def monthDays(year, month): if (isLeapYear(year) and month == 2): days = 29 return days else: days = MONTHDAYS[month] return days # This is wrong, too. def nextDay(year, month, day): if day == monthDays(year, month): if month == 12: day = 1 month = 1 year += 1 return year, month, day else: day = 1 month += 1 return year, month, day else: day += 1 return year, month, day # This is the main function def main(): print("Was", 2017, "a leap year?", isLeapYear(2017)) # False? print("Was", 2016, "a leap year?", isLeapYear(2016)) # True? print("Was", 2000, "a leap year?", isLeapYear(2000)) # True? print("Was", 1900, "a leap year?", isLeapYear(1900)) # False? print("January 2017 had", monthDays(2017, 1), "days") # 31? print("February 2017 had", monthDays(2017, 2), "days") # 28? print("February 2016 had", monthDays(2016, 2), "days") # 29? print("February 2000 had", monthDays(2000, 2), "days") # 29? print("February 1900 had", monthDays(1900, 2), "days") # 28? y, m, d = nextDay(2017, 1, 30) print(y, m, d) # 2017 1 31 ? y, m, d = nextDay(2017, 1, 31) print(y, m, d) # 2017 2 1 ? y, m, d = nextDay(2017, 2, 28) print(y, m, d) # 2017 3 1 ? y, m, d = nextDay(2016, 2, 29) print(y, m, d) # 2016 3 1 ? y, m, d = nextDay(2017, 12, 31) print(y, m, d) # 2018 1 1 ? # call the main function main()
true
d7ef5d90def8eb0115963445368c515dd142587c
Rui-FMF/FP
/AulaX/twitter.py
841
4.15625
4
# Este programa demonstra a leitura e utilização de dados de um ficheiro JSON # com mensagens do Twitter. # Modifique-o para resolver o problema proposto. # O módulo json permite descodificar ficheiros no formato JSON. # São ficheiros de texto que armazenam objetos compostos que podem incluir # números, strings, listas e/ou dicionários. import json # Abre o ficheiro e descodifica-o criando o objeto twits. with open("twitter.json", encoding="utf8") as f: twits = json.load(f) print(type(twits)) # deve indicar que é uma lista! print(type(twits[0])) # cada elemento da lista é um dicionário. print(twits[0].keys()) # mostra as chaves no primeiro elemento. # Cada elemento contém uma mensagem associada à chave "text": print(twits[0]["text"]) # Algumas mensagens contêm hashtags: print(twits[880]["text"])
false
d30e421050f8d9b28da2626d1eb51929d0baca53
jayala-29/python-challenges
/advCalc2.py
2,832
4.15625
4
# function descriptor: advCalc2() # advanced calculator that supports addition, subtraction, multiplication, and division # note: input from user does NOT use spaces # part 2 of building PEMDAS-based calculator # this represents parsing an expression as an algorithm # for operations in general, we go "left to right" # multiplication and division will come first # then the addition and subtraction # the example should be parsed as follows: # 1+2*3*4-25/5 <- input # 1+6*4-25/5 # 1+24-25/5 # 1+24-5 # 25-5 # 20 <- output # return type: nothing; program should end when the user types 'n' # example: Please enter an expression to calculate: '1+2*3*4-25/5' # Okay, the output is 20 # Do you want to calculate anything else? [y|n] 'n' # Okay, bye bye :) # you should start by pasting what you have from part 1 def advCalc2(): while True: expression = input("Please enter and expression to calculate: ") ls = [] numLs = [] oprLs = [] current = 0 lastNum = [] for item in expression: ls.append(item) for i in range(len(ls)): if(ls[i] == "+" or ls[i] == "-" or ls[i] == "*" or ls[i] == "/"): oprLs.append(ls[i]) num = [] lastOpr = i for j in range(current,i): num.append(ls[j]) numLs.append("".join(num)) current = i+1 for i in range(lastOpr+1, len(ls)): lastNum.append(ls[i]) numLs.append("".join(lastNum)) while True: for i in range(len(oprLs)): if(oprLs[i] == "+" or oprLs[i] == "-"): continue if(oprLs[i] == "*"): newNum = mult(int(numLs[i]), int(numLs[i+1])) if(oprLs[i] == "/"): newNum = div(int(numLs[i]), int(numLs[i+1])) oprLs.pop(i) numLs.pop(i+1) numLs.pop(i) numLs.insert(i, newNum) break check = 0 for i in range(len(oprLs)): if(oprLs[i] == "+" or oprLs[i] == "-"): check += 1 if(check == len(oprLs)): break while True: for i in range(len(oprLs)): if(oprLs[i] == "+"): newNum = add(int(numLs[i]), int(numLs[i+1])) if(oprLs[i] == "-"): newNum = sub(int(numLs[i]), int(numLs[i+1])) oprLs.pop(i) numLs.pop(i+1) numLs.pop(i) numLs.insert(i, newNum) break if(len(oprLs) == 0): break print("Okay, the output is " + str(numLs[0])) more = input("Do you want to calculate anything else? [y|n] ") if(more == "n"): print("Okay, bye bye :)") break return def add(a,b): return a + b def sub(a,b): return a - b def mult(a,b): return a * b def div(a,b): return a / b advCalc2()
true
80b5f2c9d94be3af52a17ceab18881721189aa39
clc80/cs-module-project-iterative-sorting
/src/searching/searching.py
1,237
4.34375
4
def linear_search(arr, target): # Your code here for i in range(len(arr)): if target == arr[i]: return i return -1 # not found # Write an iterative implementation of Binary Search def binary_search(arr, target): # Your code here first = 0 last = (len(arr) - 1) found = False while first <= last and not found: middle = (first + last) // 2 # print(f"The middle is {middle}") # check to see if item is the middle target # print(f"The middle is {arr[middle]} and the target is {target}") if target == arr[middle]: # print("found value") found = True return middle # else check to see if the number is smaller or larger and repeat else: # print("Target not found so going through the else ") if target < arr[middle]: # if smaller change the last number to be the middle last = middle - 1 # print("changed last") else: first = middle + 1 # print("changed first") return -1 arr1 = [-9, -8, -6, -4, -3, -2, 0, 1, 2, 3, 5, 7, 8, 9] binary_search(arr1, -8)
true
527b524f5cc2cea6f5bd02f801e5d22328e9ea48
arpit-omprakash/CipherX
/cipherx/__main__.py
2,922
4.25
4
doc_string = """ Encrypt or Decrypt a provided file. The program takes in one file as an input, encrypts (or decrypts) it and saves the output as another file. ----------------------------------------------- The following cipher options are supported till now: 1 = Caesar Cipher 2 = ROT 13 Cipher ----------------------------------------------- """ # Argument Parsing def parsing(): """Function to parse inputs. Returns -------- Namespace A Namespace object containing all the inputs passed to the program. """ import argparse parser = argparse.ArgumentParser(prog='cipherx', formatter_class=argparse.RawDescriptionHelpFormatter, description=doc_string) parser.add_argument('-cipher', '-c', default='1', type=int, choices=range(1,3), help='Cipher to use for encryption or decryption (default = 1)') parser.add_argument('-decrypt', '-d', action='store_true', help='Turn this flag on to enter decrypt mode') parser.add_argument('-shift', '-s', default=3, type=int, choices=range(1, 37), help='The shift for Caesar Cipher, can range from 1 to 36 (default = 3)') parser.add_argument('in_file', type=argparse.FileType('r', encoding='UTF-8'), help='Path to input file', metavar='I') parser.add_argument('out_file', type=argparse.FileType('w', encoding='UTF-8'), help='Path to output file (file is created if not existing)', metavar='O') return parser.parse_args() def apply_cipher(func): """Function to apply a supplied cipher function. The function works with strings explicitly. Should be invoked using functions that work with strings. The text is read from the earlier provided input file. The output is written to the provided output file. Parameters ----------- func : function An encryption or decryption function """ text = args.in_file.read() changed_text = func(text) args.out_file.write(changed_text) def apply_caesar_cipher(shft): """Function to apply the Caesar Cipher. Parameters ----------- shft : int The shift for Caesar Cipher """ from cipherx.ciphers.caesar_cipher import CaesarCipher c = CaesarCipher(shft) if args.decrypt: apply_cipher(c.decrypt) else: apply_cipher(c.encrypt) # Program logic if __name__ == '__main__': args = parsing() if args.cipher == 1: apply_caesar_cipher(args.shift) elif args.cipher == 2: apply_caesar_cipher(13)
true
0a079e932af4e80b238c922685a6c154b4e7492e
aafreen22/launchpad-assignments
/pgm5.py
418
4.40625
4
# this program asks the user for a string and displays it in reverse order str = input("Enter a string:: ") list = str.split() #converts the string to a list rev = list[::-1] #reverses the list resu = "" for val in rev: resu = resu + " " + val #creates a string from the reverse of the list res = resu[1::] #removes first character as it is a space print(res.capitalize()) #capitalizes the first letter of the string
true
e73be53c5870878ab396263b03b34d3c76d8c556
suku19/python-associate-example
/module/random_module.py
2,196
4.625
5
from random import random, seed ''' The most general function named random() (not to be confused with the module’s name) produces a float number x coming from the range (0.0, 1.0) –in other words: (0.0 <= x < 1.0). ''' print("random():::") for i in range(5): print(random()) ''' Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value. Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice. The seed()function is able to directly set the generator’s seed. We’ll show you two of its variants: seed() – sets the seed with the current time; seed(i) – sets the seed with the integer value i. ''' print() print("seed():::") seed(0) for i in range(5): print(random()) seed(0) for i in range(5): print(random()) ''' If you want integer random values, one of the following functions would fit better: randrange(end) randrange(beg,end) randrange(beg, end, step) randint(left, right) ''' print() print("Integer Random Value:::") from random import randrange, randint print(randrange(1), end=' ') print(randrange(0, 1000), end=' ') print(randrange(0, 1, 1), end=' ') print(randint(0, 100)) print("10 Random Int::") for i in range(10): print(randint(1, 10), end=',') ''' It’s a function named in a very suggestive way – choice: choice(sequence) -> chooses a “random” element from the input sequence and returns it. sample(sequence, elements_to_chose=1) -> builds a list (a sample) consisting of the elements_to_chose element (which defaults to 1) “drawn” from the input sequence. ''' print() print("Choice:::") from random import choice, sample lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(choice(lst)) print(sample(lst, 5)) print(sample(lst, 3))
true
b64199ff0017c04675488835f4b3a7d512d1faad
suku19/python-associate-example
/functions/function_intro.py
660
4.25
4
# Write Fibonacci series up to n def fib(n): """Print a Fibonacci series up ro n.""" a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a + b print() # Now call the function we just defined: fib(2000) def fib2(n): # return Fibonacci series up to n """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a + b return result f100 = fib2(100) # call it print(f100) # write the result def Foo(n): def multiplier(x): return x * n return multiplier
true
5e231cb48ca959af6481d2d32318446f703ebe37
suku19/python-associate-example
/classes/Inheritance/instance_method.py
2,146
4.3125
4
print("::Find the valid subclass : issubclass()::") class Vehicle: pass class LandVehicle(Vehicle): pass class TrackedVehicle(LandVehicle): pass for cl1 in [Vehicle, LandVehicle, TrackedVehicle]: for cl2 in [Vehicle, LandVehicle, TrackedVehicle]: print(issubclass(cl1, cl2), end='\t') print() print() print("::Find the valid instance : isinstance()::") vehicle = Vehicle() landvehicle = LandVehicle() trackedvehicle = TrackedVehicle() for ob in [vehicle, landvehicle, trackedvehicle]: for cl in [Vehicle, LandVehicle, TrackedVehicle]: print(isinstance(ob, cl), end='\t') print() print() print("::is operator: checks whether two variables (object1 and object2 here) refer to the same object.") print("landvehicle is vehicle : ", landvehicle is vehicle) print("vehicle is vehicle : ", vehicle is vehicle) class ThisIsClass: def __init__(self, val): self.val = val ob1 = ThisIsClass(0) ob2 = ThisIsClass(2) ob3 = ob1 ob3.val += 1 print("ob1 is ob2 :", ob1 is ob2) print("ob2 is ob3 :", ob2 is ob3) print("ob3 is ob1 :", ob3 is ob1) print("ob1.val, ob2.val, ob3.val : ", ob1.val, ob2.val, ob3.val) str1 = "Mary had a little " str2 = "Mary had a little lamb" str1 += "lamb" print("str1 == str2, str1 is str2::", str1 == str2, str1 is str2) print() print("How Python finds properties and methods?") class Super: def __init__(self, name): self.name = name def __str__(self): return "My name is " + self.name + "." class Sub(Super): def __init__(self, name): # The Sub class defines its own constructor, which invokes the one from the superclass Super.__init__(self, name) # We’ve explicitly named the superclass, and pointed to the method to invoke __init__(), providing all needed arguments. class Sub1(Super): def __init__(self, name): super().__init__(name) # super() function, accesses the superclass without needing to know its name obj = Sub("Sukanta") print(obj) obj1 = Sub1('Jhon') print(obj1)
false
d8c1a54ccafbf6e8c3edc12c7824d3e66a5972bb
ammonshepherd/learning-python
/alpha-shift.py
615
4.21875
4
# TODO: # - make it work with lowercase letters, too def alphaShift(shift): for i in range(65,91): print(chr(i), end='') print() for i in range(65, 91): z = i + shift if z > 90: print(chr(z - 26), end='') if z <= 90: print(chr(z), end='') print() def letterShift(letter, shift): z = ord(letter) + shift if z > 90: L = chr(z - 26) if z <= 90: L = chr(z) return L if __name__ == "__main__": print("Shift alphabet by 13") alphaShift(13) print("3rd letter from N is {}".format(letterShift('N', 3)) )
false
ca608aab3d7a8fc4161c7254b51356a83a3d1552
lei-hsia/LeetCode
/341.FlattenNestedList_iterator.py
1,426
4.125
4
''' This is the interface that allows for creating nestedIterator you should not implement it, or speculate about its implementation ''' class NestedIngeter(object): def isInteger(self): ''' @return True if this NestedIngeter holds a single integer, rathen than a nested list. :rtype bool ''' def getInteger(self): ''' @return the single integer tha this NestedIngeter holds if it holds a single integer Return None if this NestedIngeter holds a nested list :rtype int ''' def getList(self): ''' @return the nested list that this NestedIngeter holds, if it holds a nested list Return None if this NestedIngeter holds a single integer :rtype List[NestedIngeter] ''' # 下面是真正我们要写的 class nestedIterator(object): def __init__(self, nestedList): ''' Initialize your data structure here :type nestedList: List[NestedIngeter] ''' self.stack = nestedList[::] def next(self): ''' :rtype: int ''' return self.stack.pop(0).getInteger() def hasNext(object): ''' :rtype: bool ''' while self.stack: top = self.stack[0] if top.isInteger(): return True self.stack = top.getList() + self.stack[1:] return False
true
0294a624b7a356f40544aafdfce80e1300b1876e
asheemchhetri/pythonClass
/Section 1/zip.py
875
4.71875
5
# >>> Zip: We use zip to combine multiple iterables into a single iterator, which is very helpful when we iterate through in a loop by expansion. # Returns a list of tuple # Note: Iterators can only be use ONCE, to save memory by only generating the iterators as we need them, rahter storing them in memory country = ['India', 'USA', 'China', 'Japan'] gdp = ['$2.72 trillion', '$20.49 trillion', '$13.41 trillion', '$4.97 trillion'] data = zip(country, gdp) # print(list(data)) for name, nominal in data: print('{} has a nominal GDP of {}'.format(name, nominal)) # How to unzip a sequence # To use the above zipped data, we need to comment out the for loop, as after for loop the iterable is cleared out and unzip command will get 0 values to unpack while it is expecting 2 # country_unzipped, gdp_unzipped = zip(*data) # print(country_unzipped) # print(gdp_unzipped)
true
f420a0c862dc51af92029904ff52f55734c9a439
Chupalika/Kaleo
/tools/integersearch.py
1,350
4.21875
4
#!/usr/bin/python #This tool searches for an integer value in a binary file by converting both to binary and comparing substrings of the binary file to the target binary #Argument 1: binary file name #Argument 2: target integer value from __future__ import division import sys #Converting a byte to binary apparently strips off the 0's at the front. This fills the string with 0's back up to length 8. def fillgapsinbinary(str): ans = str while len(ans) != 8: ans = "0" + ans return ans #generate an entire string of binary from string data def generatebinary(snippet): lines = [] for x in snippet: lines.append(fillgapsinbinary(format(ord(x), 'b'))) string = "" ugh = range(len(lines)) ugh.reverse() for i in ugh: string += lines[i] return string #read files, generate binary string file = open(sys.argv[1]) filecontents = file.read() binary = generatebinary(filecontents) #convert target integer to binary target = int(sys.argv[2]) targetbinary = "{0:b}".format(target) targetlength = len(targetbinary) #search for target binary in string binary and print any matches! for i in range(len(binary) - targetlength + 1): snippet = binary[len(binary)-i-targetlength:len(binary)-i] if snippet == targetbinary: print("Match found at byte {} bit {}".format(i//8, i%8))
true
7c98cf3aeb49691a438392fe1f24da5bb23846f3
satishhirugadge/BOOTCAMP_DAY11-12
/Task1_Question4.py
316
4.34375
4
# 4. Write a program to print the value given # by the user by using both Python 2.x and Python 3.x Version. user1=input("Hey, What is your name???") print(user1) age1=int(input("What is your age???")) print(age1) # way to run on the python 2. # user2=raw_input("Hey, What is your name???") # print(user1)
true
f75d793ce584968faf5e83be54ef74398a557516
IvanovskyOrtega/project-euler-solutions
/solutions/004_largest_palindrome_product.py
1,414
4.34375
4
"""Solution to Project Euler Problem 4.""" def is_palindrome(n: int) -> bool: """is_palindrome. This function determines if a given integer number is a palindrome or not. Arguments --------- n : int The number to check if is palindrome. Returns ------- bool : `True` if is palindrome, `False` otherwise. """ n_str = str(n) str_len = len(n_str) i = 0 while i < str_len // 2: if n_str[i] != n_str[str_len - i - 1]: return False i += 1 return True def largest_palindrome_product(n_digits: int) -> int: """largest_palindrome_product. This function returns the largest palindrome product of two n-digit numbers. Arguments --------- The number of digits for the numbers. Returns ------- int : The largest palindrome Examples -------- >>> largest_palindrome_product(3) 906609 """ res = 0 lower_bound = 10 ** (n_digits - 1) upper_bound = 10 ** n_digits j = lower_bound it = 1 for i in range(lower_bound, upper_bound): while j < upper_bound: n = i * j if is_palindrome(n): res = n if n > res else res j += 1 j = lower_bound + it # Avoid to re-compute previous cases it += 1 return res if __name__ == "__main__": print(largest_palindrome_product(3))
true
1624640bce16514ef264e08d3e8e61d91565b199
Heladitooo/challenges-Python
/challenge2/oddIndexs.py
829
4.1875
4
""" RETO 2: Diseña un programa que elimine de una lista todos los elementos de índice par y muestre por pantalla el resultado. (Ejemplo: si trabaja con la lista [1,2,1,5,0,3], ésta pasará a ser [2,5,3].) """ def oddIndexs(array): #saca los índices impares, o sea no el número si no la posición en la que esta el número oddArray = [] for i in range(len(array)): if i % 2 == 0: #si el residuo al dividirlo entre 2 es 0, es par continue else: oddArray.append(array[i]) return oddArray def main(): array = [1,2,1,5,0,3] #el array en el que quieres sacar los índices impares oddArray = oddIndexs(array) print("\n\n the new array with odd indexs is: {} \n" .format(oddArray)) if __name__ == "__main__": main()
false
54cbc490ae7023113e2692f86ba55c45e15f7fc6
Mahendra522/4Fire
/python/printInReverse.py
367
4.5
4
# Python program to print elements in the Reverse order array = [0]*30 n = 0 n = int(input("Enter number of elements you wanted to insert: ")) print("\n") print("Enter each number one by one: \n") for i in range(n): array[i] = int(input()) print("Printing Elements in the reverse order: \n") for i in reversed(range(n)): print(array[i],end="\n")
true
9d59fc835a3bf9bdb7c16f90e953a3e75974734d
Cjeb24/CreditCardCheck
/creditcardcheck.py
1,741
4.15625
4
#credit card validation program number = [] creditCard=str(input("please enter your credit card number(13-16 digits):")) number.append(creditCard) sumEven = 0 sumodd = 0 # Return True if the card number is valid def isValid(number): sumOfDoubleEvenPlace(number) sumOfOddPlace(number) prefixMatched(number) if ((sumEven + sumodd)%10) == 0: print("Your credit card is valid") else: print("Your Credit card is not valid") # Get the result from Step (b) def sumOfDoubleEvenPlace(number): sumEven = 0 position = len(number) - 2 while position >= 0: Value = digitsum(int(number[position] * 2)) if Value > 9: getDigit() position = position - 2 sumEven += sumEven else: sumEven = sumEven + Value return sumEven # Return this number if it is a single digit, otherwise, return # the sum of the two digits def getDigit(number): Value2 = digitsum(int(number[position] + 2)) sumEven = sumEven + Value2 return sumEven # Return sum of odd place digits in number def sumOfOddPlace(number): sumodd = 0 position = len(number) - 1 while position >= 0: sumodd = sumodd + int(number[position]) position = position - 2 # Return True if the digit d is a prefix for number def prefixMatched(number): if number[0] == "6": print("Your card type is Discover Card") elif number[0] == "5": print("Your card type is Master card") elif number[0] == "4": print("Your card type is visa") elif number[0] == "3" and number[1] == "7": print("Your card type is American express") isValid(number)
true
fea36651929c097b6376e4476b499d1f430ca623
RebeccaML/Practice
/Python/Games/rockPaperScissors.py
1,041
4.34375
4
# Project from https://www.udemy.com/the-modern-python3-bootcamp/ # Two player version print("Let's play 'Rock, Paper, Scissors!'") player1_choice = input("Enter Player 1's choice: ") player2_choice = input("Enter Player 2's choice: ") if player1_choice == player2_choice: print(f"Both players chose {player1_choice}. It's a tie!") elif player1_choice == "rock": if player2_choice == "paper": print("Paper covers rock. Player 2 wins!") elif player2_choice == "scissors": print("Rock crushes scissors. Player 1 wins!") elif player1_choice == "paper": if player2_choice == "scissors": print("Scissors cut paper. Player 2 wins!") elif player2_choice == "rock": print("Paper covers rock. Player 1 wins!") elif player1_choice == "scissors": if player2_choice == "rock": print("Rock crushes scissors. Player 2 wins!") elif player2_choice == "paper": print("Scissors cut paper. Player 1 wins!") else: print("Valid inputs: rock, paper, scissors. Please try again.")
true
2ab46ba034d31a084a49779826c88f9adde76c21
RebeccaML/Practice
/Python/Basic/regex.py
1,019
4.1875
4
# Exercise from https://www.udemy.com/the-modern-python3-bootcamp/ import re def extract_phone(input): phone_regex = re.compile(r"\d{3} \d{3}-\d{4}\b") match = phone_regex.search(input) if match: return match.group() else: return None def extract_all_phones(input): phone_regex = re.compile(r"\b\d{3} \d{3}-\d{4}\b") match = phone_regex.findall(input) if match: return match else: return None # print(extract_phone("my number is 836 925-9582")) # print(extract_phone("my number is 4535 44 545-23")) print(extract_all_phones("my number is 836 925-9582 or call me at 344 777-2374")) print(extract_phone("my number is 4535 44 545-23")) def is_valid_phone(input): phone_regex = re.compile(r"^\d{3} \d{3}-\d{4}$") match = phone_regex.search(input) if match: return match.group() else: return None print(is_valid_phone("464 987-2868")) print(is_valid_phone("457 812-9745 dfd")) print(is_valid_phone("asd 848 111-8453 d"))
false
c123931ce12e35f08c0a0de438f63521c407d6f7
RebeccaML/Practice
/Python/Basic/addingReport.py
1,133
4.1875
4
# Create a function to add numbers input by the user. # Accepts one argument which determines whether numbers and total are printed ("A") # or just the total is printed ("T") # Exits the function and displays output once user enters Q to quit # Call twice; once using "A" and once using "T" # This would be better if the user chooses whether they want "A" or "T" but as is, # this was the assignment. # Final project for an edX course def adding_report(report_type = "T"): total = 0 items = "" while True: user_input = input("Input an integer to add to the total or \"Q\" to quit: ") if user_input.isdigit() == True: total += int(user_input) if report_type.upper() == "A": items = items + user_input + "\n" elif user_input.upper().startswith("Q"): if report_type.upper() == "A": print("Items\n" + items + "\nTotal\n" + str(total)) break else: print("Total\n" + str(total)) break else: print("Invalid input.") adding_report("A") adding_report("T")
true
ac18a69c5373de6eb081f5d0090d72a8d1f4fa8d
qanm237/q_assessment
/question2.py
310
4.34375
4
def lastele(n): return n[-1] #find the last element def sort (tuples): return sorted(tuples, key=lastele)#sort with key stated as based on last element lt=input("enter the list of tuple: ") #input of tuples in a list print("the sorted list of tuple is :") #output print(sort(lt))
true
7c84e6e89a805b58125905b65148432c6e189677
kagomesakura/numBob
/numBob.py
280
4.15625
4
#print how many times the word bob occurs in string s = 'azcbobobegghakl' numBob = 0 for i in range(len(s)): if s[i:i+3] == "bob": # [i:i+3] checks the current char + the next three chars. numBob += 1 print ('Number of times bob occurs is: ' + str(numBob))
true
75a3c18ef6236bb8044af7e04914a22004d9697b
MinhowS/py
/study/1.求一个整数的绝对值.py
336
4.21875
4
# print absolute value of an integer # 求一个整数的绝对值 # 以#开头的语句是注释,注释是给人看的,可以是任意内容, # 解释器会忽略掉注释。其他每一行都是一个语句, # 当语句以冒号:结尾时,缩进的语句视为代码块。 a = -50 if a>= 0: print(a) else: print(-a)
false
d3e9ca28d8c7bfb6c93c3580ed3dffd5f0f6cabd
edubs/lpthw
/ex03.py
1,216
4.65625
5
# Study drills # 1 above each line, user the # to write a comment to yourself explaining what the line does # 2 remember in exercise 0 when you started python3.6? start python3.6 this way again and using the math operators, use python as a calculator # 3 find something you need to calculate and write a new .py file that does it # 4 rewrite ex3.py to use floating point numbers so it's more accurate. 20.0 is floating point print("I will now count my chickens:") # divides 30 by 6 (5) then adds 25 resulting in 30.0 print("Hens", 25.0 + 30.0 / 6.0) # 100 - 3 = 97 # 25 by 3 (75) then mods 4 resulting 3, the amount from 75 leftover after 18*4 (72) print("Roosters", 100.0 - 25.0 * 3.0 % 4.0) # gratuitous order of operations exercise print("Now I will count the eggs:") print(3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0) print("Is it true that 3.0 + 2.0 < 5.0 - 7.0?") print(3.0 + 2.0 < 5.0 - 7.0) print("What is 3.0 + 2.0?", 3.0 + 2.0) print("What is 5.0 - 7.0?", 5.0 - 7.0) print("Oh, that's why it's False.") print("How about some more.") print("Is it greater?", 5.0 > -2.0) print("is it greater or equal?", 5.0 >= -2.0) print("is it less or equal?", 5.0 <= -2.0)
true
28d3a98bb4676d39a73d6f5e522b35650d8bd6f1
bji6/Practice_Problems
/Cracking_Coding_Interview/Moderate/factorialZeros.py
523
4.15625
4
#ben isenberg 10/23/2016 #a function that finds number of trailing zeros in n factorial def factorialZeros(n): temp = n #compute n factorial for i in range(1,temp): n = n * (temp-i) #find number of trailing zeros trailingCount = 0 divisor = 10 #print(n) while (n % divisor == 0): trailingCount = trailingCount + 1 divisor = divisor * 10 return trailingCount def main(): print(factorialZeros(3)) print(factorialZeros(5)) print(factorialZeros(10)) print(factorialZeros(14)) print(factorialZeros(20)) main()
false
6c99118054f5d24b3d145b5902fb77c66802a8b2
Renjihub/code_training
/Python/Duplicates.py
446
4.34375
4
# Print duplicate characters from string # Take sample string and print all duplicate characters. sample_str = "Helloo" print("Sample String :",sample_str) duplicate = set() for char in sample_str: count = 0 for char_s in sample_str: if char.lower()==char_s.lower(): count = count+1 if count>1: duplicate.add(char) if duplicate: print("Duplicate elements are : ",duplicate) else: print("No repeating character found.")
true
2d3c303813ec11805c04eaa1618963857e88ee64
mygerges/100-Days-of-Code
/Nested Condition.py
347
4.15625
4
height = float(input("Please enter your height: ")) age = int(input("Enter your age: ")) if height > 120: if age < 12 : print("You can Play, and payment $5") elif age <= 18: print("You can Play, and payment $7") else: print("You can Play, and payment $12") else: print("Sorry can't play due to your height")
true
a6d8d8d27cdc5053037f52ce897fb6c6844277e3
naumanasrari/NK_PyGamesBook
/1-chap1-get-started.py
355
4.34375
4
x=3 y=2 mul = x * y add1 = x + y sub1 = x - y dev1 = x / y expon1 = x ** y print("multiplication of x and y: ",mul) print("Addition of x and y: ",add1) print("Substraction of x and y: ",sub1) print(" Divsion of x and y in Integer: ",int(dev1)) print(" Divsion of x and y in Float: ",float(dev1)) print("Exponent of x and y: ",expon1) #print(result)
true
9d93d0a24c3c8072c13e033f9ad8a6e1a3858eed
rbabaci1/CS-Module-Recursive_Sorting
/src/searching/searching.py
2,178
4.28125
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): midpoint = (start + end) // 2 if start > end: return -1 if arr[midpoint] == target: return midpoint if arr[midpoint] > target: return binary_search(arr, target, start, midpoint - 1) else: return binary_search(arr, target, midpoint + 1, end) # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively def agnostic_binary_search(arr, target): isAsc, start, end = False, 0, len(arr) - 1 if len(arr) >= 2: if arr[0] < arr[-1]: isAsc = True while start <= end: midpoint = (start + end) // 2 if arr[midpoint] == target: return midpoint if isAsc: if arr[midpoint] > target: end = midpoint - 1 else: start = midpoint + 1 else: if arr[midpoint] > target: start = midpoint + 1 else: end = midpoint - 1 return -1 # def isAscending(arr): # if len(arr) >= 2: # if arr[0] < arr[1]: # return True # return False # def agnostic_recursive_binary_search(arr, target, start=0, end=None): # isAsc = isAscending(arr) # if not end: # end = len(arr) - 1 # midpoint = (start + end) // 2 # # base cases # if start > end: # return -1 # if arr[midpoint] == target: # return midpoint # if isAsc: # if arr[midpoint] > target: # return agnostic_binary_search(arr, target, start, midpoint - 1) # else: # return agnostic_binary_search(arr, target, midpoint + 1, end) # else: # if arr[midpoint] > target: # return agnostic_binary_search(arr, target, midpoint + 1, end) # else: # return agnostic_binary_search(arr, target, start, midpoint - 1) # return -1
true
2fff7530868944972faeaee929f3a617c6693bfd
sagsam/learn-python
/string-manipulation.py
1,718
4.125
4
print('C:\some\name') # here \n means newline! # o/p : ########### # C:\some # # ame # ########### # If you don’t want characters prefaced by \ to be interpreted as special characters, # you can use raw strings by adding an r before the first quote: print(r'C:\some\name') # note the r before the quote # o/p : ################ # C:\some\name # ################ # String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. # End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) # Sting Concatination print(3 * 'un' + 'ium') # 3 times 'un', followed by 'ium' print('Py''thon') text = ('Put several strings within parentheses ' 'to have them joined together.') print(text) prefix = 'Py' # print(prefix 'thon') error print(prefix + 'thon') #concatenate variables or a variable and a literal, with +: print(len(text)) word = 'Python' print(word[5]) # character in position 5 # since -0 is the same as 0, negative indices start from -1. print(word[-1]) # last character # Slicing print(word[0:2]) # characters from position 0 (included) to 2 (excluded) # start is always included, and the end always excluded. # s[:i] + s[i:] is always equal to s: print(word[:2] + word[2:]) # an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced. print(word[:2]) # character from the beginning to position 2 (excluded) print(word[4:]) # characters from position 4 (included) to the end
true
f4d7d0ab00cc1438d2e66ba11b405006e1842922
mohitgauniyal/Python-Learning
/list.py
672
4.34375
4
shopping_list = ["Apple","Banana"] #to create items list print(shopping_list) print(shopping_list[0:1]) #to print first two items from the list. shopping_list.append("Mango") #to add items in the current list. print(shopping_list) del shopping_list[0] #to delete items from the list. print(shopping_list) shopping_list[1] = "MANGO" #to update the list item. print(shopping_list) print(len(shopping_list)) list_num = [0,1,2,3,4,44,5] #new list. print(min(list_num)) #to print min. print(max(list_num)) #to print max. union_list = shopping_list + list_num #union of lists print(union_list) multiply_content = shopping_list * 2 #double the list items print(multiply_content)
true
ef371444b4406e23c1be33ee8dce8449656f098d
MichealGarcia/code
/py3hardway/ex44f.py
2,026
4.46875
4
# Composition # Inheritance is useful, but another way to do it # is just to use other classes and modules # rather than rely on implicit inhereitance. # Two of three ways of inheritance involve writing new code # to replace or alter funcitonality. # This can be replicated by calling functions in a module. #EXAMPLE: class Other(object): def override(self): print("OTHER override()") def implicit(self): print("OTHER implicit()") def altered(self): print("OTHER altered()") class Child(object): def __init__(self): self.other = Other() def implicit(self): # calling a method instead of rewriting the code. # Isn't this the same as using pass???? self.other.implicit() def override(self): print("CHILD override()") def altered(self): print("CHILD, BEFORE OTHER altered()") # So, instead of calling super() self.other.altered() print("CHILD, AFTER OTHER altered()") son = Child() son.implicit() son.override() son.altered() # So, did I need to make class Other? # When to use inheritance or composition # You don't want duplicated code all over your software. # It's not clean, or efficient. # Inheritance solves the problem of reuse, but when is it appropriate? # Inheritance is good for implied features set in base classes. # Composition solves the issue by giving you modules and capability to call functions # Both solve the problem, but when to use eachother? # Subjective, but here is an answer. # 1. Avoid multiple inheritance at all costs, as it's too complex to be # Reliable. if you're stuck with it, then be prepared to know the class # hierarchy and spend time finding where everything comes from. # 2. Use composition to package code into modules that are used in many # unrelated places and situations. # 3. Use inheritance only when there are clearly related pieces of code that # fit under a single concept or if you have to because of something you're using.
true
451431f093e7960dfa025130bb0b5a0d7f57794c
MichealGarcia/code
/py3hardway/ex9.py
683
4.3125
4
# variable containing a string of each day # of the week separated by a space days = "Mon Tue Wed Thu Fri Sat Sun" # using a back-slash n will print the following text in a new line. months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print("Here are the days: ", days) print("Here are the months: ", months) # This is new, and my guess is that using three quotes is the # same as telling the print function to copy as typed including new lines. # This also created the opportunity to use single and double quotes in the string. print(""" Theres something going on here. With three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """)
true
9c578c823109193ece1c066474eee5b76a6ab8eb
nzshow/pythonGb
/6.dictionary.py
474
4.15625
4
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} print('Alice:',dict['Alice']) print('Beth:',dict['Beth']) print('Cecil:',dict['Cecil']) dict['School'] = "DPS School"; # 增加键为'School'的条目 print(dict) dict['Name']="Jim"; # 修改键为'Name'的条目的值 print(dict) del dict['Name']; # 删除键是'Name'的条目 print(dict) dict.clear(); # 清空词典所有条目 print(dict) del dict ; print(dict) input()
false
62d63d655efd9c5fdd3dbfd1a18dd33b6e085fdf
MichalKala/Python_Guess_the_Number_game
/Python_Guess_the_Number_game/Python_Guess_the_Number_game.py
1,004
4.3125
4
import random #generate computer's number Computer_number = random.randint(0, 20) print("Your opponent has secretly selected number between 0-20\nYour goal is to guess the number!") print("") #Set loop to let user repeat the choice until they win Outcome = 0 while Outcome < 6: #Let user to choose a number User_choice = input("Guess the number: ") print("") #Check if enetered value is int try: User_number = int(User_choice) except ValueError: print("Please do not enter floating numbers or strings! Try again...") print("") break User_choice = int(User_choice) if Computer_number > User_choice: print("Wrong! Your number is too low, please try again") print("") Outcome = 2 elif Computer_number < User_choice: print("Wrong! Your number is too high, please try again") print("") Outcome = 4 else: print("You win!!! Congratz!") print("") Outcome = 6
true
2a4978c31422d1734b580661c46b018c7cae03b0
brayan0428/python_practice
/palindrome_word.py
312
4.1875
4
def palindrome(word): reversed_word = word[::-1] if reversed_word == word: return True return False if __name__=='__main__': word = str(input("Ingresa una palabra: ")) result = palindrome(word) if result: print("Es palindrome") else: print("No es palindrome")
false
4f981aeb86632e457a84bd74640e4b587d24e85e
pasu-t/myPython
/python_modules/sreedevi_modules/dict2_states.py
349
4.34375
4
# States / capitals x={'AP':'Hyd','TN':'Chennai','KN':'Bangalore','UP':'Lucknow'} name=input("Enter a state / capital name : ") for i,j in x.items() : if i==name : print(i,"Capital is :",j) break elif j==name : print(j,"State is : ",i) break else : print("Invalid state or capital name.")
false
44b959d49f4f7c6ed97bbcb02cb11b7e3815c575
sriley86/Python-4th
/Python Chapter 5 Maximum of Two Values.py
567
4.53125
5
# Chapter 4 Exercise 12 Maximum of Two Values # Write a function named max that accepts two integer values as arguments # and returns the value that is the greater of the two. Use the function in a # program that prompts the user to enter two integer values. The program should # display the value that is the greater of the two. # Input a = int(input('Enter a integer: ')) b = int(input('Enter another integer: ')) # Process and Output def max(a, b): if a > b: print(a, 'is bigger than', b) else: print(b, 'is bigger than', a) max(a, b)
true
00899bc6681527a2f79b03a8fea5727a613d199a
sriley86/Python-4th
/Python Chapter 2 Sales Tax.py
1,939
4.21875
4
# Chapter2 Exercise 6 Sales Tax # This program displays the Sales tax on purchased amount # Definition of the main function def main(): # Get the purchase amount purchaseAmount = getinput() print("The amount of the purchase:", purchaseAmount) statesalestax = calstatesalestax(purchaseAmount) print("The state sales tax:", statesalestax) countysalestax = calcountysalestax(purchaseAmount) print("The county sales tax:", countysalestax) Totalsalestax = caltotalsalestax(statesalestax, countysalestax) print("The total sales tax:", Totalsalestax) Totalofthesale = totalofsale(purchaseAmount, Totalsalestax) print("The total of the sale:", Totalofthesale) # definition of getinput function def getinput(): # Get the purchase amount purchaseAmount = float(input("Enter the amount of a purchase:")) return purchaseAmount # Definition of the calstatesalestax function def calstatesalestax(purchaseAmount): # Assign the value to State sales tax percentage Statesalestaxpercentage = 0.04 # Calculate the state sales tax statesalestax = purchaseAmount * Statesalestaxpercentage return statesalestax # Definition of the calcountysalestax function def calcountysalestax(purchaseAmount): # Assign the value to county sales tax percentage countysalestaxpercentage = 0.02 # Calculate the county sales tax countysalestax = purchaseAmount * countysalestaxpercentage return countysalestax # Definition of the caltotalsalestax function def caltotalsalestax(statesalestax, countysalestax): # Calculate the total sales tax Totalsalestax = statesalestax + countysalestax return Totalsalestax # Definition of the totalofsale function def totalofsale(purchaseAmount, totalsalestax): # Calculate the total of the sale Totalofthesale = purchaseAmount + totalsalestax return Totalofthesale # calling the main function main()
true
4b86009c40bf7db7bab264dda8e59da68ba1640b
Magictotal10/FMF-homework-2020spring
/homework6/pandas_exercise.py
1,264
4.25
4
import pandas as pd # Here you have to do some exercises to familiarize yourself with pandas. # Especially some basic operations based on pd.Series and pd.DataFrame # TODO: Create a Series called `ser`: # x1 1.0 # x2 -1.0 # x3 2.0 # Your code here ser = pd.Series([1.0, -1.0, 2.0],index=['x1','x2','x3']) # TODO: Create a DataFrame called `df`: # x0 x1 x2 # s0 -1.1 0.8 -2.5 # s1 -1.3 -1.0 -1.2 # s2 1.7 1.8 2.1 # s3 0.9 0.3 1.1 # Your code here df = pd.DataFrame( [[-1.1, 0.8, -2.5], [-1.3, -1.0, -1.2], [-1.7, 1.8, -2.1], [-0.9, 0.3, 1.1],], index=['s0','s1','s2','s3'], columns=['x0','x1','x2'] ) # TODO: select `df` by column="x1": print( df['x1']) # TODO: select `df` by third row and first column: print(df.iloc[2,0]) # TODO: change `df`'s column's name x0 to y0: df = df.rename( columns={'x0':'y0'}) # TODO: select `df` where column's name start with x: print( df[df.columns[df.columns.str.startswith('x')]]) # TODO: change `ser`'s index to [y0,x1,x2]: ser.index = df.columns # TODO: change `df` where column y0 multiply -1.5: df['y0'] = df['y0'] * -1.5 # TODO: calculate `df` dot `ser`: print(df.dot(ser)) # TODO: merge `ser` with the result of previous task: df.append(ser, ignore_index=True)
true
f8a1793ff5557fc5e36cffa31f61d91aa6d76157
srp527/Data-Structure-Algorithms
/3-0插入排序.py
1,909
4.1875
4
# -*- coding:utf-8 -*- __author__ = 'SRP' '''插入排序(Insertion Sort) 插入排序(Insertion Sort)的基本思想是:将列表分为2部分,左边为排序好的部分, 右边为未排序的部分,循环整个列表,每次将一个待排序的记录, 按其关键字大小插入到前面已经排好序的子序列中的适当位置,直到全部记录插入完成为止。''' import random import time import functools list2 = [random.randrange(10000) for i in range(10000)] list = [15,2,5,9,8,3,4,52,45,98,67,50,35,14,27,21,5] def run_time(): def decorator(func): @functools.wraps(func) def wrapper(*args,**kwargs): t1 = time.time() func(*args,**kwargs) t2 = time.time() print('<%s>用时:%s' %(func.__doc__,t2-t1)) return wrapper return decorator @run_time() def insert_sort(list): '''插入排序''' count = 0 n = len(list) for i in range(1,n): tmp = list[i] position = i while position > 0 and list[position-1] > tmp: list[position],list[position-1] = list[position-1],tmp position -= 1 count += 1 print('排序后:{0} \n排序次数:{1}'.format(list,count)) insert_sort(list) # count = 0 # for i in range(1,len(list)): # num = list[i] #先记下来每次大循环走到的第几个元素的值 # position = i # # print('num:%s,position:%s'%(num,position)) # # while position > 0 and list[position-1] > num: #当前元素的左边的紧靠的元素比它大,要把左边的元素一个一个的往右移一位,给当前这个值插入到左边挪一个位置出来 # list[position] = list[position-1] # position -= 1 # count += 1 # # print('--->',list) # # # print('num:%s,position:%s' % (num, position)) # list[position] = num # print(list) # print(count)
false
5acffb9fb1eae601653914242f88d2ed5fac2fa3
lightjameslyy/python-full-stack
/basics/02-python-basics/01_python_basics/lt_08_buy_apple_2.py
205
4.21875
4
# 1. input price of apple price = float(input("price of apple per Kg: ")) # 2. input weight of apples weight = float(input("weight of apples: ")) # 3. calculate money money = weight * price print(money)
true
2ef4486fcfbbc4d3cb84e17884e2285eb714d86b
preetesh0908/Python
/Assignment4/bubblyrock.py
992
4.25
4
import random def bubbleSort(xlst): for i in range(len(xlst)): for j in range(len(xlst) - 1): if (xlst[j] > xlst[j+1]): xlst[j], xlst[j+1] = xlst[j+1],xlst[j] size = int(input("Enter the number of random numbers to generate: ")) alist = [] for i in range(size): # append adds an element to a list alist.append(random.randrange(50)) print(alist) bubbleSort(alist) print(alist) def rockSort(xlst): for i in range(len(xlst)): for j in range(len(xlst) - 1): if (xlst[j] < xlst[j+1]): xlst[j], xlst[j+1] = xlst[j+1],xlst[j] size = int(input("Enter the number of random numbers to generate: ")) alist = [] for i in range(size): # append adds an element to a list alist.append(random.randrange(50)) print(alist) rockSort(alist) print(alist) ''' #The random.randrange(50)) gives us random numbers that are in the indext of 50 i.e, numbers from 0 to 49 (0,1,2,3....48,49) '''
false
3e91a965e8381d5742cff08340f6a369a137ba91
AswiniSankar/OB-Python-Training
/Assignments/Day-1/p9.py
372
4.4375
4
# program to find the given two string is equal or else which is smaller and bigger string1 = input("enter the string1") string2 = input("enter the string2") if string1 == string2: print("both strings are equal") elif string1 > string2: print(string1 + " is greater " + string2 + " is smaller") else: print(string1 + " is smaller " + string2 + " is greater")
true
f36d87c95330bca12b4d2caab7acd19336466d1e
AswiniSankar/OB-Python-Training
/Assignments/Day-5/p1.py
334
4.15625
4
# python program to calculate BMI of Argo def BMIOfArgo(weight, height): return (weight / (height * height)) age = int(input("Hai Arge, what is your Age?")) weight = float(input("What is your weight in kg ?")) height = float(input("What is your Height in meters")) print("The MBI is {:.1f}".format(BMIOfArgo(weight, height)))
true
6a229363003fbc4d6a16a91fb9d82140c5e4c030
AswiniSankar/OB-Python-Training
/Assignments/Day-5/p2.py
806
4.28125
4
# program to find BMI status def toFindBMI(weight, height): return round(weight / (height * height), 1) def BMIstatus(BMIvalue): if BMIvalue < 18.5: print("your BMI is " + str(BMIvalue) + " which means you are underweight") elif 18.5 <= BMIvalue and BMIvalue <= 24.9: print("your BMI is " + str(BMIvalue) + " which means you are healthy") elif 25.0 <= BMIvalue and BMIvalue <= 29.9: print("your BMI is " + str(BMIvalue) + " which means you are overweight") else: print("your BMI is " + str(BMIvalue) + " which means you are obese") name = input("what is your name? ") height = float(input("Hai " + name + ", What is your Height in meters? ")) weight = float(input("What is your weight in kg? ")) result = toFindBMI(weight, height) BMIstatus(result)
true
718fab3a92812374785b62fee3e140082e83626e
vikasbaghel1001/Hactoberfest2021_projects
/CDMA-Python/gen_file.py
760
4.40625
4
'''File Generator Module''' # modify PATH variable according to the filepath you want generate files in PATH = "./textfiles/input/input" file_no = int(input('Enter Number of Files : ')) msg = input('Enter text : ') print('Length of text is {}'.format(len(msg))) def generate_files(num): '''Function for generating files''' while num: with open(PATH + str(num) + '.txt', 'w', encoding='utf-8') as fptr: fptr.write(msg) num -= 1 print('Done! {} Files were created with "{}" written in each of them!'.format(file_no, msg)) ask = input('Are you sure to generate {} files? (y/N): '.format(file_no)) if ask in ('y', 'Y'): generate_files(file_no) else: print('You chose not to generate any files!')
true
41dd03437d4a4bddca4781687897f8fc5a4a1abf
vikasbaghel1001/Hactoberfest2021_projects
/Weight conversion using Python Tkinter.py
1,689
4.25
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 8 12:27:42 2021 @author: DHIRAJ """ # Python program to create a simple GUI # weight converter using Tkinter from tkinter import * # Create a GUI window window = Tk() # Function to convert weight # given in kg to grams, pounds # and ounces def convertfrom_kg(): # convert kg to gram gram = float(e2_value.get())*1000 # convert kg to pound pound = float(e2_value.get())*2.20462 # convert kg to ounce ounce = float(e2_value.get())*35.274 # Enters the converted weight to # the text widget tt1.delete("1.0", END) tt1.insert(END,gram) tt2.delete("1.0", END) tt2.insert(END,pound) tt3.delete("1.0", END) tt3.insert(END,ounce) # Create the Label widgets ee1 = Label(window, text = "Enter the weight in Kg") ee2_value = StringVar() ee2 = Entry(window, textvariable = e2_value) ee3 = Label(window, text = 'Gram') ee4 = Label(window, text = 'Pounds') ee5 = Label(window, text = 'Ounce') # Create the Text Widgets tt1 = Text(window, height = 1, width = 20) tt2 = Text(window, height = 1, width = 20) tt3 = Text(window, height = 1, width = 20) # Create the Button Widget bb1 = Button(window, text = "Convert", command = convertfrom_kg) # grid method is used for placing # the widgets at respective positions # in table like structure ee1.grid(row = 0, column = 0) ee2.grid(row = 0, column = 1) ee3.grid(row = 1, column = 0) ee4.grid(row = 1, column = 1) ee5.grid(row = 1, column = 2) tt1.grid(row = 2, column = 0) tt2.grid(row = 2, column = 1) tt3.grid(row = 2, column = 2) bb1.grid(row = 0, column = 2) # Start the GUI window.mainloop()
true
f5f565eacee20a64965707cef7501f4265c34b1d
ncaleanu/allthingspython
/advanced_func/collections.py
1,727
4.125
4
''' counter, defaultdict, ordereddict (not in this file), namedtuple, deque ''' # counter - keeps track of how many times an element appears from collections import Counter ''' device_temp = [14.0, 14.5, 15.0, 14.0, 15.0, 15.0, 15.5] temp_count = Counter(device_temp) print(temp_count) print(temp_count[14.0]) ''' # defaultdict - never raises key error, just returns the value # returned by the func when the object was created from collections import defaultdict ''' coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'),('Rolf', 'Cambridge')] # defaultdict takes in a function: list alma_mater = defaultdict(list) # if key doesnt exist in dict # then function called empty list created ^^ for coworker in coworkers: alma_mater[coworker[0]].append(coworker[1]) # If you want to raise an error from invalid keys, # set default factory to None. Note that empty lists still created above alma_mater.default_factory = None print(alma_mater['Rolf']) print(alma_mater['Noah']) ''' # named tuple. A more explicit way of using tuples! # Good for reading from databases and CSVs from collections import namedtuple ''' account = ('checking', 1850.90) Account = namedtuple('Account', ['name', 'balance']) accountNamedTuple = Account(*account) print(accountNamedTuple) print(accountNamedTuple._asdict()['balance']) ''' # Double ended queue, can push/remove items from # front or back of queue. GOOD FOR THREADS (thread safe) from collections import deque ''' friends = deque(('Rolf', 'Charlie', 'Jen', 'Anna')) # Working at the back friends.append('Jose') friends.pop() # Working at the start friends.appendleft('Noah') friends.popleft() print(friends) '''
true