blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b73a34f8f888832ca2cbb635f9a6224f817cd0ad
Harry-003/Python_programs
/Q1.py
340
4.25
4
""" Write Python Program (WPP) to enter length and breadth of a rectangle and calculate area and perimeter of the rectangle. """ length = int(input("Enter length of rectangle : ")) width = int(input("Enter width of rectangle : ")) print("Area of Rectangle : ",length*width) print("Perimeter of Rectangle : ",2*(length + width))
true
fd1d2e3977059ca1e86fd5b737c59d071adce2ce
Harry-003/Python_programs
/Q10.py
442
4.1875
4
""" WPP to enter principal amount, time and interest rate. Create simple_interest(principal, time, rate) function to calculate simple interest. """ amount = int(input("Enter principal amount: ")) time = int(input("Enter time period: ")) interest = float(input("Enter interest rate: ")) simple_interest(amount,time,interest) def simple_interest(principal,time,rate): print("Simple interest is : ",(principal*time*rate)/100)
true
4009f92fb3d3736b251a9d8fed74ed764b2165f1
jobfb/Python_introdution
/diagonal_negativos.py
708
4.125
4
#Fazer um programa para ler um numero inteiro N (no maximo 10 ) e uma matriz quadrada de ordem N contendo numeros inteiros #Em seguida mostrar a diagonal principal #Dizer quantos valores negativos a matriz possui N: int neg: int N = int(input("Qual a ordem da matriz? ")) mat: int = [[0 for x in range(N)] for x in range(N)] for i in range(0, N): for j in range(0, N): mat[i][j] = int(input(f"Elemento [{i},{j}]: ")) print("Diagonal principal:") for i in range(0,N): print(f"{mat[i][i]}") neg = 0 print() for i in range(0, N): for j in range(0, N): if mat[i][j] < 0: neg = neg + 1 print(f" O TOTAL DE NUMERO NEGATIVOS É : {neg}")
false
53f738d22b7635743d2727d49bce37e3efe3d271
DianaBelePublicRepos/PythonBasics
/Challenges/Anagrams.py
337
4.15625
4
#Check if a string is an anagram or not - use sorted to sort the string, then compare def check(s1, s2): # The sorted strings are checked if (sorted(s1) == sorted(s2)): print("The strings are anagrams.") else: print("The strings aren't anagrams.") # Driver code s1 = "listen" s2 = "silent" check(s1, s2)
true
53811f309fabe46e1dfc343046983a1befe95f97
duttasamd/pylearn
/05_features.py
1,075
4.125
4
# GENERATORS # Generators are more efficient than lists. #list comprehension # this is a list object squares_list = [x * x for x in range(10)] print(squares_list) #this is a generator squares_gen = (x*x for x in range(10)) print(squares_gen) for square in squares_gen: print(square) # Performance enhancement demo import m print("=====================================================================") # TEMPLATES from string import Template t = Template('x is $x') x = 1 print(t.substitute({'x' : 1})) print("=====================================================================") results = [] results.append({'name': 'Ram', 'marks': 40}) results.append({'name': 'Shyam', 'marks': 90}) results.append({'name': 'Jadu', 'marks': 50}) results.append({'name': 'Modu', 'marks': 56}) results.append({'name': 'Vikram', 'marks': 63}) t = Template('$name got $marks') for result in results : print(t.substitute(result)) # this is cleaner compared to : # # for result in results: # print("{} got {}".format(result['name'], result['marks']))
true
364b97fa0fadea89bea705ec340699e549091303
Miguelzm2001/introprogamacion
/Clases/clasesyobjetivos.py
2,147
4.3125
4
class Humano(): ''' Esta es la clase Humano exige atributos nombreEntrada: Hace referencia al nombre del usuario edadEntrada: Hace referencia al edad del usuario estaturaEntrada: Hace referencia al estatura del usuario Tiene las siguientes acciones: *hablar(mensaje): dado un mensaje lo muestra en pantalla *mostrarAtributos() muestra los atributos del usuario ''' def __init__(self, nombreEntrada, edadEntrada,estaturaEntrada): print('Hola soy un humano nuevo') self.edad = edadEntrada self.raza = 'Humano' self.nombre = nombreEntrada self.estatura = estaturaEntrada self.dinero = 0 def hablar(self,mensaje): print(f'Hola soy {self.nombre} tengo un mensaje que decir ...', mensaje) def mostrarAtributos(self): print(f'''Mi nombre es {self.nombre} Mi estatura es {self.estatura} metros Mi edad es {self.edad} años Tengo ahorrado {self.dinero} pesos ''') def recorrerDistancia(self,distanciaMetros): for i in range (distanciaMetros): print(f'Hola soy {self.nombre} y he recorrido {i+1} metros') def ahorraDinero(self): preguntaIngresarMontos = 'Ingrese S--> para continuar añadiendo montos y N--> para finalizar : ' preguntaMonto = 'Cuanto vas a ingresar?: ' ingresarMontos =input(preguntaIngresarMontos) while(ingresarMontos != 'N'): monto = float(input(preguntaMonto)) self.dinero = self.dinero + monto print(f'Soy {self.nombre} y tengo {self.dinero} pesos') ingresarMontos =input(preguntaIngresarMontos) return self.dinero humano1 = Humano('Daniel',27,1.67) humano2 = Humano('Mafer',27,1.60) humano1.hablar('Espero que esten muy bien') humano2.hablar('chao') print(humano1.nombre) print(humano2.nombre) print(humano2.edad) humano1.mostrarAtributos() humano1.recorrerDistancia(25) humano2.mostrarAtributos() totalAhorrado = humano2.ahorraDinero() humano2.mostrarAtributos()
false
2ce22e64173151b7603f1089718ffb153e9233a2
artOfThePigeon/RealPython_Projects
/Algorithms/2_main.py
2,070
4.46875
4
from random import randint from timeit import repeat def bubble_sort(array): n = len(array) for i in range(n): #start looking at each item of the list one by one, comparing it with #its adjacent value. With each iteration, the portion of the array that #that you look at shrinks because the remaining items have already beem sorted. for j in range(n - i - 1): #create a flag that will allow the function to terminate early if there's nothing #left to sort already_sorted = True if array[j] > array[j + 1]: # if the item you're looking at is greater than its # adjacent value then swap them array[j], array[j + 1] = array[j + 1], array[j] #since you had to swap two elements, #set the already_sorted flag to False so the #algorithm doesn't finish prematurely already_sorted = False #If there were no swaps during the last iteration, #the array is already sorted, and you can terminate if already_sorted: break return array def run_sorting_algorithm(algorithm, array): setup_code = f"from __main__ import {algorithm}" \ if algorithm != "sorted" else "" stmt = f"{algorithm}({array})" # Execute the code ten different times and return the time in seconds that each execution took times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10) # display the name of the algorithm and the minimum time it took to run print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}") ARRAY_LENGTH = 10000 if __name__ == "__main__": # generate an array of ARRAY_LENGTH items consisting of random integer values # between 0 and 999 array = [randint(0, 1000) for i in range(ARRAY_LENGTH)] # call the function using the name of the sorting algorithm and the array you just created run_sorting_algorithm(algorithm="bubble_sort", array=array)
true
50929ac315ab9dea49c9bb134901bc945329fbcc
Utuska/Python_unit2_3
/Unit2_3.py
2,567
4.21875
4
month = input("Введите месяц:") if month: date = int(input("Введите дату")) if 1 <= date <= 31: if 22 <= date <= 31 and month.lower() == 'декабрь': print("Козерог") elif 1 <= date <= 19 and month.lower() == 'январь': print("Козерог") elif 22 <= date <= 31 and month.lower() == 'январь': print("Водолей") elif 1 <= date <= 18 and month.lower() == 'февраль': print("Водолей") elif 19 <= date <= 31 and month.lower() == 'февраль': print("Рыбы") elif 1 <= date <= 20 and month.lower() == 'март': print("Рыбы") elif 21 <= date <= 31 and month.lower() == 'март': print("Овен") elif 1 <= date <= 20 and month.lower() == 'апрель': print("Овен") elif 21 <= date <= 31 and month.lower() == 'апрель': print("Телец") elif 1 <= date <= 20 and month.lower() == 'май': print("Телец") elif 21 <= date <= 31 and month.lower() == 'май': print("Близнецы") elif 1 <= date <= 20 and month.lower() == 'июнь': print("Близнецы") elif 21 <= date <= 31 and month.lower() == 'июнь': print("Рак") elif 1 <= date <= 22 and month.lower() == 'июль': print("Рак") elif 23 <= date <= 31 and month.lower() == 'июль': print("Лев") elif 1 <= date <= 22 and month.lower() == 'август': print("Лев") elif 23 <= date <= 31 and month.lower() == 'август': print("Дева") elif 1 <= date <= 23 and month.lower() == 'сентябрь': print("Дева") elif 24 <= date <= 31 and month.lower() == 'сентябрь': print("Весы") elif 1 <= date <= 23 and month.lower() == 'октябрь': print("Весы") elif 24 <= date <= 31 and month.lower() == 'октябрь': print("Скорпион") elif 1 <= date <= 21 and month.lower() == 'ноябрь': print("Скорпион") elif 22 <= date <= 31 and month.lower() == 'ноябрь': print("Стрелец") elif 1 <= date <= 21 and month.lower() == 'декабрь': print("Стрелей") else: print("Неверная дата или месяц")
false
bb184a33455cb393128ecc7e30ea3104477c75a5
samsharpy/odd-or-even-_-fizzbuss
/odd or even.py
377
4.34375
4
#created on 22/09/2019 #author: samuvel a=int(input('enter the number to be found:'))#getting input if(a%2==0 and a!=0):# wherther its even print("the given number is even") elif(a==0):# or 0 print ("the given number is neither odd nor even") else:# if its not both its odd print ("the given number is odd") print("end of the program")
true
ed3b39932960c070388e691696cc97760591490e
shubhendutiwari/P_SomeLearningCode
/Overlapping.py
870
4.1875
4
"""Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.""" def overlapping(lst1, lst2): for x in lst1: print(x) if x in lst2: return True else: continue return False lis1 = [] more_input = 'y' while more_input == 'y': p = input("Enter the value to add in list ONE : ") lis1.append(p) more_input = input("Enter 'y' to add more element in list : ") lis2 = [] more_input = 'y' while more_input == 'y': p = input("Enter the value to add in list TWO : ") lis2.append(p) more_input = input("Enter 'y' to add more element in list : ") print(overlapping(lis1,lis2))
true
a3c58c1795bb7aa71bb490e1a85e4f6adb5997ab
MitenTallewar/Hacktoberfest2021_beginner
/Python3-Learn/get_seat_type.py
947
4.40625
4
def seat_type(seat_number = int(input("Enter the seat number: "))): """ input : - seat number (int) return : - seat type (string) Given a railway seat number, the task is to check whether it is a valid seat number or not. Also print its berth type i.e lower berth, middle berth, upper berth, side lower berth, side upper berth. """ if seat_number>0 and seat_number<73: if seat_number % 8 == 1 or seat_number % 8 == 4: print(seat_number, " is lower berth") elif seat_number % 8 == 2 or seat_number % 8 == 5 : print(seat_number, " is middle berth") elif seat_number % 8 == 3 or seat_number % 8 == 6: print(seat_number, " is upper berth") elif seat_number % 8 == 7 : print(seat_number, " is side lower berth") else: print(seat_number," is side upper berth") else: print(seat_number," is invalid") seat_type()
true
942b796938f987092fa5fcd2b20356ef17b02c05
edanyliuk/python-programming
/unit-3/func.py
2,008
4.4375
4
def add(num1, num2): return num1 + num2 #you write a function to do something. Something it will return something and sometimes it doesn't. #Use return for a function that calculates something - it gives you the answer #this function adds two integers print(add(5, 10)) #pass to print function result = add(50, 20) #assign to a variable. always name your variables to reflect what they're doing ie num1 and num2 #parameter vs argument. important to understand when we use which #function may or may not have parameters. Can be 0 #we use a function by calling it. ie print() the thing inside () are the arguments #num1 and num2 are parameters #function has no parameters and takes no arguments when were calling it. #when were calling it we give it arguments #this function displays hello there def say_hello(): print("Hello there!") say_hello() #cannot use your function before it is defined #function that returns the length of a string def length(string): return len(string) print(length("hi there")) #function to return the sum of integers in a list #use is to compare types def sum_of_integers(a_list): result = 0 for num in a_list: if type(num) is int: result += num return result print(sum_of_integers([1, 2, 3, "a"])) #function to reverse a string. the while loop is used to count backwards def rev_string(string): idx = len(string) - 1 result = "" while idx >= 0: result += string[idx] idx -= 1 return result print(rev_string("Emma")) #reverse string in one line (python) def one_line_reverse(string): return string[::-1] print(one_line_reverse("Emmasmalll")) #using a for loop - Daniela's version. This puts the first part last. Will find the first letter in the string and then add to result which is blank. Then it keeps adding def daniela_reverse(string): result = "" for character in string: result = character + result return result print(daniela_reverse("HIIIIITINY"))
true
320f7189bac2eec0eb884a30a4630525f5dfe803
edanyliuk/python-programming
/unit-2/strings.py
782
4.28125
4
#strings are immutable. We cannot change a string #strings are iterable movie_title = "Thor, the Dark World" #print(movie_title[0]) #movie_title[5] = " - " #this is not allowed #Once the string has been declared you cannot change it. You can re-assign movie_title movie_title = "The Avengers" #this is reassignment start = movie_title[0:2] #starts from position 0 and grabs up to position 2 but excludes position 2 (which would be the third character) #Indices can also be negative. -1 gives you the last character #If you are starting with position 0 then you can just do [:x number] and if you do [x number:] then it goes to the end #you can use [:x number] with x number being negative. print(movie_title[-1]) print(start) print(movie_title[:4]) print(movie_title[2:])
true
40716570b086a89c8a00ad893fc41055510855f3
cgj333/46-Simple-Python-Exercises
/Simple exercises including I:O/36 - Hapax Legomenon.py
813
4.21875
4
''' A hapax legomenon (often abbreviated to hapax) is a word which occurs only once in either the written record of a language, the works of an author, or in a single text. Define a function that given the file name of a text will return all its hapaxes. Make sure your program ignores capitalization. ''' import re def hapax_checker(file_name): with open(file_name, 'r') as f: f = f.read() # substitute all non letters with spaces f = re.sub(r'[^A-Za-z]', ' ', f) words = f.lower().split(' ') for line in f: words.append(line.lower().split()) # filter swords which occurs once hapaxes = list(filter(lambda x: words.count(x) == 1, words)) return hapaxes file_name = input('Please enter your file name') print(hapax_checker(file_name))
true
02fd4c2cb3f7b69a83cb3175d529942edb7077fb
RaviC19/Rock-Paper-Scissors-Python
/rps_with_randint.py
2,488
4.3125
4
from random import randint computer_wins = 0 player_wins = 0 winning_score = 5 while computer_wins < winning_score and player_wins < winning_score: player = input("What is your choice? ").lower() computer = randint(0, 2) if computer == 0: computer = "Rock" elif computer == 1: computer = "Paper" else: computer = "Scissors" if player.lower() == computer.lower(): print( f"You and the computer chose the same option, this game is a draw. The score is you have {player_wins} whilst the computer has {computer_wins}") elif player == "rock": if computer == "Scissors": player_wins += 1 print( f"You chose Rock and the computer chose Scissors. Your Rock Wins! The score is you have {player_wins} whilst the computer has {computer_wins}") elif computer == "Paper": computer_wins += 1 print( f"You chose Rock and the computer chose Paper. The Computer's Paper Wins! The score is you have {player_wins} whilst the computer has {computer_wins}") elif player == "paper": if computer == "Rock": player_wins += 1 print( f"You chose Paper and the computer chose Rock. Your Paper Wins! The score is you have {player_wins} whilst the computer has {computer_wins}") elif computer == "Scissors": computer_wins += 1 print( f"You chose Paper and the computer chose Scissors. The Computer's Scissors Wins! The score is you have {player_wins} whilst the computer has {computer_wins}") elif player == "scissors": if computer == "Rock": computer_wins += 1 print( f"You chose Scissors and the computer chose Rock. The Computer's Rock Wins! The score is you have {player_wins} whilst the computer has {computer_wins}") elif computer == "Paper": player_wins += 1 print( f"You chose Scissors and the computer chose Paper. Your Scissors Wins! The score is you have {player_wins} whilst the computer has {computer_wins}") else: print("You entered something that wasn't Rock, Paper or Scissors") if computer_wins > player_wins: print("The computer reached 5 before you could so unfortunately you lost!") elif player_wins > computer_wins: print("Congratulations! You got to 5 wins before the computer could and you won!")
true
06d6c817d9d80510b2c57535396565b1770da24a
yi-mei-wang/boggle
/boggle_dictionary.py
1,604
4.5625
5
def binary_search(target, my_list): """ Searches for a target in a sorted list recursively. Uses the binary search algorithm. Target is compared to the midpoint. If the former is not found, compare it to the latter. Depending on whether the target is smaller or larger than the midpoint, the irrelevant portion of the list is discarded. Args: ----- target : A string or an int to be searched for my_list : A sorted list to be searched from Returns: -------- A boolean indicating whether the target is found. """ start = 0 endpoint = len(my_list) - 1 midpoint = (start + endpoint) // 2 if start > endpoint: return False else: if target == my_list[midpoint]: return True elif target < my_list[midpoint]: # endpoint = midpoint - 1 return binary_search(target, my_list[0:midpoint]) elif target > my_list[midpoint]: # start = midpoint + 1 return binary_search(target, my_list[midpoint+1:]) def load_dictionary(pathname): """Loads a dictionary in the form of a .txt file. Opens a .txt file. Strips the ending newline character from each line in the file before appending each line into a list. Args: ----- pathname : A string representing the path to a .txt file. The file should contain a new word on each line. Returns: -------- A list whose elements are the words from the .txt file with their newline character stripped. """ return [line.rstrip('\n') for line in open(pathname)]
true
87643d55fcc9ef5676e8a23fac85eea467de119a
surfer190/fixes
/calculate_age.py
874
4.28125
4
def get_age_in_days(age_in_years: int) -> int: ''' Calculate the age in days ''' return age_in_years * 365 def get_age_in_hours(age_in_years: int) -> int: ''' Calculate the age in hours ''' return age_in_years * 365 * 24 def get_age_in_seconds(age_in_years: int) -> int: ''' Calculate the age in seconds ''' return age_in_years * 365 * 24 * 60 * 60 if __name__ == "__main__": age = int(input('How old are you? ')) age_expected = int(input('How old are you expected to be? ')) print(get_age_in_days(age), 'days') print(get_age_in_hours(age), 'hours') print(get_age_in_seconds(age), 'seconds') years_left = age_expected - age print(get_age_in_days(years_left), 'days left') print(get_age_in_hours(years_left), 'hours left') print(get_age_in_seconds(years_left), 'seconds left')
false
954daabc6726320661a914cb8ac2274452136788
shiden/Fundamentals-of-Computing-Python
/scripts/wk1b_prac06.py
1,442
4.1875
4
#Write a Python function name_and_age that take as input the parameters name #(a string) and age (a number) and returns a string of the form "% is % years #old." where the percents are the string forms of name and age. The function #should include an error check for the case when age is less than zero. In this #case, the function should return the string "Error: Invalid age". Name and age #template --- Name and age solution --- Name and age (Checker) # Compute the statement about a person's name and age, given the person's name and age. ################################################### # Name and age formula # Student should enter function on the next lines. #saved as: http://www.codeskulptor.org/#user44_GT0N2p9COM_0.py def name_and_age(name, age): """ Check age and name of person and returns an error if less than 0 """ if age > 0 : return name + " is " + str(age) + " years old." else: return "Error: Invalid age" ################################################### # Tests # Student should not change this code. def test(name, age): """Tests the name_and_age function.""" print name_and_age(name, age) test("Joe Warren", 52) test("Scott Rixner", 40) test("John Greiner", -46) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #Joe Warren is 52 years old. #Scott Rixner is 40 years old. #Error: Invalid age
true
e25d7289cb317ac1b113e9e0c1ec9807c1b020e9
shiden/Fundamentals-of-Computing-Python
/scripts/wk1_prac01.py
1,207
4.53125
5
# Compute the number of feet corresponding to a number of miles. ##Write a Python function miles_to_feet that takes a parameter miles and #returns the number of feet in miles miles. Miles to feet template --- Miles #to feet solution --- Miles to feet (Checker) #There are 5280 feet in a mile, because one mile is defined as 8 furlongs #and 1 furlong is 660 feet, that makes 8 * 660 ft = 5280 feet in a mile. ################################################### # Miles to feet conversion formula # Student should enter function on the next lines. #saved as: http://www.codeskulptor.org/#user44_FVnIZ9YzZi_0.py def miles_to_feet(miles): feet = miles * 5280 #print "miles: ", miles #s print "feet: ", feet return feet ################################################### # Tests # Student should not change this code. def test(miles): print str(miles) + " miles equals", print str(miles_to_feet(miles)) + " feet." test(13) test(57) test(82.67) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #13 miles equals 68640 feet. #57 miles equals 300960 feet. #82.67 miles equals 436497.6 feet.
true
0de5ba0c7108aa7cb12999eab3996a5bde3f4144
shiden/Fundamentals-of-Computing-Python
/scripts/wk1_prac09.py
1,229
4.21875
4
#Write a Python function name_and_age that takes as input the parameters name #(a string) and age (a number) and returns a string of the form "% is % years #old." where the percents are the string forms of name and age. Reference the #test cases in the provided template for an exact description of the format of #the returned string. Name and age template --- Name and age solution --- #Name and age (Checker) # Compute the statement about a person's name and age, given the person's name and age. #saved as: http://www.codeskulptor.org/#user44_cuhkCTyEnu_0.py ################################################### # Name and age formula # Student should enter function on the next lines. def name_and_age( name, age): sentence = name + " is " + str(age) + " years old." return sentence ################################################### # Tests # Student should not change this code. def test(name, age): print name_and_age(name, age) test("Joe Warren", 52) test("Scott Rixner", 40) test("John Greiner", 46) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #Joe Warren is 52 years old. #Scott Rixner is 40 years old. #John Greiner is 46 years old.
true
df1de6157d40997931980aa3a079cb4e7bad68f2
techkids-c4e/c4e5
/MinhQuang(c4e)/BTVN 6-7-2016/wave1.py
548
4.125
4
hanoi = {"name":"Hanoi", "longt":50, "lat": 75} haiduong = {"name" : "HaiDuong", "longt" : 25, "lat":10} class City: def __init__(self,name,longt,lat): self.name = name self.longt = longt self.lat = lat def calculateDistance(self, other): distance = ((self.longt-other.longt)**2 + (self.lat-other.lat)**2) **(1/2) return distance Hanoi = City("Hanoi",50,75) HaiDuong = City("HaiDuong",25,10) x = Hanoi.calculateDistance(HaiDuong) print("The distance is:",x)
false
d09a5f5fd329573e8d3abcce043a6314132baa85
techkids-c4e/c4e5
/Minh Đức/BTVN 26.6/Session 5-3.py
434
4.1875
4
from turtle import* shape('turtle') speed(0) def draw_star(x,y,length): penup() forward(x) left(90) forward(y) right(90) pendown() for a in range(5): forward(length) right(144) x=float(input('Please enter x for the location of the star: ')) y=float(input('Please enter y for the location of the star: ')) length=float(input('Please enter length of the star: ')) draw_star(x,y,length)
true
ada0c491f7fe246f2d45f314d089315c6d5d8a73
ibreezzy/Calculating-Areas
/assignment4.py
1,298
4.21875
4
#This program is designed to calculate the area of a square print('This calculator helps you calculate the area of a square') Length = float(input('What is the length?: ')) Area = Length ** 2 print('Area',(round(Area,2))) #This program is designed to calculate the area of a trapezoid print('This calculator helps you calculate the area of a trapezoid') Base2a = float(input('Enter the value of a: ')) Base2b = float(input('Enter the value of b: ')) Height2 = float(input('Enter the value of h: ')) Area2 = (Base2a + Base2b) / (2) * (Height2) print('Area =',(round(Area2,2))) #This program is designed to calculate the area of a cylinder with closed surface print('This calculator helps you calculate the area of a cylinder with closed surface') from math import exp, pi Radius = float(input('Enter the value of radius: ')) Height3 = float(input('Enter the value of Height: ')) Area3 = (2 * pi * Radius * Height3) + (2 * pi * Radius) print('Area =',(round(Area3,2))) #This program is designed to calcullate the area of a triangle print('This calculator helps you calculate the area of a triangle') Height4 = float(input('Enter the value of height: ')) Base4 = float(input('Enter the value of base: ')) Area4 = (Height4 * Base4) / (2) print('Area =',(round(Area4,2)))
true
64fd6ba274469c08aa1bb70cca66d3b46923d7a3
congxinxu0116/CMU15112
/Week 2/GraphicsPart1.py
1,028
4.3125
4
# Graphics in Tkinter Part 1 # Create an Empty Canvas from tkinter import * def draw(canvas, width, height): # create_line (x1, y1, x2, y2) draws a line # from (x1, y1) to (x2, y2) canvas.create_line(25, 50, width/2, height/2) def runDrawing(width=300, height=300): root = Tk() root.resizable(width=False, height=False) # prevents resizing window canvas = Canvas(root, width=width, height=height) canvas.configure(bd=0, highlightthickness=0) canvas.pack() draw(canvas, width, height) root.mainloop() print("bye!") runDrawing(400, 200) from tkinter import * def draw(canvas, width, height): pass # replace with your drawing code! def runDrawing(width=300, height=300): root = Tk() root.resizable(width=False, height=False) # prevents resizing window canvas = Canvas(root, width=width, height=height) canvas.configure(bd=0, highlightthickness=0) canvas.pack() draw(canvas, width, height) root.mainloop() print("bye!") runDrawing(400, 200)
true
2afcaddebc7cbfbeb2898a0ac8190cfcf6f18fbf
zhangpenghui1122/warehouse
/123/02_第二周-周测题目(1).py
2,604
4.25
4
""" 选择题(每题10分 ,共50分) 1. 关于面向过程描述正确的是:( C ) A: 根据需求划分职责,然后交给不同程序员完成。 B:根据职责划分任务,然后专人实现。 C:根据解决问题步骤,然后逐步实现。 D:使用函数屏蔽过程,彰显实现细节。。 2. 关于面向对象描述正确的是:( A ) A:使用封装、继承、多态的特点解决问题 B:使用分而治之、变则疏之、高内聚、低耦合的理念解决问题 C:主要考虑算法+数据结构 D:根据需求,划分给多个程序员共同完成。 3. class MyClass:( D ) def __init__(qtx,a,b=””): qtx.a = a qtx.b = b qtx.c = 100 关于语法,下列描述正确的是: A:构造函数__init__的第一个参数必须是self,存储的是当前对象地址. B: 因为参数b有默认值,所以参数a也应该有默认值。 C:构造函数不应该使用del修饰,不能使用def修饰。 D:实例变量c不能在构造函数中确定值,必须作为参数。 4. class MyClass:( A ) def __init__(qtx,a,b=""): qtx.a = a qtx.b = b qtx.c = 100 关于创建对象,下列语法正确的是: A:MyClass(10,20) B: __init__(10,”20”) C: mc = MyClass(10,20,”30”) D: mc = __init__(10,”20”) 5. class MyClass:( C ) def __init__(self,a): self.a = a mc = MyClass(10) 关于修改实例变量,下列错误的是: A:mc.__dict__[“a”] = 20 B:mc.a = 20 C:MyClass.a = 20 D:mc.a = “20” 编程题(50分) 根据课上讲过的薪资计算器案例,使用面向对象的方式重写薪资计算器 """ # 根据课上讲过的薪资计算器案例,使用面向对象的方式重写薪资计算器 # 根据工资计算个人社保缴纳费用 # 步骤:在终端中录入工资,根据公式计算,显示缴纳费用 # 公式:养老保险8% + 医疗保险2% + 3元 + 失业保险0.2% + 公积金12% class Salary: def __init__(self, money): self.money = money def salary01(self, x): print("工资为:" + str(self.money)) x.sd(self.money) class Salary_calculato: def __init__(self, endowment, medical, unemployment, fund): self.endowment = endowment self.medical = medical self.unemployment = unemployment self.fund = fund def sd(self, value): money01 = value * (self.endowment + self.medical + self.unemployment + self.fund) money01 += 3 print("缴纳费用为:" + str(money01)) s01 = Salary(6000) t01 = Salary_calculato(0.08, 0.2, 0.02, 0.12) s01.salary01(t01)
false
8c222dd730d84b29c382da7b854387d83520ee1e
Chen-Wei-Ming/Python-Learn
/lesson1.py
331
4.5
4
# 變數建立 # create a var # var is a integer var = 1 print(var) # var is a float var = 1.0 print(var) # var is a character var = '1' print(var) # var is a String var = 'string' print(var) # var is a Array var = ['array1' , 'array2' , 'array3'] print(var) # print item which in var array for item in var : print(item)
false
6f69325321dc16a417bd2c4ce3dffb7093a17dcb
henrylin2015/python
/fun.py
1,376
4.5
4
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ r''' learning.py A Python 3 tutorial from http://www.liaoxuefeng.com Usage: python3 learning.py ''' import sys def check_version(): v = sys.version_info if v.major == 3 and v.minor >= 4 : return True print('Your current python is %d.%d.Please use Python 3.4' % (v.major,v.minor)) return False if not check_version(): exit(1) r''' 用户从键盘输入数据,然后输出到控制台 ''' ''' def get_name(): return input('Please enter your name:') print(get_name()) ''' ''' 小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点,并用字符串格式化显示出'xx.x%',只保留小数点后1位: ''' ''' def get_core(): s1 = 72 s2 = 85 r = (s2-s1)/s1*100 return ('%.2f' % r) print("小明的成绩的百分点:%s" % get_core()) ''' ''' 我们先写一个计算x2的函数: ''' #def power(x): # return x * x ''' 现在,如果我们要计算x3怎么办?可以再定义一个power3函数,但是如果要计算x4、x5……怎么办?我们不可能定义无限多个函数。 你也许想到了,可以把power(x)修改为power(x, n),用来计算xn,说干就干: ''' def power(x,n): s = 1 while n > 0: n = n -1 s = s * x return s print('power(5,5):%s' % power(5,5))
false
cab76a4130e1086f188dd21acecf89de713d0c4f
ferasmis/Volume-of-a-Sphere
/Exercise2.2.1.py
222
4.65625
5
## Author: Feras ## Description: Find the volume of a sphere using a radius from user input radius = float(input('Enter a radius of a sphere:\n')) pi = 3.14 volume = (4/3) * pi * radius**3 print('Volume is %.2f' % volume)
true
853eda5e2b9223cd378c3d226bfe37ebf63f240a
vinayakasg18/algorithms
/InsertionSortSwap.py
719
4.1875
4
class InsertionSort: """ Function to sort the input array using Insertion Algorithm """ def insertionsort(self, a): if not a: return [] # 0 1 2 3 4 5 # [5, 2, 4, 1, 0, 2] # [2, 5, 4, 1, 0, 2] # [2, 4, 5, 1, 0, 2] for index in range(1, len(a)): # sorted(0, index - 1) -- works key = a[index] while index > 0 and key < a[index - 1]: a[index - 1], a[index] = a[index], a[index - 1] # sorted(index - 1, index) -- wrong index = index - 1 return a if __name__ == "__main__": array = [5, 2, 4, 1, 1, 9] print(InsertionSort().insertionsort(array))
true
b5d5c25d75cced8bdfd281754ed0bd0fe3735d48
leo-skinner/CursoEmVideoPython
/CursoEmVideo/Mundo1/Exercicios/Exe022_Upper_Lower_Split.py
767
4.28125
4
#Crie programa que leia o nome completo e mostre: #- O nome com Uppercase #- O nome com Lowercase #- Quantas letras ao no total, sem considerar espaços #- Quantas letras tem o primeiro nome. nome = str(input('Digite seu nome completo: ')).strip() #para eliminar possíveis espaços no início e final da string. print('Seu nome em uppercase: ', nome.upper()) print('Seu nome em lowercase: ', nome.lower()) # usando replace... print('1- Número de letras de seu nome completo: ', len(nome.replace(' ', ''))) # usando subtração de espaços print('2- Número de letras de seu nome completo: ', len(nome) - nome.count(' ')) letras = nome.split() print('Seu primeiro nome é {} e tem: {} letras' .format(letras[0] ,len(letras[0]), 'letras.'))
false
263289f824eb0bf43a79195cdb8117b6ff90f921
sdsunjay/interviews
/battleship/script.py
2,023
4.15625
4
# import random module import random def create_board(): board = [] for i in range(0, 5): board.append(["0"] *5) return board def print_board(board): for i in board: print(" ".join(i)) def random_row(board): return random.randint(0,len(board)-1) def random_col(board): return random.randint(0, len(board[0])-1) def guess(board, ship_row, ship_col): tries = 0 while(tries < 3): print("Turn: " + str(tries+1)) guess_row = int(input("Guess Row: ")) while guess_row < 0 or guess_row > 4: print("Oops, that's not even in the ocean") guess_row = int(input("Guess Row: ")) guess_col = int(input("Guess Col: ")) while guess_col < 0 or guess_col > 4: print("Oops, that's not even in the ocean") guess_col = int(input("Guess Col: ")) # print(ship_row) # print(ship_col) if guess_row == ship_row and guess_col == ship_col: print("Congratulations! You have hit my battleship!") break # ship_row = random_row(board) # ship_col = random_col(board) else: if guess_row == ship_row: print("You missed my battleship! (row is correct)") elif guess_col == ship_col: print("You missed my battleship! (col is correct)") else: print("You missed my battleship!") if board[guess_row][guess_col] == "X": print("You've guessed that one already!") tries-=1 if tries == 3: print("Game Over") board[guess_row][guess_col] = "X" print_board(board) tries+=1 return 0 def main(): board = create_board() print_board(board) ship_row = random_row(board) ship_col = random_col(board) guess(board, ship_row, ship_col) if __name__ == '__main__': # use test_main to create tables and genres # test_main() main()
false
25080e32b5e28b89120d552832cd3994ecd5c1f6
ryanedmonds2000/VizualizeSorts
/Sorts/utils.py
206
4.125
4
# Helper functions def swap(list, i, j): """ Swaps the elements in indexes i and j in the given list. Updates list without returning """ temp = list[j] list[j] = list[i] list[i] = temp
true
db879c56aae573f4992b56471cca3deb6c4725e3
varghesetom/Sweigart_Inspired_Games
/pygameHelloWorld.py
2,145
4.3125
4
'''The following is directly from the Al Sweigart book. I typed out the commands for practice on using pygame ''' import pygame, sys from pygame.locals import * ## set up pygame pygame.init() # set up window windowSurface = pygame.display.set_mode((500,400), 1, 8) pygame.display.set_caption("Hello World!") # Set up the colors black = (0,0,0) white = (255,255,255) red = (255, 0 , 0 ) green = (0, 255, 0) blue = (0, 0 , 255) # Set up the fonts basicFont = pygame.font.SysFont(None, 30) # Set up text ## .render(text, aliasing, text color, background color) text = basicFont.render("Hello World!", True, white, blue) textRect = text.get_rect() ## assigning the overall surface's center coords to the text coords textRect.centerx = windowSurface.get_rect().centerx textRect.centery = windowSurface.get_rect().centery # Draw white background onto surface windowSurface.fill(white) # Draw a green polygon onto surface ## .polygon(Surface object to draw on, color, tuple of tuples for coords, ## and optionally line width but if not filled, then polygon will be filled) pygame.draw.polygon(windowSurface, green, ((146,0), (291,106), (236,277), (56,277), (0,106))) # Draw some blue lines onto surface pygame.draw.line(windowSurface, blue, (60,60), (120,60), 4) pygame.draw.line(windowSurface, blue, (120,60), (60,120), 3) #Draw a blue circle ## .circle(surface object, color, center point, radius, line width) ### last arg can be 0 so can be filled in pygame.draw.circle(windowSurface, blue, (300,50), 20,0) #Draw a red ellipse pygame.draw.ellipse(windowSurface, red, (300,250,40,80),1) #draw text's background rectangle pygame.draw.rect(windowSurface, red, (textRect.left-20, textRect.top-20, textRect.width+40, textRect.height + 40)) # Get pixel array of surface pixArray = pygame.PixelArray(windowSurface) pixArray[480][380] = black del pixArray # draw text ## putting a surface object upon another windowSurface.blit(text, textRect) # draw window on screen pygame.display.update() # run game loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
true
642ba2a0b4ca733364d96c89e629e51d017c2ca1
conanchiao/Ling-Ji-Chu-Xue-Python-Yu-Yan-CAP
/Unit 4 Python编程之控制结构/maxn.py
380
4.1875
4
# maxn.py # 寻找一组数中的最大值 def main(): n=eval(input("How many numbers are there?")) max=eval(input("Enter a number >> ")) #将第一个值赋值给max for i in range(n-1): x=eval(input("Enter a number >> ")) #连续与后边n-1个值比较 if x>max: max=x print("The largest value is ", max) main()
false
e2ef90c5f2b66c44c6f3189dd6257ea1182b4cfa
DvC99/Ahoy-Capitan
/main.py
2,456
4.21875
4
""" Programa para apoyar al marinero Seijo Daniel Valencia Cordero Mayo 3-2021 """ import utilidades as util #====================================================================== # Algoritmo principal Punto de entrada a la aplicación (Conquistar) # ===================================================================== # Ejecuta el programa varias veces para ver su funcionamiento criatura= util.aparecer_criatura() direccion=util.aparecer_direccion() if(criatura == 'Kraken'): if(direccion == 'babor' or direccion == 'estribor'): print("Ahoy! capitán, un Kraken a "+direccion) elif(direccion == 'proa' or direccion == 'popa'): print("Ahoy! capitán, un Kraken por la "+direccion) elif(criatura == 'Sirenas'): if(direccion == 'babor' or direccion == 'estribor'): print("Ahoy! capitán, unas Sirenas a "+direccion) elif(direccion == 'proa' or direccion == 'popa'): print("Ahoy! capitán, unas Sirenas por la "+direccion) elif(criatura == 'Ballena'): if(direccion == 'babor' or direccion == 'estribor'): print("Ahoy! capitán, una Ballena a "+direccion) elif(direccion == 'proa' or direccion == 'popa'): print("Ahoy! capitán, una Ballena por la "+direccion) elif(criatura == 'Hipocampo'): if(direccion == 'babor' or direccion == 'estribor'): print("Ahoy! capitán, un Hipocampo a "+direccion) elif(direccion == 'proa' or direccion == 'popa'): print("Ahoy! capitán, un Hipocampo por la "+direccion) elif(criatura == 'Macaraprono'): if(direccion == 'babor' or direccion == 'estribor'): print("Ahoy! capitán, una Macaraprono a "+direccion) elif(direccion == 'proa' or direccion == 'popa'): print("Ahoy! capitán, una Macaraprono por la "+direccion) elif(criatura == 'Pulpo'): if(direccion == 'babor' or direccion == 'estribor'): print("Ahoy! capitán, un Pulpo a "+direccion) elif(direccion == 'proa' or direccion == 'popa'): print("Ahoy! capitán, un Pulpo por la "+direccion) elif(criatura == 'Leviatanes'): if(direccion == 'babor' or direccion == 'estribor'): print("Ahoy! capitán, unos Leviatanes a "+direccion) elif(direccion == 'proa' or direccion == 'popa'): print("Ahoy! capitán, unos Leviatanes por la "+direccion) elif(criatura == 'Hidras'): if(direccion == 'babor' or direccion == 'estribor'): print("Ahoy! capitán, unas Hidras a "+direccion) elif(direccion == 'proa' or direccion == 'popa'): print("Ahoy! capitán, unas Hidras por la "+direccion)
false
e24920a841c579ae46d74a759d9148c858222ea4
johnson365/python
/Design Pattern/Observer.py
1,986
4.1875
4
"""Implementation of Observer pattern""" from abc import ABCMeta, abstractmethod class Subject: """The abstract class of Subject put all Observer object in a collection!""" def __init__(self): self.observers = [] def attachObserver(self, observer): """add a observer into observer collection""" self.observers.append(observer) def removeObserver(self, observer): """remove a observer from observer collection""" self.observers.remove(observer) def notify(self): """notify all observers when state changed""" for ob in self.observers: ob.updateState() class Observer: """The abstract class of Observer""" __metaclass__ = ABCMeta @abstractmethod def updateState(self):pass class ConcreteSubject(Subject): """The concrete class of subject""" def __init__(self): Subject.__init__(self) self.__subjectState = None def getSubjectState(self): return self.__subjectState def setSubjectState(self, state): self.__subjectState = state class ConcreteObserver(Observer): """ The concrete class of Observer""" def __init__(self, subject, name): self.__subject = subject self.__name = name self.__state = None def getSubject(self): return self.__subject def setSubject(self, subject): self.__subject = subject def updateState(self): """update state by subject`s state""" self.__state = self.__subject.getSubjectState() print "Observer%s `s new state is %s" % (self.__name, self.__state) if __name__ == '__main__': s = ConcreteSubject() x = ConcreteObserver(s, 'x') y = ConcreteObserver(s, 'Y') z = ConcreteObserver(s, 'z') s.attachObserver(x) s.attachObserver(y) s.attachObserver(z) s.setSubjectState("ABC") s.notify()
true
49e7315a2a6e91ade9a8a35d7be559f715f0cea4
MashinaSSokom/Geek
/Ashimov_Sultan_dz_2/task_2_4.py
436
4.15625
4
names = ['инженер-конструктор Игорь', 'главный бухгалтер МАРИНА', 'токарь высшего разряда нИКОЛАй', 'директор аэлита'] for name in names: temp = name.split() print(f'Привет, {temp[-1].capitalize()}!') print(f'Твоя должность {" ".join(temp[:-1])}?') #Решил не выкидывать должности и немного усложнить задание :)
false
d37eec249f9eae3f11d1eff5939199c62054ffaf
JSheldon3488/Daily_Coding_Problems
/Chapter6_Trees/6.3_Evaluate_Arithmetic_Tree.py
2,033
4.15625
4
""" Date: 7/7/20 6.3: Evaluate Arithmetic Tree """ class Node(): """ Node class used for making trees """ def __init__(self, val, left = None, right = None): self.val = val self.left = left self.right = right ''' Problem Statement: Suppose an arithmetic expression is given as a binary tree. each leaf is an integer and each internal node is one of +,-,*,/. Given the root of such a tree, write a function to evaluate it. Example: * + + 3 2 4 5 Should return 45. (3+2) * (4+5) in-order: [3, +, 2, *, 4, +, 5] pre-order: [*, +, 3, 2, +, 4, 5] ''' ''' My Solution ''' def evaluate(root: Node) -> int: # Base Case: if isinstance(root.val, int): return root.val # Recursive Case: elif root.val == '*': return evaluate(root.left) * evaluate(root.right) elif root.val == '+': return evaluate(root.left) + evaluate(root.right) elif root.val == '-': return evaluate(root.left) - evaluate(root.right) else: try: return evaluate(root.left)/evaluate(root.right) except ZeroDivisionError: return ZeroDivisionError ''' Book Solution ''' """ Same solution that I came up with. Note this is O(n) time and O(h) space complexity """ ''' Test Cases ''' def main(): assert evaluate(Node('*', left=Node('+', Node(3), Node(2)), right=Node('+', Node(4), Node(5)))) == 45 assert evaluate(Node('*', left=Node('+', Node(3), Node(2)), right=Node('+', Node(4), Node(5)))) != 35 assert evaluate(Node('*', left=Node('-', Node(3), Node(2)), right=Node('-', Node(4), Node(5)))) == -1 assert evaluate(Node('/', left=Node('+', Node(3), Node(2)), right=Node('-', Node(5), Node(5)))) == ZeroDivisionError if __name__ == '__main__': main() ''' Lessons Learned: * '''
true
4ec43707554a617f2211609ec94ab0fbc756e70f
JSheldon3488/Daily_Coding_Problems
/Chapter4_Stacks_and_Queues/Stack.py
1,565
4.21875
4
class Stack: """ A basic Stack class following "last in, first out" principle. Supports methods push, pop, peek, and size. The stack is initialized as empty. Attributes: Size: Keeps track of the size of the stack """ def __init__(self): """ Initializes the stack to an empty list with size 0 """ self.stack = [] self.size = 0 def __str__(self): """ Returns String representation of the stack. Top of stack is first element printed""" s = "Stack( " for i in range(self.size -1, -1, -1): s += str(self.stack[i]) if i != 0: s += " --> " s += " )" return s def push(self,data): """ Pushes 'data' onto the top of the stack (the back of the list) :param data: data to be pushed onto the stack """ self.stack.append(data) self.size += 1 def pop(self): """ Returns and removes the 'data' from the top of the stack :return: data from the top of the stack """ if self.size == 0: raise ValueError("The Stack is Empty") self.size -= 1 return self.stack.pop() def peek(self): """ Returns the 'data' from the top of the stack but does not remove the data. :return: 'data from the top of the stack """ if self.size == 0: raise ValueError("The Stack is Empty") return self.stack[-1]
true
ef6fa04462315f367b3d91186bbf2f3ed48fb559
JSheldon3488/Daily_Coding_Problems
/Chapter8_Tries/8.2_PrefixMapSum.py
2,066
4.25
4
""" Date: 7/26/20 8.2: Create PrefixMapSum Class """ ''' Problem Statement: Implement a PrefixMapSum class with the following methods: def insert(key: str, value: int) Set a given key's value in the map. If the key already exists overwrite the value. def sum(prefix: str) Return the sum of all values of keys that begin with a given prefix. Example: mapsum.insert("columnar", 3) assert mapsum.sum("col") == 3 mapsum.insert("column", 2) assert mapsum.sum("col") == 5 ''' from Trie import Trie, ENDS_HERE from collections import defaultdict ''' My Solution ''' class PrefixMapSum: def __init__(self): self._trie = Trie() self.values = defaultdict(int) def insert(self, key: str, value: int): self._trie.insert(key) self.values[key] = value def sum(self, prefix: sum): # Get all possible words with prefix words = self.complete_words(prefix, self._trie.find(prefix)) # Sum values from values dictionary for all possible words return sum(self.values[word] for word in words) def complete_words(self, prefix, prefix_dict: dict): words = [] for key, next_level in prefix_dict.items(): if key == ENDS_HERE: words.append(prefix) else: words.extend(self.complete_words(prefix + key, next_level)) return words ''' Book Solution ''' ''' Test Cases ''' def main(): mapsum = PrefixMapSum() mapsum.insert("columnar", 3) assert mapsum.sum("col") == 3 mapsum.insert("column", 2) assert mapsum.sum("col") == 5 if __name__ == '__main__': main() ''' Lessons Learned: * Using key.startswith(prefix) would allow us to do this without even using a trie and would make insertions fast but would do poorly with summation because it will check every single key in the dictionary * '''
true
608ed5c38e186df1ef955933bf6c77a3aa340ef1
ARON97/Desktop_CRUD
/backend.py
1,676
4.28125
4
import sqlite3 class Database: # constructor def __init__(self, db): self.conn = sqlite3.connect(db) self.cur = self.conn.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)") self.conn.commit() def insert(self, title, author, year, isbn): # The id is an autoincrement value so we will pass in null self.cur.execute("INSERT INTO book VALUES (NULL, ?, ?, ?, ?)", (title, author, year, isbn)) self.conn.commit() def view(self): # The id is an autoincrement value so we will pass in null self.cur.execute("SELECT * FROM book") rows = self.cur.fetchall() return rows # All search. The user will enter in a title or auther or isbn or year def search(self, title = "", author = "", year = "", isbn = ""): self.cur.execute("SELECT * FROM book WHERE title=? OR author=? OR year=? OR isbn=?", (title, author, year, isbn)) rows = self.cur.fetchall() return rows # Delete a record by selecting a record from the listbox def delete(self, id): self.cur.execute("DELETE FROM book WHERE id = ?", (id,)) # Note enter comma after id self.conn.commit() # Update a record by selecting a record from the listbox and display the record in the widget def update(self, id, title, author, year, isbn): self.cur.execute("UPDATE book SET title = ?, author = ?, year = ?, isbn = ? WHERE id = ?", (title, author, year, isbn, id)) self.conn.commit() # destructor def __del__(self): self.conn.close() #insert("The Earth", "John Doe", 1997, 225555852) #delete(3) # update(4, "The moon", "John Smith", 1917, 985557) # print(view()) # print(search(author="Aron Payle"))
true
67dac92e4e07eba726e5a200454f12b1656945e4
VittorLF/progr1ads
/Lista 5/Lista 5 Ex1.py
369
4.125
4
# 1 - Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem casoo valor seja inválido e continue pedindo até que o usuário informe um valor válido. while True: user = float(input('Insira um numero entre zero e dez: ')) if user >= 0 and user <= 10: print(user) break else: print('Informe um valor válido')
false
83b5a4195d0edbeb10c0693f7f68bb63d2430386
sun1day/leetcode
/lt_2020_6_16/square_root.py
1,182
4.4375
4
""" 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842...,   由于返回类型是整数,小数部分将被舍去。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sqrtx 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ def square_root(x: int) -> int: # todo pass 太耗时 # if x == 0: # return 0 # for i in range(1, x + 1): # if i ** 2 == 0: # return i # if i ** 2 < x < (i + 1) ** 2: # return i def inner(header, end, ident): middle = (header + end) // 2 if middle == header or middle ** 2 == ident: return middle if middle ** 2 > ident: return inner(header, middle, ident) return inner(middle, end, ident) if x in [0, 1]: return x return inner(0, x, x) if __name__ == '__main__': print(square_root(100))
false
35541f5ca6badb364ae278e121a7b82155188361
sun1day/leetcode
/lt_2020_4_20/shou_suo_cha_ru_wei_zi.py
1,186
4.125
4
""" 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 示例 2: 输入: [1,3,5,6], 2 输出: 1 示例 3: 输入: [1,3,5,6], 7 输出: 4 示例 4: 输入: [1,3,5,6], 0 输出: 0 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/search-insert-position 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List def solution(nums: List[int], target: int) -> int: for i, num in enumerate(nums): if num == target: return i if target < nums[0]: return 0 # 说明 不存在 for i in range(0, len(nums)): if i + 1 == len(nums): return i + 1 if nums[i] < target < nums[i + 1]: return i + 1 if __name__ == '__main__': print(solution([1, 3, 5, 6], 5)) # 2 print(solution([1, 3, 5, 6], 2)) # 1 print(solution([1, 3, 5, 6], 7)) # 4 print(solution([1, 3, 5, 6], 2)) # 1
false
5990428dbea6421d99b43c21c6c83c55f2617a59
matthewmuccio/Assessment1
/q1/run.py
1,969
4.28125
4
#!/usr/bin/env python3 import random # Helper function that gets the number of zeroes in the given list. def get_num_zeroes(x): num = 0 for i in x: if i == 0: num += 1 return num # Moves all the 0s in the list to the end while maintaining the order of the non-zero elements. def move_zeroes(x): length = len(x) # Length of the given list. num_zeroes = get_num_zeroes(x) # Gets the number of zeroes that must be moved. count = 0 # Counts the number of zeroes that have been moved to the end of the list. i = length - 1 # current index i is initially set to the last element's index. # Iterating through the list backward. while i >= 0: # If the current element is 0 and it is not in the correct place (at end of list). if x[i] == 0 and i <= length - num_zeroes: # Swap adjacent elements until the current element (0) is at end of list. while i < length - 1: temp = x[i] x[i] = x[i + 1] x[i + 1] = temp i += 1 # If the current index is at the last element's index, # we successfully moved the 0. if i == length - 1: count += 1 i -= 1 # If we have moved all zeroes to the end of the list we're done, break out of the loop. if count == num_zeroes: break return x # Returns the same list that was passed in as an argument (#in-place). # My alternate implementation of the function using list comprehensions (not in-place). #def move_zeroes(x): # return [not_zero for not_zero in x if not_zero != 0] + [zero for zero in x if zero == 0] # Tests if __name__ == "__main__": # Given test case. x = [0, 0, 1, 0, 3, 12] print("Given list:") print(x) print("Result:") print(move_zeroes(x)) print() # Random test case. lst = [0, 0] # Loads two zeroes into the list for simpler testing. for i in range(9): # Loads eight more random integers into the list. rand_num = random.randint(0, 25) lst.append(rand_num) print("Given list:") print(lst) print("Result:") print(move_zeroes(lst))
true
95ba120923b093a6af9636f643f12719e0dee77e
angelinka/programming4DA
/week5/lab5DatastrTuple.py
588
4.4375
4
#Program creates a tuple that stores the months of the year, from that tuple create #another tuple with just the summer months (May, June, July), print out the #summer months one at a time. #Author: Angelina B months = ("January", "February", "March", "April", "May", "June", "july", "August", "September", "October", "November", "December" ) # Slicing months to get 3 summer months in another tuple summerMonths = months[4:7] for month in summerMonths: print (month)
true
2bcf78b22555bc9db039525d2afb2fecae2fcce6
caoxiang104/algorithm
/data_structure/Linked_List/Singly_Linked_List.py
2,847
4.1875
4
# coding=utf-8 # 实现带哨兵的单链表 class LinkedList(object): class Node(object): def __init__(self, value, next_node): super(LinkedList.Node, self).__init__() self.value = value self.next = next_node def __str__(self): super(LinkedList.Node, self).__str__() return str(self.value) def __init__(self, *arg): super(LinkedList, self).__init__() self.nil = LinkedList.Node(None, None) self.nil.next = self.nil self.length = 0 for value in arg: self.append(value) def append(self, value): temp_node = self.nil node = LinkedList.Node(value, temp_node) while temp_node.next is not self.nil: temp_node = temp_node.next temp_node.next = node self.length += 1 return self.length def prepend(self, value): temp_node = self.nil node = LinkedList.Node(value, temp_node.next) temp_node.next = node self.length += 1 return self.length def insert(self, index, value): cur_node = self.nil cur_pos = 0 if index > self.size(): raise IndexError("Can't insert value beyond the list") while cur_pos < index: cur_node = cur_node.next cur_pos += 1 node = LinkedList.Node(value, cur_node.next) cur_node.next = node self.length += 1 return self.length def delete(self, value): cur_node = self.nil.next temp_node = self.nil while cur_node is not self.nil: if cur_node.value == value: break else: cur_node = cur_node.next temp_node = temp_node.next if cur_node is not self.nil: temp_node.next = cur_node.next self.length -= 1 return cur_node.value def search(self, value): cur_node = self.nil.next while cur_node is not self.nil and cur_node.value != value: cur_node = cur_node.next return cur_node.value def size(self): return self.length def __str__(self): super(LinkedList, self).__str__() cur_node = self.nil.next link_ = [] while cur_node is not self.nil: link_.append(str(cur_node)) cur_node = cur_node.next return '[' + ",".join(link_) + ']' def main(): link_ = LinkedList(2, 3, 5) print(link_) for i in range(10): link_.append(i) print(link_) link_ = LinkedList(1, 2, 3) for i in range(10): link_.prepend(i) print(link_) print(link_.size()) link_.insert(2, 100) print(link_) link_.delete(2) print(link_) print(link_.search(100)) if __name__ == '__main__': main()
true
62540e1e6192619838f134c1499907cbf03cf019
XuQiao/codestudy
/python/pythonSimple/list_comprehension.py
309
4.1875
4
listone = [2,3,4] listtwo = [2*i for i in listone if i>3] print (listtwo) def powersum(power, *args): '''Return the sum of each arguments raised to specified power''' total = 0 for i in args: total = total + pow(i,power) return total print (powersum(1,23,34)) print (powersum(2,10))
true
80fd1179076556a77d87ebe6aae78c2edd03ddf5
jhobaugh/password_generator
/password_generator.py
822
4.1875
4
# import random, define a base string for password, name, and characters in password import random password = "" name = "" chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!#$%&" # while loop to ensure a password is outputted while password == "": # limit input limit = int(input("Thanks for using python password generator!\n" "How many characters would you like in your password? (minimum of 6): ")) # name input name = (input("What would you like to name the password?: ")) # character limiter if limit < 6: print("The minimum password length is 6") else: # character selector for c in range(limit): password += random.choice(chars) # print statement print(name + "\n" + password)
true
49a2f2e2c4b0da26013b635c66045373ad9e2654
xchmiao/Leetcode
/Tree/145. Binary Tree Postorder Traversal.py
2,366
4.15625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ## Solution-1 ''' 1.1 Create an empty stack 2.1 Do following while root is not NULL a) Push root's right child and then root to stack. b) Set root as root's left child. 2.2 Pop an item from stack and set it as root. a) If the popped item has a right child and the right child is at top of stack, then remove the right child from stack, push the root back and set root as root's right child. b) Else print root's data and set root as NULL. 2.3 Repeat steps 2.1 and 2.2 while stack is not empty. ''' class Solution(object): def peekStack(self, stack): if len(stack) > 0: return stack[-1] else: return None def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] else: result = [] stack_nodes = [] node = root while True: while node: if node.right: stack_nodes.append(node.right) stack_nodes.append(node) node = node.left node = stack_nodes.pop() top_node = self.peekStack(stack_nodes) if (node.right == top_node) and (node.right is not None): stack_nodes.pop() stack_nodes.append(node) node = node.right else: result.append(node.val) node = None if len(stack_nodes) == 0: break return result ## Solution-2 class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] stack, output = [root, ], [] while stack: root = stack.pop() output.append(root.val) if root.left is not None: stack.append(root.left) if root.right is not None: stack.append(root.right) return output[::-1]
true
ec8e857911afcc4b2e7c74377913639f5a4b964c
zheguang/fun-problems
/longest_common_sequence.py
1,503
4.21875
4
#!/usr/bin/env python # Longest common sequence # Given two strings, the task is to find the longest common sequence of letters among them. # The letters do not have to be next to each other in the original string. # E.g. C D E F G A B # D E G B R T Z # output: D E G B # # It is interesting to compare this problem to longest increasing sequence. # The subproblem search space is different. # In longest increasing sequence, the search space is the LIS[i:-1] for all i. # But for longest common sequence, the search space is similat to the edit distance # i.e. LCS[0:-1]. # To determine the proper search space, it is important to know what the final optimal # answer might be from. memo = {} def longest_common_sequence(xs, ys): if (tuple(xs), tuple(ys)) in memo: lcs = memo[(tuple(xs), tuple(ys))] else: # can't use xs == [] comparison because string xs and list xs is different in python. if len(xs) == 0 or len(ys) == 0: lcs = [] else: lcs = max([ longest_common_sequence(xs[:-1], ys), longest_common_sequence(xs, ys[:-1]), longest_common_sequence(xs[:-1], ys[:-1]) + [xs[-1]] if xs[-1] == ys[-1] else [] ], key=lambda xs: len(xs)) memo[(tuple(xs), tuple(ys))] = lcs return lcs def main(): xs = 'helloworld' ys = 'foobarbusdust' lcs = longest_common_sequence(xs, ys) print(lcs) if __name__ == '__main__': main()
true
62715dc8bbb9f658cb9f6db7318614dc4843b630
trianglesis/myRefferences
/languages/python/datetime/working_hours.py
728
4.125
4
import datetime now = datetime.datetime.now().replace(second=0, microsecond=0) morning = now.replace(hour=7) evening = now.replace(hour=19) print(f'Dates: {morning} - {now} - {evening}') print(f'now > morning = {now > morning}') print(f'now < morning = {now < morning}') print(f'morning > now = {morning > now}') print(f'morning < now = {morning < now}') print(f'now > evening = {now > evening}') print(f'now < evening = {now < evening}') print(f'evening > now = {evening > now}') print(f'evening < now = {evening < now}') print(f'now - evening = {evening - now}') # 17 hours day end = 0:00:00, 18 = 1:00:00 if now > morning and now < evening: print("Staring working hours!") else: print("Working hours no more!")
false
a2da9360fd828ab92db4f8f4b7d13c25327309e4
ruslanfun/Python_learning-
/if_elif3.py
360
4.25
4
# Ask the user to enter a number between 10 and 20 (inclusive). # If they enter a number within this range, display the message “Thank you”, # otherwise display the message “Incorrect answer” number = int(input("enter a number between 10 and 20: ")) if number >= 10 and number <= 20: print('thank you') else: print('incorrect answer')
true
1223e8cd384e5be4bf36329a22e85c3b538522b7
Priya-Mentorship/Python4Everybody
/arrays/adding.py
427
4.1875
4
import array as arr numbers = arr.array('i', [1, 2, 3, 5, 7, 10]) # changing first element numbers[0] = 34 print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10]) # changing 3rd to 5th element numbers[2:5] = arr.array('i', [4, 6, 8]) print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10]) numbers.append(6) numbers.insert(5,0) numbers2 = arr.array('i', [10,20,20]) numbers.extend(numbers2) print(numbers)
true
8f6d3c5ab8ca31a8aaba3fb47e7234f0fa0c95c6
onuratmaca/Data-Analysis-w-Python-2020
/compliment.py
583
4.6875
5
#!/usr/bin/env python3 """ Exercise 2 (compliment) Fill in the stub solution to make the program work as follows. The program should ask the user for an input, and the print an answer as the examples below show. What country are you from? Sweden I have heard that Sweden is a beautiful country. What country are you from? Chile I have heard that Chile is a beautiful country. """ def main(): # Enter you solution here country = input("What country are you from? ") print(f"I have heard that {country} is a beautiful country.") if __name__ == "__main__": main()
true
bb24c91663b4d3b52360a20fe35942c92daf7904
erarpit/python_practise_code
/secondprogram.py
324
4.125
4
print('A program for print list function') list = [ 2,4,5,5,5,6,'hello','ratio' ] print(list) print(list[4]) list.remove('hello') print(list) list.append('my') print(list) print(list[3:8]) newlist = list.copy() print(newlist) print(newlist.count(6)) print(newlist) list.index('my') print("printlist:",list)
true
4c9449f99ddf27fc6ae1ec687531231321e9f70d
luc14/coding_practice
/fizzbuzz.py
1,310
4.28125
4
'''generates, translates and prints Fibonacci numbers ''' def generate_fibonacci(n): '''yields n fibonacci numbers. ''' for i in range(n): if i < 2: yield 1 continue if i == 2: f1, f2 = 1, 1 f1, f2 = f2, f1+f2 yield f2 def is_prime(n): '''returns True if n is a prime; otherwise returns False. ''' if n == 1: return False for i in range(2, int(n**0.5)+1): if n%i == 0: return False return True def translate_fibonacci(f): ''' Args: f is a positive integer. Returns: "Buzz" when f is divisible by 3 but not by 15. "Fizz" when f is divisible by 5 but not by 15. "FizzBuzz" when f is divisible by 15. "BuzzFizz" when f is prime. the value f otherwise. ''' if f%15 == 0: return "FizzBuzz" if f%3 == 0: return "Buzz" if f%5 == 0: return "Fizz" if is_prime(f): return "BuzzFizz" return f def print_result(n, where=None): '''prints the first n translated fibonacci numbers according to translate_fibonacci function. prints the result to file-object if where is not None. ''' for f in generate_fibonacci(n): result = translate_fibonacci(f) print(result, file=where)
false
9573ba807776f8906f1da9e66a0f5c9ec2d6979f
blackviking27/Projects
/text_based_adventure.py
2,162
4.25
4
# text based adventure game print("Welcome to text adventure") print("You can move in two directions left and right and explore the rooms") print("but you cannot go beyond the rooms since it is not safe for you as of now") print("r or right to go in right direction") print("l or left to go in left direction") room=[1,2,3,4,5,6] a = room[0] #initial room number i=1 while i>0: try: def room(n): #defining each room with its own proprties print("You are in room number",n) if n==1: print("This a magical room full of magic") elif n==2: print("This room is full of nightmares all around the world") elif n==3: print("This room belongs to the wisest man on the planet") elif n==4: print("This room belongs to the strongest man on the planet") elif n==5: print("This room belongs to someone unknown for centuries") elif n==6: print("This room is out of bounds for people") def left(): l=globals()['a']-1 if l>=1: room(l) else: print("There is no room in that direction") def right(): r =globals()['a']+1 if r<=6: room(r) else : print("There is no room in that direction") def main(): dir = input("Which direction you want to move") if dir == 'right' or dir == 'r': right() elif dir == 'left' or dir == 'l': left() else: print("Enter a valid direction") main() q=input("If you want to quit you can enter q or exit if not then press enter") if q == 'q' or q == "exit": break except Exception as e: pass i+=1 print("Thank you for playing the game") print("Hope to see you again")
true
e3e5eeb60adb1ad74935c816db64847c71e7bf98
khadley312/NW-Idrive
/Exercise Files/Ch2/variables_start.py
564
4.3125
4
# # Example file for variables # # Declare a variable and initialize it f=0 print(f) # # re-declaring the variable works f="abc" print(f) # # ERROR: variables of different types cannot be combined print("this is a string" + str(123)) # Global vs. local variables in functions def someFunction(): global f #this makes the f variable in this function global to outside of the function f="def" print(f) someFunction() print(f) del f #this deletes that global variable causing the next line to create an error in the code since f is deleted print(f)
true
2e003018aa4a1511f5cb3a1e18202e5c2e47b0b5
marsbarmania/ghub_py
/codingbat/Logic-1/near_ten.py
464
4.125
4
# -*- coding: utf-8 -*- # Given a non-negative number "num", # return True if num is within 2 of a multiple of 10. # Note: (a % b) is the remainder of dividing a by b, # so (7 % 5) is 2. def near_ten(num): remainder = num while remainder > 10: remainder %= 10 # print "remainder: ",remainder return True if remainder <= 2 or remainder >= 8 else False print near_ten(12) # True print near_ten(17) # False print near_ten(19) # True print near_ten(29)
true
155580584152bc4acf0d52f76e7ee6491b4739dc
ananyapoc/CPSC230
/CPSC230/APochiraju_2/newvolume.py
459
4.3125
4
#this is to calculate the volume of a cylinder import math #asking the user for inputs r=int(input("give me a length for the radius of the cylinder")) #stating conditions for radius if(r==0): print("please do not give zero") elif(r!=0): h=int(input("give me a length for the height of the cylinder")) #stating conditions for height if(h==0): print("please do not give zero") elif(h!=0): print((r*r)*h*math.pi) #calculating the volume using pi
true
39d4e818838bb596e46ed641193a64392a3f25e0
barbmarques/HackerRank-Python-Practice
/Basic_Python_Challenges.py
1,285
4.4375
4
# Print Hello, World! print("Hello, World!") # Given an integer,n, perform the following conditional actions: -- If n is odd, print Weird -- If n is even and in the inclusive range of 2 to 5, print Not Weird -- If n is even and in the inclusive range of 6 to 20, print Weird -- If n is even and greater than 20, print Not Weird if n%2 == 1: print('Weird') elif n >= 2 and n <= 5: print('Not Weird') elif n >= 6 and n <=20: print('Weird') else: print('Not Weird') # The provided code stub reads two integers from STDIN, a and. # Add code to print three lines where: # 1. The first line contains the sum of the two numbers. # 2. The second line contains the difference of the two numbers # 3. The third line contains the product of the two numbers print(a + b) print(a - b) print(a * b) # The provided code stub reads two integers, a and b, from STDIN. # Add logic to print two lines. The first line should contain the result of integer division a//b # The second line should contain the result of float division, a/b # No rounding or formatting is necessary. print(a//b) print(a/b) # The provided code stub reads an integer, n, from STDIN. # For all non-negative integers i<n, print i squared. i = 0 while i < n: print(i ** 2) i += 1
true
d0bf27b5664a52879314a298c25e0d17e1e613d5
luizfelipe-on/Python_intro
/Exercicios/Aula8/exercicio5_aula8.py
1,410
4.1875
4
class Ponto: """ Cria um Ponto com coordenadas x, y """ def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "({0}, {1})".format(self.x, self.y) class Retangulo: """ Cria um Retângulo com altura, largura e vértices """ def __init__(self, largura=0, altura=0, canto=Ponto(0,0)): self.largura = largura self.altura = altura self.canto = canto def vertices(self): v1 = (self.canto.x, self.canto.y) v2 = (self.canto.x + self.largura, self.canto.y) v3 = (self.canto.x, self.canto.y + self.altura) v4 = (self.canto.x + self.largura, self.canto.y + self.altura) return v1, v2, v3, v4 def __str__(self): return "({0}, {1}, {2})".format(self.largura, self.altura, self.canto) # Solicitação de um ponto qualquer ao usuário: p = Ponto() p.x = int(input('coordenada x do ponto: ')) p.y = int(input('coordenada y do ponto: ')) # Solicitação da largura e da altura do retângulo ao usuário, usando o ponto acima como o canto do retângulo: ret = Retangulo() ret.largura = int(input('largura desejada do retângulo: ')) ret.altura = int(input('altura desejada do retângulo: ')) ret.canto = p # Definição dos vértices do retângulo a partir do ponto e das dimensões do retângulo: vert = ret.vertices() print('os vértices do retângulo são', vert)
false
bf747305bacb8c2e43dbe99c1cbc3ac6177fc808
luizfelipe-on/Python_intro
/Exercicios/Aula9_Listas/exercicio1a_listas.py
438
4.15625
4
# Função modificadora que dobra o valor dos elementos de uma lista: def dobrar_elementos(lista): clone_lista = lista[:] for (i, valor) in enumerate(clone_lista): valor_dobrado = 2 * valor clone_lista[i] = valor_dobrado print('lista de entrada:', lista) print('lista dobrada:', clone_lista) # Escolhendo uma lista de entrada e aplicando a função: minha_lista = [2, 4, 6] dobrar_elementos(minha_lista)
false
08d1d54fb84923904a94599150c528974fe86b3c
adid1d4/timer
/timer.py
1,114
4.15625
4
''' what should it do? it should decrease the seconds on the same line after the seconds go to 0, it should decrease a minute and get 59 on the seconds after this the iteration should repeat itself for the seconds when the minutes get to 0, the hour should decrease by 1, the minutes to 59, seconds to 59 and the iteration for the seconds should repeat itself. ''' import time import os import sys print "Working here, take another computer." print "It will show how to terminate after the time is done" print "I mean If I don't come by the timer eta" h = 2 m = 1 s = 5 # if the time given is negative or not wanted if s > 59 or m>59 or m<0 or s<0 or h<0: print "error. Please type the correct time." sys.exit(0) # the main idea while h>-1: print str(h)+':'+str(m)+':'+str(s) os.system('clear') if -1<s: s = s-1 time.sleep(1) if s==-1: m = m-1 if m == -1: h = h-1 if h==0 and s==0: m = 0 s - 59 m=59 s=59 s = 59
true
6a3afca3067a704a06be3892fdc773b16054bc69
njounkengdaizem/eliteprogrammerclub
/capitalize.py
962
4.34375
4
# write a simple program that takes a sentence as input, # returns the capitalized for of the sentence. ############################################################# result = "" # an empty string to hold the resulting string sentence = input("Enter a word: ") # gets inputs from the user sentence = sentence.capitalize() sentence_list = sentence.split('.') list = [] for word in sentence_list: list.append(word.strip()) # takes out every whitespace between splited sentence sentence = list for word in sentence: # here goes the magic result += word[0].upper() + word[1:] + '. ' # converts the first letter of the split string to uppercase print(result[:]) # then concatenates the remaining letters and adds a # full stop and empty space between the words.
true
c24e526cf07e7c920a5c17e277d1730235438d95
vvp-lab/GB-VVP
/lesson1/task6.py
1,135
4.40625
4
# 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который результат спортсмена составит не менее b километров. Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. a = float(input("Сколько км пробежит спортсмен в первый день: ")) b = float(input("Какая цель в км: ")) d = 1 print("{}-ый день:{}".format(d, round(a,2))); while a < b: a = a * 1.1 d = d + 1 print("{}-ый день:{}".format(d, round(a,2))); print("Ответ: на {}-й день спортсмен достиг результата — не менее {} км.".format(d, int(a)));
false
532d97e98be271d59021622e0273c57447a50cc9
vvp-lab/GB-VVP
/lesson2/task2.py
945
4.1875
4
# 2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). text = input('Введи список значений и раздели значения запятой: ') list = text.split(',') cnt = len(list) - 1 ind = 0 for i in list: if ind < cnt and (ind % 2) == 0: list[ind], list[ind + 1] = list[ind + 1], list[ind] print(list) ind += 1 # помоему сделано кривовато, но работает. интересно будет послушать решение потом
false
43f899162d4df281c17ff7cb00f75a6e0506483f
vvp-lab/GB-VVP
/lesson8/task2.py
1,100
4.21875
4
#Lesson 8 task 2 """ Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. """ class OopsDivisionByZero(Exception): def __init__(self, txt): self.txt = txt try: devidend = int(input('Введите число, которое собираетесь разделить: ')) division = int(input('Введите число, НА которое собираетесь разделить: ')) if not division: raise OopsDivisionByZero('Oops! division by zero') print(f'Результат {devidend/division}') except ValueError: print('вы ввели не числа') except OopsDivisionByZero as error: print(error)
false
7d2ca4711e013e5493e0532ad89d5c10380d73c3
mikestrain/PythonGA
/firstPythonScript.py
349
4.28125
4
print("this should be printed out") #this is a comment # print("The number of students is "+str(number_of_students)) # print(3**3) number_of_students = 6 number_of_classes = 10 total = number_of_students + number_of_classes print('number of students + number of classes = ' + str(total)) print('number of students + number of classes =', total)
true
725e62fb19f409922b89b8cbfc94669976130255
17c23039/The-Unbeatable-Game
/main.py
2,939
4.375
4
from time import sleep import random score = int(0) print("Rock Paper Scissors, Python edition! This project is to see how complicated and advanced I can make a RPS game.") sleep(3) print("When it is your turn, you will have three options. [R]ock, [P]aper and [S]cissors! For a loss you will lose a point, a tie it will stay the same, and a win will add a point.") sleep(5) print("Let's begin.") while score < 5 : rpschoice = input("Rock, paper, or scissors? R/P/S. ") sleep(1) print("Rock,") sleep(1) print("Paper,") sleep(1) print("Scissors,") sleep(1) print("Shoot!") sleep(1) aichoice = random.randint(1, 1) if aichoice == 1 : print("Rock!") sleep(1) if rpschoice == "R" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "r" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "P" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "p" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "S" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "s" : print("I win!") score = score - 1 print(f"Your score is {score}.") else : print("Invalid option!") elif aichoice == 2 : print("Paper!") sleep(1) if rpschoice == "R" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "r" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "P" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "p" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "S" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "s" : print("You win!") score = score + 1 print(f"Your score is {score}.") else : print("Invalid option!") elif aichoice == 3 : print("Scissors!") sleep(1) if rpschoice == "R" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "r" : print("You win!") score = score + 1 print(f"Your score is {score}.") elif rpschoice == "P" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "p" : print("I win!") score = score - 1 print(f"Your score is {score}.") elif rpschoice == "S" : print("Tie!") print(f"Your score is {score}.") elif rpschoice == "s" : print("Tie!") print(f"Your score is {score}.") sleep(3) print("You have reached 5 points! Congrats, you win!") sleep(3) print("Oh? You stayed?") sleep(1) print("Right, let's move on.") sleep(1) import coinflip
true
c92a73c69f718e8cf44b3ea989ef34a401513bc1
ArtemKhmyrov/Python
/Циклы3-12.py
1,098
4.125
4
n = int(input("Введите размерность массива NxN: "))#ввод X = int(input("Введите X: "))#ввод a = []#создаем пустой список for i in range(n):#генерируем b = []#создаем временную переменную for j in range(n):#генерируем столбец x = input()#вводим столбец b.append(x)#заносим в список a.append(b)#заносим в список for i in range(n):#генерируем массив if i % 2 != 0:#условие на нечетный столбец начиная нумерацию с нуля for j in range(n):#генерируем a[j][i] = X#заменяем на этот столбец print("\n")#разделитель for i in range(n):#генерируем цикл s = ""#создаем пустую переменную for j in range(n):#генерируем s += str(a[i][j]) + " "#заносим в нашу переменную print(s)#вывод
false
a95825d0e3dc02402740bfaf5edb01235682e24a
talhatepe/pyhton-lectures
/week1/hw1.py
686
4.28125
4
while True: def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("Select operation.") choice = input("Enter choice('+' '-' '/' '*'):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '+': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '-': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '/': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '*': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input!")
false
79b98689566b207db2031eb5b883f6d1a78b9dd3
siyer13/Python
/hacker_rank/list_commands.py
1,357
4.1875
4
# https://www.hackerrank.com/challenges/python-lists/problem my_list = [] def insert(lst, a, e): i = int(a) lst.insert(i, e) return lst def append(lst, e): lst.append(e) return lst def sort(lst): lst.sort() return lst def print_list(lst): print(lst) def remove(lst, e): lst.remove(e) return lst def pop(lst): lst.pop() return lst def reverse(lst): lst.reverse() return lst if __name__ == '__main__': print("Enter range of commands: ") n = int(input()) commands = [] for i in range(n): print("Enter command :") cmd = input() commands.append(cmd) print("List of Commands", str(commands)) for c in commands: if 'insert' in c: cmds = c.split(" ") my_list = insert(my_list, cmds[1], cmds[2]) elif 'remove' in c: cmds = c.split(" ") my_list = remove(my_list, cmds[1]) elif 'append' in c: cmds = c.split(" ") my_list = append(my_list, cmds[1]) elif 'sort' in c: my_list = sort(my_list) elif 'pop' in c: my_list = pop(my_list) elif 'reverse' in c: my_list = reverse(my_list) elif 'print' in c: print_list(my_list) else: print("Not a List command")
false
7250d2b24e69dce512edb4f99cb2710e770c1d80
buggy213/ML-120_Materials
/Unit-035/traditional_five_starter.py
2,620
4.1875
4
import random import sys # We will be using the following encoding for rock, paper, scissors, lizard, and Spock: # Rock = 0 # Paper = 1 # Scissors = 2 # Lizard = 3 # Spock = 4 # # Fill in the below method with the rules of the game. # determineWinner is a structure called a method. The code in the method will run every time it is called. def determineWinner(userInput, computerInput): if(userInput == 0): if(computerInput == 0): print("Rock against rock! It's a tie!") elif(computerInput == 1): print("Paper beats rock! You lose!") elif(computerInput == 2): print("Rock beats scissors! You win!") # TODO: finish this if statement elif(userInput == 1): if(computerInput == 0): print("Paper beats rock! You win!") elif(computerInput == 1): print("Paper against paper! It's a tie!") elif(computerInput == 2): print("Scissors beats paper! You lose!") # TODO: finish this if statement elif(userInput == 2): if(computerInput == 0): print("Rock beats scissors! You lose!") elif(computerInput == 1): print("Scissors beats paper! You win!") elif(computerInput == 2): print("Scissors against scissors! You win!") # TODO: finish this if statement #TODO: add cases for userInput == 3, 4 #The main part of our program. Everything below here will run when we press the play button. playing = True while(playing): # Step 1: Get the user input userInput = int(input("\nEnter rock (0), paper (1), scissors (2), lizard (3), or Spock(4)\n")) # Step 2: Making sure that the user inputted a correct value if(userInput < 0 or userInput > 4): print("Please input 0, 1, 2, 3, or 4.") continue # Step 3: TODO: Finish the statement below, using a method from Python's random API. computerInput should be between 0 and 2. computerInput = random.randint(0, 4) # Step 4: Printing out the computer's choice of rock, paper, or scissors if(computerInput == 0): print("Computer chose rock.") elif(computerInput == 1): print("Computer chose paper.") elif(computerInput == 2): print("Computer chose scissors.") elif(computerInput == 3): print("Computer chose lizard.") elif(computerInput == 4): print("Computer chose Spock.") else: print("Invalid input from computer: " + computerInput) continue # Step 5: Calling the determineWinner method here determineWinner(userInput, computerInput) # Step 6: Seeing if the user would like to play the game again playAgain = input("\nPlay again? [y or n]\n") if(playAgain == "n"): playing = False
true
ac65076020ab2a9aa50ee4ea7f31679a90cdf949
The-SS/parallel_python_test
/parallel_py_test.py
2,517
4.25
4
# Author: # Sleiman Safaoui # Github: # The-SS # Email: # snsafaoui@gmail.com # sleiman.safaoui@utdallas.edu # # Demonstrates how to use the multiprocessing.Process python function to run several instances of a function in parallel # The script runs the same number of instance of the function in series and parallel and compare the execution time # Note: Running a small number of instance will not demonstrate the advantages of parallel processing # from __future__ import print_function import multiprocessing as mp import time def function1(num1, num2): # function to run multiple instances of sum1 = 0 if num1 < num2: for i in range(num2 - num1): sum1 += 1 elif num2 < num1: for i in range(num1 - num2): sum1 += 1 else: sum1 = 0 print('returning: ', sum1) return sum1 def run_parallel_instances(number_of_instances_to_run): ''' runs several instances of function1 in parallel ''' cpu_count = mp.cpu_count() # get number of CPUs available print(cpu_count, ' available. Will use all of them') start_time = time.time() # for timing all_events = [] for count in range(1, number_of_instances_to_run): event = mp.Process(target=function1, args=(1, (count * count) ** 3)) # start a process for each function (target takes function name and args is the arguments to pass) event.start() # start the function but don't wait for it to finish all_events.append(event) # store handle for the process for e in all_events: e.join() # join the parallel threads end_time = time.time() print('Ran ', number_of_instances_to_run, 'parallel instances') print('Finished Parallel processes in: ', end_time - start_time) return end_time - start_time def run_sequential_instances(number_of_instances_to_run): ''' runs several instances of function1 sequentially ''' start_time = time.time() for count in range(1, number_of_instances_to_run): function1(1, (count * count) ** 3) end_time = time.time() print('Ran ', number_of_instances_to_run, 'sequential instances') print('Finished Sequential processes in: ', end_time - start_time) return end_time - start_time if __name__ == "__main__": number_of_instances_to_run = 20 s_time = run_sequential_instances(number_of_instances_to_run) p_time = run_parallel_instances(number_of_instances_to_run) print('Sequential time: ', s_time) print('Parallel time: ', p_time)
true
ce8c2b43b52665cb4c391dd30b8b088a7192916c
nicholasinatel/Python-Snippets
/00 - Basico/04_ObjectsInMemory.py
832
4.34375
4
# Objetos e Referencias Na Memoria # Em Python Strings Sao Imutaveis # Portanto a && b estao apontando para o mesmo bloco de memoria a = "banana" b = "banana" test = a is b # Retorna True Por Estar Apontando para o mesmo bloco de memoria ja que strings sao imutaveis print(test) #__________________________________ d = [3,4,5] c = [3,4,5] test = d is c print(test) # Nesse caso os objetos sao diferentes portanto retorna false test = d == c print(test) # o sinal == refere-se ao conteudo dos objetos portanto iguais e retorna TRUE #______________________________________________ # Lista De Listas origlist = [45, 76, 34, 55] listaDelistas = [origlist] * 3 print(listaDelistas) origlist[1] = 99 # Altera no objeto origlist print(listaDelistas) # Alterou 3 objetos em listaDelistas pois apontam para o mesmo objeto de origlist
false
a6bda81a2698b6e44e5a693e4b9c4797e481949a
lsifang/python
/python变量/python基础_集合交并.py
743
4.125
4
#--------------------# # 1、set.intersection(otherset) 注意注意:与&运算符一样&&&&&&& # 另外:返回的交际集合与最前边的集合类型一样如可变或不可变 #新知识:Intersection()可与其他可迭代对象起作用如字符串\元组\列表.注意的是把这些可迭代对象先转换为集合在进行运算 # & # & # & # 2、set.intersectionupdate(otherset)...把交集付给原集合(set) s1={1,2,3,4,5} s2={4,5,8,6,12} s=s1.intersection(s2) s3=s1 & s2 print(s) print(s3) #=============并集==============# # 1、set.union(otherset) # 2、符号 | # 3、set.update(otherset) #============差集============# # 1、set.difference(otherset) #2、符号 - 减号 # 3、set.difference_update(otherset)
false
f00e5943faeff177c285ca990e8f6a51be585ec3
manickaa/CodeBreakersCode
/Recursion/fibonacci.py
544
4.125
4
def fibonacciMemo(n, fib_dict): if n in fib_dict: return fib_dict[n] else: result = fibonacciMemo(n-1, fib_dict) + fibonacciMemo(n-2, fib_dict) fib_dict[n] = result return result def fibonacciBottomUp(n): dp = [0] * (n+1) dp[0] = 1 dp[1] = 1 for i in range(2, n+1): dp[i] = dp[i-1] + dp[i-2] return dp[-1] #nth index if __name__ == '__main__': fib_dict = {0:1,1:1} for i in range(2,12): print(fibonacciMemo(i, fib_dict)) print(fibonacciBottomUp(i))
false
21dc4be25dccbeef4651870eee09042c189427be
paulyun/python
/Schoolwork/Python/To Be Graded/Project3/TestScoreAverage.py
707
4.21875
4
#Test Score Average #Paul_Yun CS_902 Spring 2016 test_score_one = float(input("Enter your first test score")) test_score_two = float(input("Enter your second test score")) test_score_three = float(input("Enter your three test score")) test_score_average = (test_score_one + test_score_two + test_score_three) / 3 if (test_score_average>=90): print("You received an A") elif (test_score_average>=80): print("You received an B") elif (test_score_average>=70): print("You received an C") elif (test_score_average>=60): print("You received an F") elif (test_score_average>=50): print("You received an F") elif (test_score_average<=50): print("You received an F")
false
cef145f7edee15add71fd819ba64d39c7cb2f052
paulyun/python
/Schoolwork/Python/In Class Projects/3.10.2016/InClassActivity_3.10.2016.py
390
4.1875
4
#In class Activity for 3/10/2016 totalTime = int(input ("Enter a time in seconds")) resultMinutes = int(totalTime / 60) #this function divides the users totaltime by 60 to get the minute value resultSeconds = totalTime % 60 #this function gets the remainder value of the totaltime divided by 60 to get the remaining seconds value print (resultMinutes,"Minutes", resultSeconds,"Seconds")
true
27e0fcf49ea15c5bccf24a5858c85809fe5f022e
paulyun/python
/Schoolwork/Python/In Class Projects/5.17.2016/Palindrome.py
268
4.21875
4
def isPalindrome(): word = input("Please enter a word to see if it is Palindrome") reverse = "" for letter in range(len(word)-1, -1, -1): #range(start, stop, sequence) reverse+=word[letter] return reverse == word print(isPalindrome())
true
1ac8cbf4abb9d670f1e38bb7cfb706f0f8326308
Saksham-Bhardwaj/Password-Validation
/ValidationModule.py
1,105
4.25
4
#regex module import re #function to validate each password input def checkPass(str): if(len(str)<6 or len(str)>12): print(str + " Failure password must be 6-12 characters.\n") return if not re.search("[a-z]", str): print(str + " Failure password must contain at least one letter from a-z \n") return if not re.search("[A-Z]", str): print(str + " Failure password must contain at least one letter from A-Z \n") return if not re.search("[0-9]", str): print(str + " Failure password must contain at least one number 0-9 \n") return if not re.search("[*$_#=@]", str): print(str + " Failure password must contain at least one letter from *$_#=@! \n") return if re.search("[%!)(]", str): print(str + " Failure password cannot contain %!)( \n") return print(str+" Success\n") return #main function if __name__ == '__main__': password = input("Enter Password: ") arr = password.split(',') print("\n") for i in arr: checkPass(i)
true
2505d32f0cea8d1d6813edfcf2d87973e8524b77
IMDCGP105-1819/text-adventure-Barker678
/Player.py
1,132
4.25
4
class Player(object): #we create a Player class that affects the inventory of the player, the players name and given direction to the player. def __init__ (self): self.Player = Player self.Name = "" #empty - for the players name self.inventory = [] #we define the inventory/we need it for the items def getname (self): return self.Name def setname (self, newname): #the name of the player will be the same in the whole game self.Name = newname def givedirections (self): #the directions of the game print ("Type the direction you want to walk.") print ("north") print("south") print ("east") print ("west") # when we go to a certain place, we add a item to the inventory def addItem (self, itemtoadd): # check to see if player already has item if itemtoadd in self.inventory: print ("There is nothing else in this room that can help.") else: # add item to player inventory self.inventory.append(itemtoadd) print(self.inventory)
true
112ead1004333cd0b246109dd25103e7e579820b
SpadinaRoad/Python_by_Examples
/Example_114/Example_114.py
1,019
4.15625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_114 # $ python3 Example_114.py # $ python3 Example_114.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 114 Using the Books.csv file, ask the user to enter a starting year and an end year. Display all books released between those two years. """ import csv print(__doc__) start_year = int(input('Enter the start year : ')) print(f'The input for the start year : {start_year}') print() end_year = int(input('Enter the end year : ')) print(f'The input for the end year : {end_year}') print() filename = "Books.csv" with open(filename, 'r') as fo: reader = csv.reader(fo, delimiter=',') for line in reader : try : year = int(line[2]) if year in range(start_year, end_year) : print(f'"{line[0]}" by {line[1]} published in {line[2]}') except : pass print()
true
67e75bf152ecf46e74dfd00fcdfc7fa44523f85c
SpadinaRoad/Python_by_Examples
/Example_035/Example_035.py
599
4.125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_035 # $ python3 Example_035.py # $ python3 Example_035.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 035 Ask the user to enter their name and then display their name three times. """ print(__doc__) name = '' while name != 'x' : name = input('Enter your name : ') print() print(f'The input for your name : {name}.') if name != 'x' : print(name * 3) print()
true
af64d3f5ecf4e84e40a4d58eeaf5112f12bf5595
SpadinaRoad/Python_by_Examples
/Example_058/Example_058.py
1,125
4.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_058 # $ python3 Example_058.py # $ python3 Example_058.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 058 Make a maths quiz that asks five questions by randomly generating two whole numbers to make the question (e.g. [num1] + [num2]). Ask the user to enter the answer. If they get it right add a point to their score. At the end of the quiz, tell them how many they got correct out of five. """ import random print(__doc__) score = 0 count = 0 while count < 5 : num_1 = random.randint(0,20) num_2 = random.randint(0,20) sum = num_1 + num_2 answer = int(input(f'What is the sum of {num_1} and {num_2}? ')) print(f'The input for the answer is {answer}.') print(f'The sum of {num_1} and {num_2} is {sum}.') if answer == sum : print(f'Your answer is correct.') score += 1 else : print('Wrong answer.') count += 1 print() print(f'Your score is {score} out of 5.')
true
17110747677a3be407ce36d3a27a5d415d7d9432
SpadinaRoad/Python_by_Examples
/Example_022/Example_022.py
870
4.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_022 # $ python3 Example_022.py # $ python3 Example_022.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 022 Ask the user to enter their first name and surname in lower case. Change the case to title case and join them together. Display the finished result. """ print(__doc__) fname = '' while fname != 'x' : fname = input('What is your first name? ') if fname != 'x' : lname = input('What is your last name? ') print() print(f'Input for first name : {fname}') print(f'Input for last name : {lname}') fname = fname.title() lname = lname.title() print(f'Your full name : {fname} {lname}.') print()
true
7603e32d8a1590523d33d29d2e331968e6881de0
SpadinaRoad/Python_by_Examples
/Example_121/Example_121.py
2,486
4.84375
5
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_121 # $ python3 Example_121.py # $ python3 Example_121.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 121 Create a program that will allow the user to easily manage a list of names. You should display a menu that will allow them to add a name to the list, change a name in the list, delete a name from the list or view all the names in the list. There should also be a menu option to allow the user to end the program. If they select an option that is not relevant, then it should display a suitable message. After they have made a selection to either add a name, change a name, delete a name or view all the names, they should see the menu again without having to restart the program. The program should be made as easy to use as possible. """ print(__doc__) def menu() : print('Main Menu') print('----------') print('A. List names') print('B. Add a name') print('C. Change a name') print('D. Delete a name') print('X. Exit') print() return input('Enter menu item : ') def list_names() : print('List of Names.') count = 1 for i in names_list : print(f'{count} : {i}') count += 1 def add_name() : new_name = input('Enter a new name: ') print(f'The input for a name : {new_name}') names_list.append(new_name) def change_name() : list_names() index = int(input(f'Enter the number for the name to change: ')) print(f'The input for the index: {index}') new_name = input('Enter the new name: ') print(f'The input for a name : {new_name}') print() names_list[index - 1] = (new_name) list_names() def delete_name() : list_names() index = int(input(f'Enter the number for the name to change: ')) print(f'The input for the index: {index}') del names_list[index - 1] names_list = [] choice = '' while choice != 'x' : choice = menu().lower() print(f'The input for the choice: {choice}') print() if choice == 'a' : list_names() elif choice == 'b' : add_name() elif choice == 'c' : change_name() elif choice == 'd' : delete_name() elif choice == 'x' : pass else : print('Please enter one of A, B, C, D or X.') print()
true
949e7b0d24b836761e0b5f326349dadd404c91c5
SpadinaRoad/Python_by_Examples
/Example_120/Example_120.py
2,377
4.59375
5
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_120 # $ python3 Example_120.py # $ python3 Example_120.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 120 Display the following menu to the user: 1) Addition 2) Subtraction Enter 1 or 2 : If they enter a 1, it should run a subprogram that will generate two random numbers between 5 and 20, and ask the user to add them together. Work out the correct answer and return both the user’s answer and the correct answer. If they entered 2 as their selection on the menu, it should run a subprogram that will generate one number between 25 and 50 and another number between 1 and 25 and ask them to work out num1 minus num2. This way they will not have to worry about negative answers. Return both the user’s answer and the correct answer. Create another subprogram that will check if the user’s answer matches the actual answer. If it does, display “Correct”, otherwise display a message that will say “Incorrect, the answer is” and display the real answer. If they do not select a relevant option on the first menu you should display a suitable message. """ import random print(__doc__) def addition() : a = random.randint(5, 20) b = random.randint(5, 20) value = a + b answer = int(input(f'What is {a} plus {b} : ')) print(f'The input for the answer: {answer}') print() return (value, answer) def subtraction() : a = random.randint(25, 50) b = random.randint(1, 25) value = a - b answer = int(input(f'What is {a} less {b} : ')) print(f'The input for the answer: {answer}') print() return(value, answer) def check_answer(a: 'numbers') : if a[0] == a[1] : print('Correct.') else : print('Incorrect.') def main() : print('1) Addition') print('2) Subtraction') choice = int(input('Enter 1 or 2 : ')) print() print(f'The input for choice : {choice}') print() if choice not in range(1, 2) : print('You choice cannot be processed.') print() return if choice == 1 : to_check = addition() elif choice == 2 : to_check = subtraction() check_answer(to_check) print() main()
true
89696d06bfc3e0760c8fa983b4bdffa34a54a6a7
SpadinaRoad/Python_by_Examples
/Example_087/Example_087.py
628
4.71875
5
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_087 # $ python3 Example_087.py # $ python3 Example_087.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 087 Ask the user to type in a word and then display it backwards on separate lines. For instance, if they type in “Hello” it should display as shown below: o l l e H """ print(__doc__) a_word = input('Enter a word : ') print(f'Input for a word : {a_word}') print() for i in range(len(a_word), 0, -1) : print(a_word[i - 1])
true
59d41de6a817138dd30562aab81ef9e878ced7f1
SpadinaRoad/Python_by_Examples
/Example_008/Example_008.py
768
4.34375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_008 # $ python3 Example_008.py # $ python3 Example_008.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 008 Ask for the total price of the bill, then ask how many diners there are. Divide the total bill by the number of diners and show how much each person must pay. """ print(__doc__) total = input('What is the total amount of the bill : ') diners = input('How many diners are there : ') average = int(total) / int(diners) print('') print(f'The total amount of the bill is {int(total):.2f}') print(f'The number of diners is {diners}') print(f'The cost per diner is {average:.2f}')
true
b674a22cbac308660674199958dda064260eeb78
SpadinaRoad/Python_by_Examples
/Example_118/Example_118.py
781
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_118 # $ python3 Example_118.py # $ python3 Example_118.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 118 Define a subprogram that will ask the user to enter a number and save it as the variable “num”. Define another subprogram that will use “num” and count from 1 to that number. """ print(__doc__) def get_num() : a_num = int(input('Enter a number : ')) print(f'The input for a number : {a_num}') print() return a_num def display_nums(a : 'number') : for i in range(1, a + 1) : print(i) print() a_num = get_num() display_nums(a_num)
true
4cdf1d1b109601376c4046cd58fc940ba8a67ac0
SpadinaRoad/Python_by_Examples
/Example_073/Example_073.py
1,079
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_073 # $ python3 Example_073.py # $ python3 Example_073.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 073 Ask the user to enter four of their favourite foods and store them in a dictionary so that they are indexed with numbers starting from 1. Display the dictionary in full, showing the index number and the item. Ask them which they want to get rid of and remove it from the list. Sort the remaining data and display the dictionary. """ print(__doc__) food_dict = dict() for i in range(1, 5) : food_choice = input('Enter a favourite food: ') food_dict[i] = food_choice print() print(f'Input for food : {food_choice}') print() print(f'Here is the dictionary: {food_dict}') to_remove = int(input('What item do you want to remove? Enter the number: ')) print(f'Input for number to remove: {to_remove}') print() del food_dict[to_remove] print(sorted(food_dict.values()))
true
122071acd8cdcdb643aeb24d40edeb5bf00e5f72
SpadinaRoad/Python_by_Examples
/Example_005/Example_005.py
792
4.40625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_005 # $ python3 Example_005.py # $ python3 Example_005.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 005 Ask the user to enter three numbers. Add together the first two numbers and then multiply this total by the third. Display the answer as The answer is [answer]. """ print(__doc__) num_1 = input('Enter a number : ') num_2 = input('Enter a number : ') num_3 = input('Enter a number : ') answer = (int(num_1) + int(num_2)) * int(num_3) print('') print(f'The first number is : {num_1}') print(f'The second number is : {num_2}') print(f'The third number is : {num_3}') print(f'The answer is {answer}')
true
7acfe740b3794bfb3667c2012f8cad14ee51e14a
SpadinaRoad/Python_by_Examples
/Example_054/Example_054.py
1,300
4.3125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_054 # $ python3 Example_054.py # $ python3 Example_054.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 054 Randomly choose either heads or tails (“h” or “t”). Ask the user to make their choice. If their choice is the same as the randomly selected value, display the message “You win”, otherwise display “Bad luck”. At the end, tell the user if the computer selected heads or tails. """ import random print(__doc__) your_choice = '' comp_wins = 0 my_wins = 0 h_t_dict = { 'h' : 'heads', 't' : 'tails'} while your_choice != 'x' : heads_or_tails = random.choice(['h', 't']) your_choice = input('Choose heads or tails (h/t) : ') your_choice = your_choice.lower() if your_choice != 'x' : print() if heads_or_tails == your_choice : print('You win.') my_wins += 1 else : print('Bad luck') comp_wins += 1 print(f'You chose : {h_t_dict[your_choice]}') print(f'The computer chose : {h_t_dict[heads_or_tails]}') print(f'The score: Computer {comp_wins} Me {my_wins}') print()
true
862410ffce316943c47de2b0ab155f6549182f71
SpadinaRoad/Python_by_Examples
/Example_033/Example_033.py
1,029
4.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_033 # $ python3 Example_033.py # $ python3 Example_033.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 033 Ask the user to enter two numbers. Use whole number division to divide the first number by the second and also work out the remainder and display the answer in a user-friendly way (e.g. if they enter 7 and 2 display “7 divided by 2 is 3 with 1 remaining”). """ print(__doc__) int_a = '' while int_a != 'x' : int_a = input('Enter an integer : ') if int_a != 'x' : int_a = int(int_a) int_b = input('Enter a second integer : ') int_b = int(int_b) print() print(f'The input for number 1 : {int_a}.') print(f'The input for number 2 : {int_b}.') print(f'{int_a} divided by {int_b} is {int_a // int_b} with {int_a % int_b} remaining.') print()
true
9f61ce54a78450b8cd1151a94c177b3330e6b1f1
SpadinaRoad/Python_by_Examples
/Example_117/Example_117.py
2,151
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_117 # $ python3 Example_117.py # $ python3 Example_117.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 117 Create a simple maths quiz that will ask the user for their name and then generate two random questions. Store their name, the questions they were asked, their answers and their final score in a .csv file. Whenever the program is run it should add to the .csv file and not overwrite anything. """ import csv import random print(__doc__) #Start data. print('The Great Math Quiz') print('') name = input('What is your name? ') print(f'The input for name: {name}') print() #Saving to csv file filename = 'MathQuiz.csv' with open(filename, 'a') as fo: fo.write('The Great Math Quiz\n') fo.write(f'User: {name}\n') fo.write('\n') #First math question. operand_a = random.randint(1, 100) operand_b = random.randint(1, 100) correct_answer = operand_a + operand_b line_1 = f'Enter the addition of {operand_a} and {operand_b} : ' answer = int(input(line_1)) line_2 = f'Your answer is {answer}. ' if answer == correct_answer : line_2 += 'It is correct.' score = 1 else : line_2 += 'It is not correct.' score = 0 print(line_2) with open(filename, 'a') as fo : fo.write('The first question: \n') fo.write(f'{line_1}\n') fo.write(f'{line_2}\n') fo.write(f'\n') print() #Second math question. operand_a = random.randint(1, 100) operand_b = random.randint(1, 100) correct_answer = operand_a + operand_b line_1 = f'Enter the addition of {operand_a} and {operand_b} : ' answer = int(input(line_1)) line_2 = f'Your answer is {answer}. ' if answer == correct_answer : line_2 += 'It is correct.' score += 1 else : line_2 += 'It is not correct.' score += 0 print(line_2) with open(filename, 'a') as fo : fo.write('The first question: \n') fo.write(f'{line_1}\n') fo.write(f'{line_2}\n') fo.write(f'\n') fo.write(f'Correct answers: {score} out of 2 ({score/2:.2%}).') print()
true
b5e95bb07b2cb89f23c172c8af483b6bf595fa36
ooladuwa/cs-problemSets
/Week 1/07-SchoolYearsAndGroups.py
2,132
4.34375
4
Imagine a school that children attend for years. In each year, there are a certain number of groups started, marked with the letters. So if years = 7 and groups = 4For the first year, the groups are 1a, 1b, 1c, 1d, and for the last year, the groups are 7a, 7b, 7c, 7d. Write a function that returns the groups in the school by year (as a string), separated with a comma and space in the form of "1a, 1b, 1c, 1d, 2a, 2b (....) 6d, 7a, 7b, 7c, 7d". Examples: csSchoolYearsAndGroups(years = 7, groups = 4) ➞ "1a, 1b, 1c, 1d, 2a, 2b, 2c, 2d, 3a, 3b, 3c, 3d, 4a, 4b, 4c, 4d, 5a, 5b, 5c, 5d, 6a, 6b, 6c, 6d, 7a, 7b, 7c, 7d" Notes: 1 <= years <= 10 1 <= groups <=26 """ Understand: - There are a given number of years notated by y - for each year, there are a number of groups notated by a letter corresponding to the letter of the alphabet - 1 - each year/group combination is notated by yearNumbergroupLetter - in order to iterate through years and/or groups, integer must be converted to string Plan: - create groupLetters list indentical to alphabet # groupLetters = ["a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] - create yearsList list from 1-10 # yearsList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - create empty list to hold groups by year # yearsByGroup = [] - slice groupLetters list from left identical to the number of groups # groupLetters[0:groups] - slice yearList at integer corresponding to years # yearList[0:years] - for each year/index, iterate through groupLetters and attach all letters to year individually attach one element from groupLetters and append it to new list # for year in yearsList and letter in groupLetters yearsByGroup += f{year}{letter} """ def csSchoolYearsAndGroups(years, groups): groupLetters = "abcdefghijklmnopqrstuvwxyz" yearList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] yearsByGroup = [] for year in yearList[:years]: for letter in groupLetters[:groups]: yearGroup = (f"{year}{letter}") yearsByGroup.append(yearGroup) continue continue return ", ".join(yearsByGroup)
true
56c7032089bdb28b37620aa15a03faf782e67f26
ooladuwa/cs-problemSets
/Week 3/033-insertValueIntoSortedLinkedList.py
2,081
4.3125
4
# Singly-linked lists are already defined with this interface: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # """ - create function to insert a node - create new link node with value provided - set up a current variable pointing to the head of the list and set a ref to the current node - while current.next < value - traverse to the next node - set new nodes pointer to current nodes next - set current nodes pointer to new node """ def insertValueIntoSortedLinkedList(l, value): new_node = ListNode(value) current = l # edge case if l is empty if l == None: return new_node # edge case if value is less than initial current value ie. first node if new_node.value < l.value: new_node.next = current return new_node # middle cases while current.next is not None: if current.next.value > new_node.value: new_node.next = current.next current.next = new_node return l current = current.next # edge case if value to be replaced comes after last element current.next = new_node return l """ Note: Your solution should have O(n) time complexity, where n is the number of elements in l, since this is what you will be asked to accomplish in an interview. You have a singly linked list l, which is sorted in strictly increasing order, and an integer value. Add value to the list l, preserving its original sorting. Note: in examples below and tests preview linked lists are presented as arrays just for simplicity of visualization: in real data you will be given a head node l of the linked list Example For l = [1, 3, 4, 6] and value = 5, the output should be insertValueIntoSortedLinkedList(l, value) = [1, 3, 4, 5, 6]; For l = [1, 3, 4, 6] and value = 10, the output should be insertValueIntoSortedLinkedList(l, value) = [1, 3, 4, 6, 10]; For l = [1, 3, 4, 6] and value = 0, the output should be insertValueIntoSortedLinkedList(l, value) = [0, 1, 3, 4, 6]. """
true