blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
455d1124c6e6846b4da09d0bcb4ad8d80d8badb7
912-CUCONU-MARIA/FP
/src/seminar/group_917/seminar_05b/functions.py
1,927
4.46875
4
"""" 1. Generate 'n' rectangles random.randint(a,b) -> use to generate random integers - n is a positive integer read from the keyboard. - program generates and stores n distinct rectangles (distinct = at least one different corner), - each rectangle is completely enclosed in the square defined by corners (0,0) and (20,20) 2. Display all rectangle data, sorted descending by area rectangle: (0,0) - (10,10) -> area is 100 (0,0), (0,10), (10,0), (10,10) rectangle: (14,15) - (18,18) -> area is 12 - display area and coordinates for each rectangle, using right justification (str.rjust) 3. Delete all rectangles that have at least one corner below the line x = y """ import random from rectangle import * class functions: def __init__(self): self._rectangle_list = [] def check_previous_rectangles_for_uniqueness(self, r): for rect in self._rectangle_list: if equal_rectangles(rect, r): return False return True def delete_rectangles_below_the_line(self): i = 0 while i < len(self._rectangle_list): if below_the_line(get_corner1(self._rectangle_list[i])) == True or below_the_line( get_corner2(self._rectangle_list[i])) == True: self._rectangle_list.pop(i) i -= 1 i += 1 def rectangles_list_by_area(self): rectangles_sorted = sorted(self._rectangle_list, key=area_of_rectangle, reverse=True) return rectangles_sorted def generate_a_rectangle(): p1 = create_point(0, 0) p2 = create_point(0, 0) while equal_points(p1, p2) and points_on_different_lines(p1, p2) == False: x = random.randint(0, 20) y = random.randint(0, 20) p1 = create_point(x, y) a = random.randint(0, 20) b = random.randint(0, 20) p2 = create_point(a, b) return create_rectangle(p1, p2)
true
3545cc2e60da4bab85a29380228466e971063166
affan10/Python-Concepts
/anonymousFuncs.py
1,761
4.34375
4
''' This script is an implementation of Lamda Functions with map(), filter() and reduce() Anonymous Functions = Lambda Expressions = Lambda Function(s) ''' # Simple Lambda Expression to calculate corresponding y coordinate given x, m and c # Either return the Lambda Expression into a variable and pass values to that as follows: equation = lambda x, m, c: m * x + c print('With variable:', equation(1, -2, 10)) # Or pass values directly to the Lambda Expression like this: print('Without variable:', (lambda x, m, c: m * x + c)(1, -2, 10)) ''' Using map() with Lambda Expressions map() performs the given function to all values in the passed iterable ''' # Convert lowercase strings in list to uppercase lowerStrings = ['messi', 'iniesta', 'xavi', 'puyol', 'pique'] convertToUpper = lambda name : name.upper() print(list(map(convertToUpper, lowerStrings))) ''' Using filter() with Lambda Expressions filter() returns values depending on the filter critera defined in the lambda function ''' # Remove missing values from list lowerStrings = ['messi', '', 'iniesta', '', '', 'xavi', 'puyol', 'pique', '', ''] removeMissingValues = lambda name : name print(list(filter(removeMissingValues, lowerStrings))) ''' Using reduce() with Lambda Expressions reduce() always requires at least two values in its lamdba function It performs the operation specified in the lambda function and computes the result of the first two values. It then uses the result to perform the operation on the next value ''' from functools import reduce # Concatenate all strings in the list lowerStrings = ['messi', 'iniesta', 'xavi', 'puyol', 'pique'] concateStrings = lambda x, y : x + y print(reduce(concateStrings, lowerStrings))
true
94a71e9a1cd844f036ee97547f4bbee604826f1e
armedev/Basics_python
/age_calculator.py
933
4.3125
4
#age_calculator_and_voter_predictor ww = int(input("your date of birth:> ")) if ww in range(0, 5000): print(ww, "-birth year") if ww <= 2019: age = 2019 - int(ww) else: age = 0.1 if age == 1: yr = "year" print("you have completed your", age, yr) elif age == 0: print("you are just months older or you have not born yet") elif age == 0.1: print("you have not born yet") else: yr = "year's" print("you have completed your", age, yr) if age > 18: print('''you have the right to vote''') elif age == 18: print("you are the voter for the next year") elif age == 0: print("you failed to provide your correct birth-date") elif age == 0.1: print("you failed to provide your correct birth-date") else: print("But you are under 18 year's") else: print(f"you entered string(letters).")
false
388e63771e759efc468db0051655d2af770ee7b7
abbibrunton/python-stuff
/Python stuff/numbers_to_words.py
731
4.21875
4
number = list(input("please enter a number: ")) units = {0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven", 8:"eight",9:"nine",10:"ten",11:"eleven",12:"twelve",13:"thirteen",14:"fourteen", 15:"fifteen",16:"sixteen",17:"seventeen",18:"eighteen",19:"nineteen"} tens = {2: " twenty",3: " thirty",4: " forty",5: " fifty",6: " sixty",7: " seventy",8: " eighty",9: " ninety"} scales = {0 : "and", 1 : " ", 2 : ", ", 3 : " hundred", 6 : " thousand", 9 : " million", 12 : " billion", 15 : " trillion"} num_len = len(number) if num_len>13: print("number is too large") elif num_len =15: number.reverse() elif n def num_to_words(number, scale, output): 1,000,000,000,000 000,000,000,000,1
false
5816941b81d803269a66c36de4d60d460affd7db
0x4ndy/algorithms-data-structures
/src/bfs.py
1,125
4.28125
4
""" This is an example implementation of BFS algorithm (iterative). """ from data_structures.queue import Queue from helpers.graph_heplers import get_path, offsets from helpers.maze_helpers import load_maze, can_move, print_maze def bfs(maze, start, goal): queue = Queue() queue.enqueue(start) predecessors = {start: None} while not queue.is_empty(): current = queue.dequeue() if current == goal: return get_path(predecessors, start, goal) for direction in ["up", "right", "down", "left"]: next_row, next_col = offsets[direction] neighbour = (current[0] + next_row, current[1] + next_col) if can_move(maze, neighbour) and neighbour not in predecessors: queue.enqueue(neighbour) predecessors[neighbour] = current return None def main(): maze = load_maze("data/mazes/maze1") print_maze(maze) start = (0, 0) goal = (2, 2) result = bfs(maze, start, goal) assert result == [(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)] print(result) if __name__ == "__main__": main()
true
8c77634b3bd32a11cea163f2e2ae0a5d1328d376
0x4ndy/algorithms-data-structures
/src/helpers/maze_helpers.py
1,197
4.40625
4
""" A set of maze functions used throughout all other algorithms and data structures. """ def load_maze(filename): """ This function is used to generate a 2d list based on a maze stored in a text file. """ with open(filename, newline=None) as file: maze = [[c for c in line.rstrip("\n\r")] for line in file] return maze def print_maze(maze): """ This function prints maze """ [print(row) for row in maze] def is_maze_rectangular(maze): """ This function checks whether the rows of a maze are all the same length """ if len(maze) == 0: return True base_len = len(maze[0]) for i in range(1, len(maze)): if len(maze[i]) != base_len: return False def can_move(maze, pos): """ This function checks whether a move to the give position can be made. """ i, j = pos row_count = len(maze) col_count = len(maze[0]) return 0 <= i < row_count and 0 <= j < col_count and maze[i][j] != "*" def calc_distance(a, b): """ Calculates the Manhattan distance between coordinates 'a' and 'b' """ x1, y1 = a x2, y2 = b return abs(x1 - x2) + abs(y1 - y2)
true
8f0bd06673944722522e6902ad52676fa366575e
m-sousa/curso-em-video-python
/Exercicios/MOD02/ex059.py
1,464
4.3125
4
# Exercício Python 059: Crie um programa que leia dois valores e mostre um menu # na tela: # [ 1 ] somar # [ 2 ] multiplicar # [ 3 ] maior # [ 4 ] novos números # [ 5 ] sair do programa # Seu programa deverá realizar a operação solicitada em # cada caso. operacao = int(0) a = float(input('Informe o 1º número: ')) b = float(input('Informe o 2º número: ')) while operacao != 5: operacao = int(input('''Qual das operações abaixo deseja realizar: [ 1 ] somar [ 2 ] multiplicar [ 3 ] maior [ 4 ] novos números [ 5 ] sair do programa\n\nOperação: ''')) if operacao in [1,2,3,4,5]: if operacao == 1: print('A soma entre {} e {} é: {}'.format(a, b, a + b)) elif operacao == 2: print('A muliplicação entre {} e {} é: {}'.format(a, b, a * b)) elif operacao == 3: if a > b: print('{} é maior que {}'.format(a, b)) elif b > a: print('{} é maior que {}'.format(b, a)) else: print('{} e {} são iguais'.format(a, b)) elif operacao == 4: a = float(input('Informe o 1º número: ')) b = float(input('Informe o 2º número: ')) print('Programa encerrado...')
false
6003dff344a4a346187fb6bfb03dc6a90793e08b
m-sousa/curso-em-video-python
/Exercicios/MOD01/ex016.py
314
4.125
4
# Exercício Python 016: Crie um programa que leia um número Real qualquer pelo # teclado e mostre na tela a sua porção Inteira. from math import trunc valor = float(input('Digite um valor: ')) print('O valor digitado foi {} e a sua porção inteira é {}'.format(valor, trunc(valor)))
false
d61dbc209291d893af4b6ede15297c2b9d98f24d
aga-moj-nick/w3resource---Python-Basic-Part-I-
/Exercise 037.py
619
4.21875
4
# 37. Write a Python program to display your details like name, age, address in three different lines. # ROZWIĄZANIE 1: def dane_personalne (): imie = input ("Podaj swoje imię: ") nazwisko = input ("Podaj swoje nazwisko: ") wiek = input ("Podaj swój wiek: ") print ("imie: {} \nnazwisko: {} \nwiek: {}".format (imie, nazwisko, wiek)) dane_personalne () # ROZWIĄZANIE 2: imie = input("Podaj swoje imię: ") nazwisko = input ("Podaj swoje nazwisko: ") wiek = input ("Podaj swój wiek: ") print(f"Twoje imię to: {imie}") print(f"Twoje nazwisko to: {nazwisko}") print(f"Twój wiek to: {wiek}")
false
c347894a99ad3d9b9f12595b54591555cf069b51
aga-moj-nick/w3resource---Python-Basic-Part-I-
/Exercise 029.py
451
4.21875
4
# 29. Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2. color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) for color in color_list_1: if color not in color_list_2: print (color) """ print ("Pierwsza lista: ", color_list_1) print ("Druga lista: ", color_list_2) print ("Różnice: ", color_list_1.difference (color_list_2)) """
true
0779391f6a66fcc9d8c359874bb050cb8ab70b29
MindaugasVainauskas/python-problems
/Newtowns-square-root-calculation.py
241
4.125
4
#21/09/2017 #Lab 1 #Calculating Newton's method for square roots x = 20 z_next = lambda z: (z - ((z*z - x) / (2 * x))) current = 1.0 while current != z_next(current): print("Current guess: %0.10f" % (current)) current = z_next(current)
false
bd0d7993fc828d2835764e52955b434253d6daf4
lkmsf/pythonLearning-
/Challenges/outer_space_weigth.py
1,672
4.625
5
#1-1 #The user inputs their weight and the program returns what their weight would be on another planet # Milestone 1: Make sure this works first before moving on! The user inputs their weight and the program returns what their weight is on the moon. You will have to look up how your weight changes when your are on another planet. # Milestone 2: (If you have time) The user inputs their weight and some planet and the program returns what their weight on that planet is. # Beyond: Really excited by this program? Add your own spin! What do you think it needs? Some inspiration: What else would be different on different planets? What is their survival changes on that other planet? #!!!!! Having trouble running this? run main above and follow the instructions! Let me know if you have any questions! #auto indent : https://www.tutorialspoint.com/online_python_formatter.htm def main(): #write code here print("weight-converter ") result = input("what is your weight?") weight = int(result) print(weight) result = input("what planet would you like to know your weight on?") if result == "moon" : weight_mult = 0.165 elif result == "venus" : weight_mult = 0.9 elif result == "saturn" : weight_mult = 1.07 elif result == "neptune" : weight_mult = 1.10 elif result == "mars" : weight_mult = 0.379 elif result == "mercury" : weight_mult = 0.376 elif result == "jupiter" : weight_mult = 2.4 elif result == "uranus" : weight_mult = 0.86 weight = weight * weight_mult print(weight) #write any helper functions here #this just runs the main function above when we run this file as a script if __name__ == '__main__': main();
true
901dd6704df37deb498425ea007530c301bf9d22
dfg31197/Algo-DS
/Python/Conversions/binaryToDecimal.py
503
4.15625
4
while True: print("Please Enter a Binary number or Type EXIT to exit") temp = raw_input() if(temp != "EXIT"): ques = temp[::-1] count = 0 res = 0 flag = 0 for x in ques: if(int(x)>1): print("Invalid. Enter a binary number") flag = 1 break res += int(x)*(2**count) count += 1 if not flag: print res else: break print ("End of program")
true
1eec187e3878e24b1211845802bc02f1cb323976
Siddhant-Jha/Basic-Python-Programs
/MilesToMeter.py
299
4.21875
4
print("Welcome To The Miles Per Hour To Meter Per Second Conversion app") miles = float(input("Enter Your Speed In Miles Per Hour :\t")) mps = miles*0.4474 mps = round(mps,2) print("Your Speed In Miles Per Hour Is : " + str(miles)) print("While, Your Speed In Meter Per Second Is : "+ str(mps))
true
ec98a406795ffc09d94feb6c178ae6543ca327e7
prathmesh31/python_assignments
/Solved Assigments/assignment_phrase_palindrome.py
721
4.3125
4
#palindrome paragraph #"Go hanga salami I'm a lasagna hog.", "Was it a rat Isaw?", #"Step on no pets", "Sit on a potato pan, Otis", "LisaBonet ate no basil", #"Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", #"Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, #capitalization, and spacing are usually ignored. phrase = input("Enter a palindrome phrase") temp="" for i in range(len(phrase)): if phrase[i].isalpha(): #exculdes symbols temp+=phrase[i] #This will add charcter only one by one if temp.lower() == temp[::-1].lower(): #condition for palindrome print("palindrome") else: print("not palindrome")
true
8a0ef6c5c29026b4c72d8bc46e113cf4368601a9
waffle52/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
411
4.125
4
#!/usr/bin/python3 def read_lines(filename="", nb_lines=0): """ func to print file as whole or by line limit """ with open(filename, encoding="utf-8") as MyFile: if nb_lines <= 0 or nb_lines >= len(MyFile.readlines()): print(MyFile.read(), end="") else: MyFile.seek(0) for i in range(1, nb_lines + 1): print(MyFile.readline(), end="")
true
3476b9574cbed1f8bae33a807dab63e51860bff1
nielsonnp/segundoperiodo
/exercicio2/questao4.py
966
4.1875
4
'''4. Faça um programa que tenha uma classe que define uma Pessoa, com atributos nome, idade e sexo. Em seguida, o programa deve ser capaz de ler os mesmos dados e imprimir a confirmação dos dados criados, que estarão armazenados em uma estrutura de dados. Estabeleça um critério de parada.''' class Pessoa: def __init__(self, nome, idade, sexo): self.nome = nome self.idade = idade self.sexo = sexo def __repr__(self): return "Nome: {}, Idade: {}, Sexo: {} " .format(self.nome, self.idade, self.sexo) def get_nome(self): return self.nome def get_idade(self): return self.idade def get_sexo(self): return self.sexo lista = [] while True: nome = input("Digite seu nome: ") if nome == "-1": break idade = int(input("Digite sua idade: ")) sexo = input(("Digite seu sexo: ")) pes = Pessoa(nome, idade, sexo) lista.append(pes) print(lista)
false
de90096228ca75ecdcab9d18dfa4485002432def
karangurtu/Python-Programming
/1_Fundamental Python Programming/1_1_Python Fundamentals/BitwiseOperators.py
1,057
4.375
4
print("Bitwise Operators in Python"); print(""); print(""); print("1) Bitwise & Operator (AND)"); print("5&4 =",5&4); ''' Logic: Column Wise, 1 if all 1 else 0. 5 = 101 4 = 100 out = 100 = 4 ''' print(""); print(""); print("2) Bitwise | Operator (OR)"); print("5|4 =",5|4); ''' Logic: Column Wise, 1 if atleast 1 else 0. 5 = 101 4 = 100 out = 101 = 5 ''' print(""); print(""); print("3) Bitwise ~ Operator (One's Complement)"); print("~5",~5); ''' Logic: Not all bits 1 -> 0 0 -> 1 5 = 101 ~5 = 010 = 2 ''' print(""); print(""); print("4) Bitwise ^ Operator (XOR)"); print("5^4 =",5^4); ''' Logic: If odd number of 1 in column then 1 else 0 5 = 101 4 = 100 out = 001 = 1 ''' print(""); print(""); print("5) Bitwise << Operator (Left Shift)"); print("5<<4 =",5<<4); ''' Left shift a<<b == a*(2**b) ''' print(""); print(""); print("6) Bitwise >> Operator (Right Shift)"); print("5>>4 =",50>>4); ''' Right shift a>>b == a/(2**b) ''' print("Note: Answer of Right Shift always in form of Floor Division //"); print(""); print("");
false
ac1aec6c2cebcb4bd17f1fa49a33893739a0cc04
UncleBob2/100_day_python_solution
/day3_treasure_island.py
1,078
4.15625
4
print( """ Welcome to Treasure Island. Your mission is to find the treasure. """ ) turn = input( 'You\' are at a cross road. Where do you want to go? Type "left" or "right" \n' ).lower() # *** NEED TO CONVERT TO LOWER CASES, NEED TO DRAW UP DECISION DIAGRAM if turn == "left": print( """You've come to a lake. There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across.""" ) action = input().lower() if action == "wait": print( """You arrived at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose?""" ) option = input().lower() if option == "red": print("It's a room full of fire. Game Over.") elif option == "yellow": print("You found the treasure! You Win!") else: print("You enter a room of beasts. Game Over.") else: print("You get attacked by an angry trout. Game Over") else: print("You fell into a hole. Game Over.")
true
28b34f35a665a56ec0694bc1e955aa8299025785
UncleBob2/100_day_python_solution
/day_8_Caesar_Cipher_final.py
1,670
4.1875
4
import day_8_art import string num_sym = list(string.digits + string.punctuation + " ") alphabet = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", ] def caesar_1(plain_text, shift_amount, direction_code): code_text = "" shift_amount %= 25 # ensure program still work when shift is greater than alphabet if direction == "decode": shift_amount *= -1 # ***must be outside of for loop for letter in plain_text: if letter in num_sym: code_text += letter else: position = alphabet.index(letter) new_position = position + shift_amount code_text += alphabet[new_position] print(f"Here's is the {direction_code}d results: {code_text}") ##🐛Bug alert: What happens if you try to encode the word 'civilization'?🐛 print(day_8_art.logo) run_again = True while run_again == True: direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) caesar_1(text, shift, direction) ask = input("Type 'yes' if you want to run again. Otherwise type 'no'. \n") if ask == "no": run_again = False print("Goodbye")
true
956ca6a1095e02d6066573481d5c24f19abd1910
erayaydin/python
/Articles/002-variables-and-operators/variables.py
1,134
4.21875
4
## type() # Printing int variable print(1970) # Testing str type print(type('Hello World')) # Testing int type print(type(1970)) # Testing float type print(type(3.14)) ## variables # creating a new variable release_date=1970 hello='Hello World' pi_number=3.14 # using variable print(release_date) print(hello) print(pi_number) # using in type function print(type(release_date)) print(type(hello)) print(type(pi_number)) ## assign # assign a result to variable math = 2+5 # using another variable for assign (first calculation then assign) math = math + 1 # print the value (8) print(math) ## operators plus = 4+4 minus = 3.14-1 times = 11*6 divide = 16/5 divideUp = 16//5 modDivide = 17%2 power = 3**4 print("4+4=",plus) print("3.14-1=",minus) print("11*6=",times) print("16/5=",divide) print("16//5=",divideUp) print("17%2=",modDivide) print("3**4=",power) ## using operators with strings # concat print('kirmizi' + ' ' + 'kalem') # times print('kirmizi' * 5) ## change type of a variable string = '5' number = 3 print(type(string)) print(type(int(string))) print(type(number)) print(type(str(number)))
true
76312d0208da121903deb419f73bbaf712c2b1e1
kaki1104/Su-CS550
/loops.py
616
4.21875
4
# loops.py # num = int(input("Pick a number between 1 and 5")) # while num<1 or num>5: # num = int(input("This number is not in the right range.")) # print ("success!") # def check (choice, a, b) # while choice != and choice != b # choice= input ("please choose "+a+" or "+b+"") # return choice while True : try: num = int(input("Pick a number between 1 and 5.")) while num<1 or num>5: num = int(input("This number is not in the right range. enter a number between 1 and 5.")) break #breaks immediate loop except ValueError : print ("That's not a number. Try again.") print ("success!")
true
a78bda11eab1ad1a16d4c356f06d2badd041a467
kaki1104/Su-CS550
/function.py
971
4.25
4
#function.py #lesson on python function #def greetings (someone) : #print ("Hello", someone) #greetings ("Alex") #greetings ("Daniel") #greetings ("a") #greetings (True) def start (): input ("You are here to save the princess!") input ("She has been kidnapped by Bowser and Bowser Jr.") result = input("type 1 to save the princess or \ntype 2 to turn back.") #do multiple inputs if you want the user to enter for every sentence if result =="1": savePrincess() elif result == "2": shame() else: print ("I don't know what that "+result+" means. Please type 1 or 2.") start() def savePrincess(): direction=input ("choose left or right.") if direction == "right": print ("oops, there is a bear.") elif direction == "left": print ("hmmm.... This route is oddly peaceful.") else: print ("I don't know what that "+direction+" means. Please type right or left.") savePrincess() def shame(): print ("Wow, you are clearly a coward.") start()
true
a7e745a745c94058a27a5a4d7f25369ad340cce2
antooa/PracticePythonBeginner
/RockPaperScissors.py
1,945
4.1875
4
#! A simple gave Rock Paper Scissors print('Welcome to the game Rock Scissors Paper!\nI hope you know the rules :D') player_1 = input('FIRST player, what is your name?\n') player_2 = input('SECOND player, what is your name?\n') rock = 'rock' scissors = 'scissors' paper = 'paper' def play(player_1_move, player_2_move): if player_1_move != rock and player_1_move != scissors and player_1_move != paper: return False if player_2_move != rock and player_2_move != scissors and player_2_move != paper: return False if player_2_move == player_1_move: return 'Its a draw' else: if player_1_move == rock: if player_2_move == scissors: return player_1 elif player_2_move == paper: return player_2 elif player_1_move == scissors: if player_2_move == paper: return player_1 else: return player_2 elif player_1_move == paper: if player_2_move == scissors: return player_2 else: return player_1 def start_game(): while True: print("----------NEW ROUND-----------") print("{0}! Now is your turn:" .format(player_1)) player_1_move = input() if player_1_move == 'quit': break print("{0}! Now is your turn:" .format(player_2)) player_2_move = input() if player_2_move == 'quit': break result = play(player_1_move.lower(), player_2_move.lower()) if not result: print("FOLLOW THE RULES! ONLY ROCK/SCISSORS/PAPER!") elif result == 'draw': print('{0}!' .format(result)) else: print("{0} is winner! CONGRATULATIONS!" .format(result)) def main(): print("To quit write \'quit\'") print("!!!Game Starts!!!") start_game() print("Thank you for the game!") main()
false
2c38b781f56162103b29aca439e113e411001fd5
charleycornali/codeeval_challenges
/longest_lines.py
1,241
4.65625
5
# -*- coding: utf-8 -*- """ Write a program which reads a file and prints to stdout the specified number of the longest lines that are sorted based on their length in descending order. INPUT SAMPLE: Your program should accept a path to a file as its first argument. The file contains multiple lines. The first line indicates the number of lines you should output, the other lines are of different length and are presented randomly. You may assume that the input file is formatted correctly and the number in the first line is a valid positive integer. For example: 2 Hello World CodeEval Quick Fox A San Francisco OUTPUT SAMPLE: Print out the longest lines limited by specified number and sorted by their length in descending order. For example: San Francisco Hello World """ import sys, re def main(): file_object = open(sys.argv[1], 'r') lines = file_object.readlines() num_lines_to_print = int(re.sub('\n', '', lines[0])) word_length_dict = {} for idx, line in enumerate(lines): word_length_dict[len(re.sub('\n', '', line))] = line for _ in range(num_lines_to_print): key = max(word_length_dict.keys()) sys.stdout.write(word_length_dict[key] + '\n') del word_length_dict[key] if __name__ in '__main__': main()
true
5bcd5c36957d9a4491a57bf98c5f81e40c38d981
denasiahamilton/freshman_code2018-
/Homework/homework5/hamil662_5B.py
1,044
4.21875
4
#CSCI 1133 Homework 5 #Denasia Hamilton #Problem 5B def finding_base(decimal_number, the_base): #letters replace 10-15 in string conversion = '0123456789' + 'ABCDEF' #conversion[decimal_number] == place in the length of the string if decimal_number < the_base: #base case return conversion[decimal_number] #take the decimal_number, and divide it by the_base until the quotient = 0; this is final #once quotient = 0, take final & add remainder in type(str) based on conversion, return string #if remainder < 9, use letter from conversion else: final = finding_base(decimal_number//the_base, the_base) #division remainder = decimal_number % the_base #module, remainder return str(final) + conversion[remainder] def main(): decimal_number = int(input("Enter your decimal number: " )) the_base = int(input("Enter the base you want to convert to: ")) print(decimal_number, "in base", the_base, "is", finding_base(decimal_number, the_base)) if __name__ == "__main__": main()
true
99f082351a1455e4494e392bcf3635c83e838c16
dcronkite/pytraining
/001-DataStructures/homework1.py
824
4.34375
4
""" Run this file from the command line by going to the directory and typing: python homework1.py Assignment ============= Take two numbers and combine them according to the given operation. I've started it... Hint: Input returns a `str`, and the numbers need to be `int` or `float` to combine them. """ while True: # this lets you do several iterations num1 = input('Give me a number: ') num2 = input('Give me another number: ') operator = input('Give me an operator: ') if operator == '+': print(num1 + num2) # this is wrong to start elif operator == '-': print(num1 - num2) else: print('I did not recognize the operator.') # you'll need to exit and run the program again for changes to take effect if input('Continue? (y/n): ').lower() != 'y': break
true
5d8cde1fb6c56d67f22bf3bc836573000894dc2a
dcronkite/pytraining
/003-Functions/homework-complete.py
1,156
4.1875
4
""" Assignment =============== * Write a program which repeatedly reads numbers until the user enters "done". * Once "done" is entered, print out the total, count, and average of the numbers. * If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number. Enter a number: 4 Enter a number: 5 Enter a number: bad data Invalid input Enter a number: 7 Enter a number: done 16 3 5.33333333333 """ numbers = [] while True: data = input('Enter a number: ') if data == 'done': break try: number = float(data) numbers.append(number) except ValueError: print('Invalid input') print('Total =', sum(numbers)) print('Count =', len(numbers)) print('Average =', sum(numbers) / len(numbers)) """ For extra credit, add the min and max """ # long form maximum = numbers[0] # start with the first one minimum = numbers[0] for number in numbers[1:]: if number > maximum: maximum = number if number < minimum: minimum = number # shortcut print('Min =', min(numbers), minimum) print('Max =', max(numbers), maximum)
true
f9feb53ef17bf670221df14487c00923e62b9478
fernandoalvessantos/pythonintroducao
/exercicio1.py
352
4.125
4
# Recebendo textos # meu_texto = input("Digite um texto: ") # Recebendo números # numero_inteiro = int(input("Digite um numero inteiro: ")) # numero_decimal = float(input("Digite um numero decimal: ")) def maiorIdade(idade): if idade >= 18: print("maior") else: print("menor") idade = int(input("Idade: ")) maiorIdade(idade)
false
6686ebdc7b826fc888fed61ba1739ba4ea0623dc
Botond-Horvath/y9-python
/Oct29Password.py
1,348
4.34375
4
#This program gives the user 5 attempts at guessing a password. #Author: Botond Horvath #October 29th, 2020 #Here, the variable 'password' becomes the string "password", which is the password the user needs to guess. password = ("password") #Below, the user recieves information of what their task is: print("There is only one password to get a prize, and you have 5 attempts at \nguessing that word!") print("") print("HINT: it is only one word... ") #This loop will run through its contenets 5 times, thereby giving the user 5 attempts: for word in range(5): attempt = input("What is the password? \n") #'attempt' variable is assigned the the input attempt of the user. if attempt == password: #If the user attempt is the same as the password... print("Well done, you got a PRIZE!") #Print a congratulation... break #and break the loop so that there are no more attempts, since they are unnesesarry. #If the above is not true, the user has not guessed the password and the loop will continue for 5 runs. else: print("Sorry, but that is not correct") #Letting the user know that what they typed in is incorrect. #After the loop, whether the user guessed the word (loop broke), or the user got to the end of the 5 trials (loop ended)... #the program prints that the password was password. print("The password was 'password'!" )
true
f679022b2056ef48f06e6a8c5f2667d9c01b7f3e
CobuLiza/homework_time_to_run
/main.py
936
4.125
4
# The program "Time of Your Life)". # (task with mark ** is an optional challenge) '''0. Ask the user how long it takes to walk to school in minutes (turn them to seconds) Ask the user the speed of walking in feet per second. Print to the user the estimate of distance to his or her school. (Put distance to school in a variable and print that variable) 1. Ask the user how many days a year he or she goes to school. Print the time user spends on walking to school and back home in a year. 2. **Tell the user how much time he or she will save in a year if he or she runs to school with a double speed of his or her walking. (try to make your answer in hours/days) ''' # help: ''' distance = time*speed time=distance//speed (you can try distance/time division and see the difference) 1 minute = 60 seconds 1 hours = 60 minutes 1 day = 24 hours '''
true
90ed211ffc3e1c45cfe9ed8690d5215d64c8e518
vsanghan/guess_the_number
/guessGame.py
512
4.125
4
#guess the number import random n = random.randint(1,100) #print (n) print ("Welcome to the Guess the Number Game.") inp = int(input("Guess the number between 1 and 100: ")) while inp != n : if inp > n : print ('You have entered bigger number.') inp = int(input("Guess the number between 1 and 100: ")) elif inp < n : print ('You have entered smaller number.') inp = int(input("Guess the number between 1 and 100: ")) print ("That's correct! Well Done")
true
70249a8342b9fd02d84a2ddef4673541d7bab554
HomaZeighami/Calculator
/Calculator.py
638
4.46875
4
# The user's inputs for the numbers and the operator. num1 = float(input("Enter your first number: ")) operator = input("Enter operator: ") num2 = float(input("Enter your second number: ")) str1 = str("Result:") # If operator is (+ , - , * , /), then print out number 1 (+ , - , * , /) number 2. if operator == "+": print(str1, (num1 + num2)) elif operator == "-": print(str1, (num1 - num2)) elif operator == "/": print(str1, (num1 / num2)) elif operator == "*": print(str1, (num1 * num2)) # If the user didn't put an operator, then print out "Invalid operator". else: print("Invalid operator")
true
8e8508aa6d56e2fcd1ad5d5aa93960d2e01c311e
morrowcode/pands-problem-set
/sumupto.py
758
4.28125
4
# Problem 1 - Summing all integers between user inputted number and 1 # Colin Morrow - Wed 27/02/2018 # Asking the user to input a number to define "n" n = int(input("Enter a positive integer...")) # total is a reference point for the addition of each integer total = 0 if n <= 0: print("Not really the positive integer I was looking for...") # the sum of 1 is 1 so id comment here to say something about wanting a bigger number to see what this thing can do elif n == 1: print("You should try a bigger number") else: while n > 0: #total is for the rolling total of integers between 0 and the user input one total += n #taking 1 away each 'loop' until n = o (won't end up being less than) n -= 1 print (total)
true
b2c97c48cdedb199a042ecdf07672a8bf39397ac
canyon15/PythonMod
/Example_3.py
1,457
4.5
4
""" CSE310 Python Workshop - Example 3 This example will explore classes and inheritance in Python. """ class Job: def __init__(self, title, work): """ Constructor for a Job object """ self.title = title self.work = work pass def __str__(self): """ Used to print out the object. Returns a string representation of the object. """ text = "{} : {} work".format(self.title, self.work) return text def do_work(self, ammount): """ Do work (don't let it go negative) """ if self.work < ammount: self.work = 0 else: self.work -= ammount def add_work(self, ammount): """ Increase the work load in the Job """ self.work += ammount pass def print_jobs(job_list): for job in job_list: print("{}\t".format(job),end="") print() def main(): job1 = Job("job1", 20) job2 = Job("job2", 10) job3 = Job("job3", 15) jobs = [job1, job2, job3] print_jobs(jobs) # Do 5 units of work for all jobs for job in jobs: job.do_work(8) print_jobs(jobs) # Do 4 units of work for all jobs for job in jobs: job.do_work(4) print_jobs(jobs) # Add 10 units of work to all jobs for job in jobs: job.add_work(10) print_jobs(jobs) if __name__ == "__main__": main()
true
168b4c80ea871f954785495cca40584ac622afd8
Dysio/PrjCodeWars
/Ex_0013_ShortestWord.py
250
4.125
4
def find_short(s): # your code here l = min([len(i) for i in string.split()]) return l # l: shortest word length if __name__ == '__main__': string = 'bitcoin take over the world maybe who knows perhaps' print(find_short(string))
true
503a25cb7ed6979274fa6e94919bb51163c3ba38
PEWEBER/Python
/project3.py
1,271
4.34375
4
#-------------------------------------------------------- # File------------project3.py # Developer-------Paige Weber # Course----------CS1213-03 # Project---------Project #3 # Due-------------October 5th, 2017 # # This program computes how long it will take to pay # off a loan and how much total interest is paid. #-------------------------------------------------------- original_principal = float(input("Principal-------- ")) annual_interest = int(input("Annual interest-- ")) monthly_payment = float(input("Monthly payment-- ")) monthly_interest = (annual_interest/12) * .01 month = 0 principal = original_principal old_minus_principal = 0 old_interest = 0 if monthly_payment < original_principal * monthly_interest: print() print("Loan not approved.") else: while principal > 0: minus_principal = monthly_payment - (principal * monthly_interest) total_interest = (principal * monthly_interest) + old_interest old_interest = total_interest month = month + 1 principal = original_principal - minus_principal - old_minus_principal old_minus_principal = minus_principal + old_minus_principal interest = total_interest print() print("Months :", month) print("Interest : $%5.2f"%interest)
true
98808d153e562c1f19b911b75ad8a9c327be403d
Q10Viking/algoNotes
/code/src/sort/demo/practice_1.py
569
4.125
4
import random def select_sort(arr): for i in range(len(arr)-1): # Find the min element in the unsorted range arr[left,n-1] minIndex = i for j in range(i+1,len(arr)): if arr[minIndex] > arr[j]: minIndex = j arr[i],arr[minIndex] = arr[minIndex],arr[i] if __name__ == "__main__": arr = [i for i in range(10)] random.shuffle(arr) print("before: ",arr) select_sort(arr) print("finished: ",arr) ''' before: [0, 5, 2, 9, 7, 8, 4, 3, 6, 1] finished: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] '''
false
71ef61796e82e0277efe632fbd8404a9cf89ef10
jgreen7773/python_stack
/python/fundamentals/functions_basic2.py
1,743
4.34375
4
# 1 # create a function that accepts a number as an input. Return a new list that counts down by one, from the argument given. def countdown(int): new_list1 = [] for x in range(int, -1, -1): new_list1.append([x]) print(new_list1) countdown(10) # 2 # Create a function that will receive a list with two numbers. Print the first value and return the second. def printreturn(a,b): print("print", a) return b printreturn(3,9) # 3 # Create a function that accepts a list and returns the sum of the first value in the list plus the list's length. def firstpluslength(list1): r = int(len(list1)) p = list1[0] + r print(p) sample_list = [5,3,7,2,9] firstpluslength(sample_list) # 4 # Write a function that accepts a list and creates a new list containing only the values from the original list # that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has # less than 2 elements, have the function return False def valuesgreaterthansecond(list2): new_list2 = [] if new_list2 < 2: return False for i in range(0,len(list2),1): if list2[i]>(list2[1]): new_list2.append(list2[i]) print(len(new_list2)) print(new_list2) return new_list2 sample_list2 = [8,3,5,2,1,5] valuesgreaterthansecond(sample_list2) # 5 # Write a function that accepts two integers as parameters: size and value. The function should create and return # a list whose length is equal to the given size and whose values are all the given value. def thislengththatvalue(int1,int2): new_list3 = [] for x in range(0, int1, 1): new_list3.append(int2) print(new_list3) return new_list3 thislengththatvalue(2,11)
true
4a980cb4091c6b58b5631bdab72bf21823714121
AllySmith1/CP1404_Practicals
/Prac03/asciiTableUpdated.py
1,360
4.28125
4
#Ascii Table def main(): #Constants LOWER = 33 UPPER = 127 print("Are you ready to run this program?") run_choice = input("Y - Yes, N - No: ") print() while run_choice == 'Y' or run_choice == 'y': input_char = (input("Enter a character: ")) converted_char = ord(input_char) print("The ASCII code for {} is {}.".format(input_char,converted_char)) print() input_num = get_number(LOWER, UPPER) if LOWER <= input_num <= UPPER: converted_num = chr(input_num) print("The character for {} is {}.".format(input_num,converted_num)) print() print("Would you like to run this program again?") run_choice = input("Y - Yes, N - No: ") print() print('An ASCII Table has been provided below:') for i in range(33,128,1): char = chr(i) print('{:>3} {}'.format(i,char)) print() print("Goodbye.") def get_number(lower, upper): valid_number = False while not valid_number: number = int(input("Enter a number ({}-{}): ".format(lower, upper))) #if lower < number < upper: if number > lower and number < upper: valid_number = True else: print("Please enter a valid number!") print("") return number main()
true
5019895ebd1e4b585c87826c2f439e2311918339
phamhoanglinh212/C4T_B04
/session6/matkhau2.py
220
4.1875
4
while True: text = input("Enter your password : ") length = len(text) if length < 8: print("Try again") elif text.isalpha(): print("Try again") else: print("Ok") break
true
5799e7dcf3c58a85157617330e3b925383b0d7fc
Krishnakumar01-zz/part2
/38.py
257
4.21875
4
def invertdict(dicti): '''input:a dictionary output:an inverted dictionary''' a=dicti.items() inv_dicti={} for i in a: inv_dicti[i[1]]=i[0] return inv_dicti def main(): print(invertdict({'x':1,'y':2,'z':3})) if __name__ == '__main__': main()
false
b7cf73bacac171cc5212b5089d08f750b6447643
masterford/AppliedMachineLearning
/HW1/train_and_evaluate_decision_tree.py
2,303
4.125
4
from sklearn.tree import DecisionTreeClassifier def train_and_evaluate_decision_tree(X_train, y_train, X_test, y_test): """ Trains an unbounded decision tree on the training data and computes two accuracy scores, the accuracy of the decision tree on the training data and the accuracy of the decision tree on the testing data. The decision tree should use the information gain criterion (set criterion='entropy') Parameters ---------- X_train: np.array The training features of shape (N_train, k) y_train: np.array The training labels of shape (N_train) X_test: np.array The testing features of shape (N_test, k) y_test: np.array The testing labels of shape (N_test) Returns ------- The training and testing accuracies represented as a tuple of size 2. """ model = DecisionTreeClassifier(criterion='entropy') model.fit(X_train, y_train) y_pred = model.predict(X_train) y_heldPred = model.predict(X_test) acc_train = accuracy_score(y_train, y_pred) acc_heldOut = accuracy_score(y_test, y_heldPred) return acc_train, acc_heldOut def train_and_evaluate_decision_stump(X_train, y_train, X_test, y_test): """ Trains a decision stump of maximum depth 4 on the training data and computes two accuracy scores, the accuracy of the decision stump on the training data and the accuracy of the decision tree on the testing data. The decision tree should use the information gain criterion (set criterion='entropy') Parameters ---------- X_train: np.array The training features of shape (N_train, k) y_train: np.array The training labels of shape (N_train) X_test: np.array The testing features of shape (N_test, k) y_test: np.array The testing labels of shape (N_test) Returns ------- The training and testing accuracies represented as a tuple of size 2. """ model = DecisionTreeClassifier(criterion='entropy', max_depth=4) model.fit(X_train, y_train) y_pred = model.predict(X_train) y_heldPred = model.predict(X_test) acc_train = accuracy_score(y_train, y_pred) acc_heldOut = accuracy_score(y_test, y_heldPred) return acc_train, acc_heldOut
true
0d72add52a321938ddeab9e5472caa78d2687fae
fenglisa/Python-101
/looping/fizzbuzz.py
732
4.21875
4
# Problem: FizzBuzz # Complete the function below. For a number N, print all the numbers starting # from 1 to N, except # 1. For numbers divisible by 3, print "Fizz" # 2. For numbers divisible by 5, print "Buzz" # 3. For numbers divisible by both 3 and 5, print "FizzBuzz" # Example: # Input: N = 20 # Output: # 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, # FizzBuzz, 16, 17, Fizz, 19, Buzz def fizzbuzz(n): nums = range(1, n+1) for num in nums: if num % 15 == 0: print('FizzBuzz') elif num % 3 == 0: print('Fizz') elif num % 5 == 0: print('Buzz') else: print(num) return if __name__ == "__main__": fizzbuzz(100)
true
85ecd029c3468a69e1afdadd072083e057bc0569
MaksimKulya/PythonCourse
/L4_task5.py
735
4.1875
4
# Реализовать формирование списка, используя функцию range() и возможности генератора. # В список должны войти четные числа от 100 до 1000 (включая границы). # Необходимо получить результат вычисления произведения всех элементов списка. # Подсказка: использовать функцию reduce(). import random as rnd a = [rnd.randint(100, 1000) for i in range(10)] print(f"Initial array: {a}") from functools import reduce def my_func(a1, a2): return a1 * a2 multi=reduce(my_func, a) print(f"All elements multiplication = {multi}")
false
6ac97e9d9c54a415b7af1b03f7fa4e50d8974a2e
noramark/MadLibs
/madlibs.py
1,074
4.15625
4
def story_answers(): answers = [] answers.append(raw_input("place: ")) answers.append(raw_input("relative: ")) answers.append(raw_input("name: ")) answers.append(raw_input("adjective: ")) answers.append(raw_input("adjective: ")) answers.append(raw_input("adjective: ")) answers.append(raw_input("place: ")) answers.append(raw_input("number: ")) answers.append(raw_input("plural noun: ")) answers.append(raw_input("verb: ")) answers.append(raw_input("person: ")) answers.append(raw_input("feeling: ")) answers.append(raw_input("person: ")) answers.append(raw_input("place: ")) answers.append(raw_input("verb: ")) return answers def main(story): print "Let's play Madlibs!!1! \n \n" answers = story_answers() print story.format(*answers) return story = ''' Today I went to {} with my {} {}. The weather was {}, {}, and {}. We hit the together and won {} {} We decided that she was not {} with the {}. I hope she is {} with that {}. As the night came we decided to go to a {} where people like to {}. ''' main(story)
false
a8d60fa139e4b1bde09eb1149fd89fb67c5223af
sandeepeati/eulernet
/eulerNet/p19.py
881
4.125
4
# number of sundays fell on the first day of a month in the twentieth century # function for finding a leap year or not def leap_year(year): if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True return False first_day_ly = [1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366] first_day_nly = [1, 32, 61, 92, 122, 153, 183, 214, 245, 275, 306, 336, 367] # since jan1 1900 is monday and 1900 is a non leap year, jan1 1901 is tuesday sunday = 6 count = 0 for i in range(1901,2001): if leap_year(i): while sunday <= 366: if sunday in first_day_ly: count += 1 sunday += 7 else: while sunday <= 365: if sunday in first_day_nly: count += 1 sunday += 7 sunday -= 365 print(count)
false
0cf2daf5ac411bd83f77f97212e793bd42157375
bgroveben/python2_cookbook_recipes
/ViolentPython/CH1/password_cracker.py
2,947
4.21875
4
# This file should behave the same way as 2-passwdCrack.py. # The real strength of the Python programming language lies in the wide array # of standard and third-party libraries. # To write our UNIX password cracker, we will need to use the crypt() algorithm # that hashes UNIX passwords. """ FUNCTIONS: crypt(...) crypt(word, salt) -> string word will usually be a user's password. salt is a 2-character string which will be used to select one of 4096 variations of DES. The characters in salt must be either ".", "/", or an alphanumeric character. Returns the hashed password as a string, which will be composed of characters from the same alphabet as the salt. main(...) Our main() function opens the encrypted password file "passwords.txt" and reads the contents of each line in the password file. For each line, it splits up the username and password. Then, for each individual hashed password, the main() function calls the testPass() function that tests passwords against a dictionary file. testPass(...) Our testPass() function takes the encrypted password as a parameter and returns either after finding the password or exhausting the words in the dictionary. Notice that the function first strips out the salt from the first two characters of the encrypted password hash. Next, it opens the dictionary and iterates through each word in the dictionary, creating an encrypted password hash from the dictionary word and the salt. If the result matches our encrypted password hash, the function prints a message indicating the found password and returns. Otherwise, it continues to test every word in the dictionary. """ import crypt def testPass(cryptPass): salt = cryptPass[0:2] dictFile = open('dictionary.txt', 'r') for word in dictFile.readlines(): word = word.strip('\n') cryptWord = crypt.crypt(word, salt) if (cryptWord == cryptPass): print "[+] Found Password: " + word + "\n" return print "[-] Password Not Found.\n" return def main(): passFile = open('passwords.txt') for line in passFile.readlines(): if ":" in line: user = line.split(':')[0] cryptPass = line.split(':')[1].strip(' ') print "[*] Cracking Password For: " + user testPass(cryptPass) if __name__=="__main__": main() # On modern *Nix based operating systems, the /etc/shadow file stores the # hashed password and provides the ability to use more secure hashing # algorithms. # The following example uses the SHA-512 hashing algorithm. # SHA-512 functionality is provided by the Python hashlib library. # Can you update the script to crack SHA-512 hashes? # # >>> cat /etc/shadow | grep root # [=> root:$6$ms32yIGN$NyXj0YofkK14MpRwFHvXQW0yvUid.slJtgxHE2EuQqgD74S/\ # GaGGs5VCnqeC.bS0MzTf/EFS3uspQMNeepIAc.:15503:0:99999:7:::
true
2aee8ca9320d1a146ad7a220bc0f5c546b6d714a
pandeykiran80/ProgrammingTools
/inC_1_3_divisor.py
1,542
4.1875
4
# python3.7 """ - create a function that takes an integer number as input and returns all divisors from 2 to 9 - function - fct_checkIfInt takes any input put will only proceed with integer and raise error otherwise """ #===================================================================== # modules #===================================================================== import numpy as np #-------------------my fct.------------------------------------------- def fct_find_divisor( int_no): int_no = fct_checkIfInt( int_no) a_test_div = np.arange( 2, 10, 1) l_true_div = [] for curr_div in a_test_div: print( curr_div, int_no%curr_div) if int_no%curr_div == 0: l_true_div.append( curr_div) return l_true_div def fct_checkIfInt( my_string): try: int( my_string) return int( my_string) except ValueError: error_str = "number is not an integer", my_string raise (ValueError(error_str)) #===================================================================== # params #===================================================================== #user_no = '12' # ask user for specific integer number user_no = input( "Provide an Integer Number: ") #===================================================================== # computations #===================================================================== print( 'all divisors of %s (between 2 and 9) :'%(user_no), fct_find_divisor(user_no))
true
0f8f24b7dd86b4f739efd7b3132de7420b238a24
miikahyttinen/data-analysis-python
/part01-e07_areas_of_shapes/src/areas_of_shapes.py
834
4.125
4
#!/usr/bin/env python3 import math def main(): while True: shape = input("Choose a shape (triangle, rectangle, circle):") if shape == '': break if shape == "triangle": b = input("Give base of the triangle:") h = input("Give heigth of the triangle:") print("The area is", int(b)*int(h)/2) if shape == "rectangle": b = input("Give base of the rectangle:") h = input("Give heigtht of the rectangle:") print("The area is", int(b)*int(h)) if shape == "circle": r = input("Give radius of the circle:") print("The area is", pow(int(r), 2)*math.pi) if not(shape) in ["circle", "triangle", "rectangle"]: print("Unknown shape!") if __name__ == "__main__": main()
true
7768fe748752e54bde596149bc6596ce022e3ad5
rbalaga/py-basics
/python-refresher/5.lists_tuples_sets.py
825
4.15625
4
list = ["ram", 'sujani', 'suresh'] tuple = ('ram', 'sujani', 'suresh') # constant. not able to change in future set = { "ram", 'sujani', 'suresh' } # no duplicate elements print(list[0]) print(list) list[0] = "smith" print(list) # print(tuple) # tuple[0] = "Rambabu" # gives error. # print(tuple) list.append('Chalam') # adds element at the last index print(list) list.remove('suresh') print(list) print(set) set.add('amith') print(set) set.add('amith') # duplicates will not be added. therefore set will not be altered. print(set) set.remove('suresh') print(set) print(tuple) # initialising single valued tuple tuple1 = (123,) # need to append , at last position in order to differentiate between a maths equation. which means a tuple. tuple1 = 123, # which is also represents a single valued tuple.
true
ed081d63a0c347f83b44bab8b9b67195436e3ce2
zs18034pn/ORS-PA-18-Homework05
/task2.py
614
4.40625
4
""" =================== TASK 2 ==================== * Name: Most Frequent Letter * * Write a script that takes the stirng as user * input and displays which letter has the most * occurences and how many. If two or more letters * have the same number of occurences print any. * * Note: Please describe in details possible cases * in which your solution might not work. * =================================================== """ string = input("Please enter a word or a sentence: ") maximum = 0 for i in string: if string.count(i) > maximum: maximum = string.count(i) print(i, ":", maximum)
true
bb2cdea31202b5ea49932e592fa4b80d42b5c40e
rodrikmenezes/PythonCursoUSP
/PyCursoUSP - Parte 1/semana 7/imprime_retangulo_vazado.py
673
4.46875
4
""" Escreva um programa que recebe como entradas dois números inteiros correspondentes à largura e à altura de um retângulo, respectivamente. O programa deve imprimir uma cadeia de caracteres que represente o retângulo informado com caracteres '#' na saída, de forma a desenhar um retêngulo vazado""" l = int(input('digite a largura: ')) h = int(input('digite a altura: ')) l_incremento = h_incremento = 0 while h_incremento < h: while l_incremento < l: l_incremento += 1 if h_incremento == 0 or h_incremento == h - 1: print(l_incremento * '#') else: print('#' + ' ' * (l - 2) + '#') h_incremento += 1 l_incremento = 0
false
19d2d8b5297f4ff1f66c2dc6c4b69f120459e398
rodrikmenezes/PythonCursoUSP
/PyCursoUSP - Parte 1/semana 7/imprimirFatorial_2.py
408
4.1875
4
''' Esta é uma solução mais inteligente para o probelam de imprimier fatorial ''' print('Digite um número inteiro positivo e o programa retorna o fatorial') print('Digite um número negativo para terminar') print() n = int(input('Número: ')) while n >= 0: fatorial = 1 while n > 1: fatorial = fatorial * n n -= 1 print(fatorial) print() n = int(input('Número: '))
false
48c4a9d91a344016bc993f9182d05bd963a54cfe
AvishkarKale/mycaptain-Python
/frequency-of-alphabets.py
793
4.15625
4
def most_frequent(word): """ function docstring ---------------------- entering as word as string input :enter - most_frequent(word="the word in which you want to find frequency of alphabets") """ word=word.lower() word_letters=[] counting_letters={} word_letters.clear() counting_letters.clear() count=0 while count<len(word): if word[count] not in word_letters: word_letters.append(word[count]) count=count+1 counting_letters={} j=0 while j<len(word_letters): i=0 k=0 while i<len(word): if word_letters[j]==word[i]: k=k+1 counting_letters[word_letters[j]]=k i=i+1 j=j+1 return counting_letters
true
999929b7ff61f8a15d71d5ca4159267ac14160a1
sfeng77/myleetcode
/binaryTreePostorder.py
745
4.125
4
# Given a binary tree, return the postorder traversal of its nodes' values. # # For example: # Given binary tree {1,#,2,3}, # # 1 # \ # 2 # / # 3 # # return [3,2,1]. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] st = [root] res = [] while(st): n = st.pop() res = [n.val] + res if n.right: st += [n.right] if n.left: st += [n.left] return res
true
042ac3ca80f3083dcabb68c4b5cfef3df82ce9ec
sfeng77/myleetcode
/fractionToRecurringDecimal.py
1,658
4.1875
4
""" Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, return "0.5". Given numerator = 2, denominator = 1, return "2". Given numerator = 2, denominator = 3, return "0.(6)". """ class Solution(object): def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ if numerator == 0: return "0" if(numerator < 0) and (denominator < 0): return self.fractionToDecimal(-numerator, - denominator) elif numerator < 0: return "-"+self.fractionToDecimal(-numerator, denominator) elif denominator < 0: return "-"+self.fractionToDecimal(numerator, -denominator) dn = {} dec = [] count = 0 result = str(numerator / denominator) numerator = numerator % denominator if numerator == 0: return result else: result += '.' while (numerator not in dn and numerator != 0): count += 1 dn[numerator] = count numerator *= 10 dec.append(str(numerator / denominator)) numerator = numerator % denominator if numerator == 0: return result + "".join(dec) else: idx = dn[numerator] result += "".join(dec[:dn[numerator]-1]) + "(" + "".join(dec[dn[numerator]-1:])+")" return result
true
1989e501d595fcaddd1e15d15aaa12c7c9eac10f
wfordh/coding_puzzles
/newton_roots.py
638
4.125
4
import numpy as np def newton_sqrt(init_num, x0, err = 0.0001): """ Simple square root finding algorithm. :init_num: Integer to find the square root of :x0: Initial guess at square root :err: error threshold """ while np.abs(x0**2 - init_num) > err: x0 = x0 - (x0**2 - init_num)/(2*x0) return x0 def newton_cube_rt(init_num, x0, err = 0.0001): """ Simple cube root finding algorithm. :init_num: Integer to find the cube root of :x0: Initial guess at cube root :err: error threshold """ while np.abs(x0**3 - init_num) > err: x0 = x0 - (x0**3 - init_num)/(3*x0**2) return x0 ## to do: write more general versions?
true
33235a9979fd8cf3990d169938e50c0203cd363e
benjamin-jones/bigfive
/bignum.py
1,123
4.46875
4
#!/usr/bin/env python # This class wraps up an integer and overrides the '<' # operator so that we can sort on the criteria that # matters for the exercise, namely the most significant # digit class IntNum: def __init__(self, val): self.val = val # Here we extract the most significant digit # of the interger and make a comparison # based on its value: # The purpose is that sorting on this criteria # will always produce the largest possible number def __lt__(rhs, lhs): msbr = int(str(rhs.val)[0]) msbl = int(str(lhs.val)[0]) if msbl < msbr: return True return False def __str__(self): return str(self.val) def main(): # The example vector, but works on any list really nums = [50, 2, 1, 9] # Convert our ints into our wrapper class for easy comparison list_of_IntNums = [IntNum(x) for x in nums] # Sort using our new evaluation criteria list_of_IntNums.sort() # Build the string from the correctly sorted list of ints print "".join(str(x.val) for x in list_of_IntNums) main()
true
2176af7228bf7eba18e69ef05dfc228a1cdc6b4a
gw-acm/Python-Workshop
/lists.py
717
4.21875
4
# create two lists list1 = [4, 3, 6, 1, 10, 2, 5, 9, 8, 7] list2 = [] #lets add a data element to the list list1.append(11) # lets add multiple elements to the list list2[0:5] = [2,3,4,5,6,4] #lets sort out the elements of the lists list1.sort() list2.sort() print list1 print list2 #lets create a new list and store the combined values of list1 and list2 list3 = list1+list2 print list3 #we should probably sort them out, right? list3.sort() print list3 # we can also create a list from a subsection of a list # this takes out the values from index 4 until 6 list4= list3[4:7] print "list4" print list4 # side note:this trick also works on strings string1 = "My name is Lucas" print string1[3:8]
true
13aea87a7c23b26fe5544d4737b77bf410f1b916
J-C-L/core-problem-set-recursion
/part-1.py
1,479
4.28125
4
# There are comments with the names of # the required functions to build. # Please paste your solution underneath # the appropriate comment. # factorial def factorial(n): if n < 0: raise ValueError("Number must be greater than zero") elif n == 0: return 1 return n * factorial(n - 1) # reverse def reverse(word): if len(word) <= 1: return word return word[-1] + reverse(word[1:-1]) + word[0] # bunny def bunny(count): if count == 0: return 0 return 2 + bunny(count - 1) # is_nested_parens # Original solution def is_nested_parens(parens): if not parens: return True return False if not (parens[0] == '(' and parens[-1] == ')') else is_nested_parens(parens[1:-1]) ''' I'm curious about the solution for the Challenge, but not sure I fully understand what the hint is suggesting. It said: For an additional challenge, implement is_nested_parens without creating new strings in the process of solving the problem. HINT said: Sometimes we create extra helper functions that can store more information in their parameters than we might use in the main solution function. ''' # Potential solution for the challenge, but may have misunderstood def check_set(parens_pair): return parens_pair == ("(", ")") def is_nested_parens(parens): if not parens: return True return False if not check_set((parens[0], parens[-1])) else is_nested_parens(parens[1:-1])
true
e91a312da805e201e33f1ec512b125702dfef0ac
AmitAps/python
/thinkpy/condition3.py
268
4.3125
4
choice = input("Input a choice from A,B,C oR a,b ,c : ") if choice == 'a' or choice == 'A': print('A') elif choice == 'b' or choice == 'B': print('B') elif choice == 'c' or choice == 'C': print('C') else: print('Sorry wrong choice! Please try again')
false
95855c22d8d07f28c57641a993592bad8768c48a
AmitAps/python
/hfp/ch7/tkinter_0.py
686
4.25
4
#Import everything from the tkinter module. from tkinter import * #Create a tkinter application window called "app". app = Tk() #Give the window a name. app.title("First tkinter application") #provide window coordinates and size values. app.geometry('650x300+400+200') #To add a button to your application, use code like this, being sure to put these two lines of code before the call to mainloop(): #Add a button to the window and give it some text and a width value. b1 = Button(app, text = "Click me!", width = 10) #The pack() method links the newly created button to the existing window. b1.pack(side = 'bottom', padx = 10, pady = 10) #Start the tkinter event loop. app.mainloop()
true
18bf754762b903c83f67acd8ef007011aaf428e6
AmitAps/python
/thinkpy/inoperator.py
224
4.125
4
word1_input = input("Enter a word: ") word2_input = input("Enter a word again: ") def in_both(word1, word2): for letter in word1: if letter in word2: print(letter) in_both(word1_input, word2_input)
true
6a5c7595ba4ea3d44ec8c3d0bce9006711496c33
AmitAps/python
/thinkpy/funcsrecursion.py
332
4.15625
4
n = int(input('Enter an integer: ')) s = input('Enter a string: ') def print_n(s, n): if n <= 0: return print(s) print_n(s, n-1) print_n(s, n) #If n <= 0 the return statement exits the function. The flow of execution immediately returns to the caller, and the remaining lines of the function don’t run.
true
2047dfe6baedc39dc6283924bd979dd1908c3be5
AmitAps/python
/hfp/ch3/funcwithparam.py
1,133
4.34375
4
#A parameter is a value that you send into your function. Think of it as the opposite of what you get when you return a value from a function. #The parameter’s value works just like a variable within the function, except for the fact that its initial value is set outside the function code: #To use a parameter in Python, simply put a variable name between the parentheses that come after the definition of the function name and before the colon. #Then within the function itself, simply use the variable like you would any other: def shout_out(the_name): #The parameter name goes here. return ("Congratulations " + the_name + "!") #Use the parameter's value in your function's code just like any other variable. #Later, invoke the function from your code with a different parameter value each time you use the function: print(shout_out('Wanda')) msg = shout_out('Graham, John, Michael, Eric, and Terry by 2') print(msg) print(shout_out('Monty')) #When a variable's value can be seen by some code, it is said to be “in scope.” #When a variable's value CANNOT be seen by some code, it is said to be “out of scope.”
true
9b4f3f70a0caa2c75d7e81d3d57390e8407ed832
dimas-latief/playground
/no3/customer.py
1,169
4.28125
4
class Customer(): '''this is where we create new customer created''' def __init__(self, name, group, created_since_in_years = 2): '''the constructor when creating the customer something like the minimum requirement of creating the customer''' self.name = name self.group = group.lower() self.created_since_in_years = created_since_in_years list_group = ("employee", "affiliate", "customer") # we need to throw error if not match with the list of the customer group if (self.group not in list_group): raise Exception('I am sorry, the group is not in the list.') print("Customer object created with name {} within group {} and join since {} years ago".format(self.name, self.group, self.created_since_in_years)) def check_discount_rules(self): '''every group have different discount''' if self.group == "employee": return 0.3 elif self.group == "affiliate": return 0.1 elif self.group == "customer" and self.created_since_in_years >= 2: return 0.05 else: return 1
true
430f12edf94bce0e162773fca13502f8eb6c482e
SeshadriKolluri/algorithms-course-1
/integer_multiplication_quiz1.py
1,686
4.21875
4
# Recursive method for integer multiplication # Basic Idea: We will divide the numbers into left and right halves (by number of digits), and recursively apply the multiply integers # function. If one of the numbers is too small, zeroes will be appended to left to make the numbers have equal number of digits. def multiply_ints(num1, num2): #print num1, num2 import sys # Base case if len(str(num1)) == 1 or len(str(num2)) == 1: return num1*num2 else: ndigits1 = len(str(num1)) ndigits2 = len(str(num2)) n = max(ndigits2,ndigits1) # Take last n/2 digits of the num1 as 'b' b = int(str(num1)[-1*int(n/2):]) # Take any remaining digits to the left of 'b' as 'a'. If no digits are remaining, we will assign 'a' to be zero. if(ndigits1 > n/2): a = int(str(num1)[:-1*int(n/2)]) else: a = 0 # Take last n/2 digits of the num2 as 'd' d = int(str(num2)[-1*int(n/2):]) # Take any remaining digits to the left of 'd' as 'c'. If no digits are remaining, we will assign 'c' to be zero. if(ndigits2 > n/2): c = int(str(num2)[:-1*int(n/2)]) else: c = 0 return multiply_ints(b,d) + pow(10,int(n/2))*(multiply_ints(a,d)+multiply_ints(b,c)) + pow(10,2*int(n/2))*multiply_ints(a,c) num1 = 3141592653589793238462643383279502884197169399375105820974944592 num2 = 2718281828459045235360287471352662497757247093699959574966967627 # Checking the algorithm against the built-in multiplication function in python if(num1*num2 == multiply_ints(num1,num2)): print str(num1)+ ' * ' + str(num2) + ' = ' + str(multiply_ints(num1,num2)) else: print 'your program does not work: ' str(num1)+ ' * ' + str(num2) + ' != ' + str(multiply_ints(num1,num2)) else:
true
6470da3ec6a2e275bafcf0fd74da2e8019a39bef
pblaszk/python_is
/exercises/day_02.py
1,689
4.125
4
#Lesson 2 #Pobieranie danych od uzytkownika # imie = input("Jak masz na imie? ") # nazwisko = "Blaszkiewicz" # print(imie) # print(nazwisko) #zdanie = "piotrek ma kota" #Capitalize - duza litera na poczatku #print(zdanie.capitalize()) #komentarz wielonijkowy # hej = '''Hej # milo # Cie # widziec''' # # print(hej) # liczba_1 = 123 # liczba_2 = 4.5 # #konwersja na liczbe # liczba_3 = int("15") #print(liczba_1//liczba_3) # tekst_1 = "Milo " # tekst_2 = "Cie widziec" # print(tekst_1 + tekst_2) #Znaki biale # zdanie_1 = "Hej\nPiotr" # zdanie_2 = "Hej\tPiotr" # zdanie_3 = "Hej\\tPiotr" # zdanie_4 = r"Hej\ntPiotr" # print(zdanie_1) # print(zdanie_2) # print(zdanie_3) # print(zdanie_4) # imie = input("Jak masz na imie? ") # nazwisko = "Blaszkiewicz" # # print(imie + '\n' + nazwisko) #sprawdzanie typu zmiennej # zmienna = input("Wpisz coś: ") # typ = type(zmienna) # print(typ) # liczba_1 = input("Liczba 1:") # liczba_2 = input("Liczba 2:") # n_1 = float(liczba_1).conjugate() # n_2 = float(liczba_2).conjugate() # print(n_1 + n_2) # wartosc_1 = input("Wartosc 1:") # wartosc_2 = input("Wartosc 2:") # n_1 = float(liczba_1) # n_2 = float(liczba_2) # print((n_1 + n_2).conjugate()) # # sprawdzanie dlugosci # len(zmienna) # 01234567890 # zdanie = "Ala ma kota" # print(zdanie[7]) zdanie = "Ala ma kota!" # print(zdanie[1:8:2]) # w domu pocwiczyc indeks z wartosciami ujemnymi #przedzial lewy otwarty, prawy zamkniety #print(zdanie[-1]) # zdanie = "Piotrek" # # if (zdanie == "Piotrek"): # print("Zgadza się") # else: ("Nie zgadza się") ostatni_znak = zdanie[-1] if ostatni_znak == 'a': print('Nie krzycz na mnie') else: print('Dziekuje')
false
efa470cefb16717d31780124573e5243f24c5607
stevekutz/py_hashtable
/lecture_8-4.py
1,433
4.1875
4
# Artem:lambdalogo2020: 8:08 PM # @channel Thanks for joining today, here is the code from class # hashes.py words = ["apple", "book", "cat", "dog", "egypt", "france"] # ​to access egypt, runtime is: O( n ) ## What if we had a magic function # takes a word ----> returns the index for where that word is located in some array # book -> 1 # egypt -> 4 # fake_word -> None # this function is O(1) # HASH FUNCTIONS # Any string input ---> A specific number (within some range) # MOST IMPORTANT: # This function must be deterministic # Same input will always return the same output def my_hash(s, limit): # take every character in the string, and convert character to number # Convert each character into UTF-8 numbers string_utf = s.encode() total = 0 for char in string_utf: total += char total &= 0xffffffff # limit total to 32 bits return total % limit hash_table = [None] * 8 # ADD items to hash_table using the my_hash function # Hash the key to get an index # Store the value at the generated Index index = my_hash('Hello', len(hash_table)) hash_table[index] = 'Hello value' index = my_hash('World', len(hash_table)) hash_table[index] = 'World value' # # Retrieve some items from hash_table # # Lets retrieve the value for "Hello" index = my_hash('World', len(hash_table)) print(hash_table[index]) # should be "World Value" print(hash_table)
true
e0cb09e427d7e2b1cbe80f3ddf57bb066dcc4b1b
Innocent19/week3_day3
/day four/app/power.py
237
4.28125
4
a = int(input("Enter integer a : ")) b = int(input("Enter integer b : ")) def power(a,b): if b==0: return 1 if b<0: return 1/a*power(a,b+1) return a*power(a,b-1) print(power(a,b))
false
11d59fcfaf9e5dc5f524db48836ca782a875b8f3
cabulioj8165/cabulio_jake
/cabulio_jake-master/Pylesson_05/DiceRoll.py
687
4.15625
4
import random import time print("This is a dice roll game.") print("The person with the highest score wins.") enter = input("Press enter for the numbers.") amountTime = input("The numbers will appear in three seconds. Press enter to begin timer.") time.sleep(1) print("3") time.sleep(1) print("2") time.sleep(1) print("1") time.sleep(1) num1 = random.randint(1 , 7) num2 = random.randint(1 , 7) print("Your number is:" , num1) time.sleep(1) print("The computer's number is:" , num2) if num1 > num2: time.sleep(1) print("You win!") elif num1 < num2: time.sleep(1) print("You lose! Better luck next time! ") elif num1 == num2: time.sleep(1) print("It is a tie!")
true
85303df8f7f01af73f160c1e7b7a86aa7d47b95b
nirav-Hub4yoU/14-Days-Internship-AkashTechnolabs
/six.py
292
4.1875
4
num = int(input("Enter a Number :")) factorial = 1 if num < 0: print("Factorial Does not exist ") elif num == 0: print("The Factorial of 0 is 1") else: for i in range(1, num + 1): factorial = factorial * i print("The Facorial of ", num, "is ", factorial)
true
565ca15b4fb17eaaf602059896f49a3e5a02c6b9
jacko8638/Computational-Thinking
/find 7.py
662
4.375
4
import math # this subroutine checks the length of the list to check it isn't empty and to find all the numbers #divisable by 7 and adding them to a list def findDivSeven(inputList): if len(inputList) == 0: print ("The inputted list is empty") else: outputList = [] for i in inputList: if i % 7 == 0: outputList.append(i) if len(outputList) == 0: print ("There are no numbers divisible by 7") else: return outputList #this is the list of numbers intList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,123,45678,890] #this is the main program print(findDivSeven(intList))
true
cb4c4b3fb24d7ed619369fdebe67c5984f68166b
Alicho220/python_practice
/python practice/Dictionary.py
480
4.40625
4
# key value pair eg a phone book.. # name to a contact detail where name is the key and the cd is the value # use string for the key and anytype for the value # you can get the value associtaed with a key using index.. which is a name of a key. point = {"x":1, "y":2} point = dict(x=1,y=2) print (point) # to get an index use the get function.. x = point.get("x") print(x) # you can also delete an element del point["x"] # loop for key in point: print(key, point[key])
true
1589c97bdacc733dd0ac891b9c8bfea689c85a8b
Alicho220/python_practice
/python practice/Turples.py
571
4.4375
4
# use it to in a position where you dont want to accidentally edit elements.. # read only list that can not be modified () point =(1, 2, 4) point2 = 1, 2 point3 =() # you can concartinmate two turples # * is used to replicate the turple point4 = point + point2 print(point4) point5 = point * 3 print(point5) # list can be converted to a turple using a turple function.. list1=tuple([1,2]) list2= tuple("Hello world") print(list2) print(list1) # you can find the range of element in a turple point = point[0:2] print(point) if 2 in point: print("Exist")
true
03602c9f40392d9977b4be2420c1eaa4340ec28d
brendanjang/Algorithms-Practice
/binarySearch.py
911
4.1875
4
# binary search algorithm # params: list and item to search for def binary_search(list, item): # low and high values to keep track of which part of list to search low = 0 high = len(list) - 1 # while not narrowed down to 1 element while low <= high: # start with checking middle (index) element mid = (low + high) // 2 guess = list[mid] # if middle element is correct element, return element if guess == item: # return index of item return mid # if guess is too high, new high value is 1 less than mid val if guess > item: high = mid - 1 # if guess is too low, new low value is 1 more than mid val else: low = mid + 1 # if item not in list, return null return None my_list = [1, 3, 5, 7, 9] print(binary_search(my_list, 9)) print(binary_search(my_list, -1))
true
22c9a6f38debe2bd9579b9c68e7d8cc02e4832a2
chessai/Numerical-Analysis-Examples
/Python/mullersmethod.py
911
4.1875
4
import math def f(x): #function example return math.exp(x) - 2*x**2 def muller(f): ''' Implementation of Muller's method, a generalization of the secant method of root finding. Args: f: A function whose root is to be found. Returns: x: Floating point representing f's real root. ''' x0 = input("x0: ") x1 = input("x1: ") x2 = input("x2: ") eps = 1e-6 x = x0 it = 0 while (math.fabs(f(x)) > eps): h = x0 - x2 hi = x2 - x1 hj = x1 - x0 l = hi/hj d = 1 + l g = (l**2) * f(x0) - (d**2) * f(x1) + (l + d) * f(x2) c = l * (l * f(x0) - d * f(x1) + f(x2)) l = min((-2 * d * f(x2)) / (g + math.sqrt((g**2) - 4 * d * f(x2) * c)), (-2 * d * f(x2)) / (g - math.sqrt((g**2) - 4 * d * f(x2) * c))) x = x2 + (x2 - x1)*l x2,x1,x0 = x,x2,x1 return x print muller(f)
true
4519b53a6f11e5d902e713a020c33daf58050cef
FarkasGao/LearnPython
/Chapter8/Exercise/8_8.py
859
4.125
4
def make_album(singer, album, song_number = None): if song_number: album_info = {"singer": singer, "album": album, "song number": song_number} else: album_info = {"singer": singer, "album": album} return album_info album = make_album("jay", "Twelve new", 12) print(album) album = make_album("jay", "A magic jay", 11) print(album) album = make_album("jay", "November Chopin", 12) print(album) while True: print("(enter 'quit' at any time to quit)") singer = input("Please enter the name of the artist: ") if singer == 'quit': break album = input("Please enter the name of the album: ") if album == 'quit': break song = input("Please enter the number of songs from the album: ") if album == 'quit': break album_info = make_album(singer, album, song) print(album_info)
true
c80e6d2be3fe9580a39fdca0bfe044294398389a
p0leary/cs1301x
/4.3.4.py
456
4.1875
4
def multiply_strings(string_list): # for item in string_list[::2]: # item *= 2 # print(item) # for item in string_list[::3]: # item *= 3 # print(item) # return string_list for i in range(0,len(string_list)): if i % 2 == 0: string_list[i] *= 2 if i % 3 == 0: string_list[i] *= 3 return string_list test_list = ["A", "B", "C", "D", "E", "F", "G"] print(multiply_strings(test_list))
false
e8d3dffd298af13435d86977b20b665657fd4165
P-Tasty/ProjectEuler
/Euler-1.py
562
4.28125
4
import math """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ #With first 4 numbers given we'll start with 9 x = 9 #Create an array of existing numbers mults=[3, 5, 6, 9] #Check for every multiple of 3 & 5 while (x < 999): x = x + 1 if (x % 5 == 0) or (x % 3 == 0): mults.append(x); print x z = 0 #Find the sum of multiples for y in mults: z = z + y #Print sum of multiples print z
true
98da888d2601294f509cb2ba440eb4dd2a706b4c
debryc/LPTHW
/ex15.5.py
534
4.15625
4
filename = raw_input( "What file do you want to open and read?: ") txt = open(filename) print "Here's your %r file: " % filename print txt.read() filename_again = raw_input( "What file do you want to open and read again?: ") txt_again = open(filename_again) print "Here's your %r file again: " % filename print txt_again.read() # Using raw_input instead of command line arguments # is better for users who need the prompting. Using # command line arguments instead of raw_input useful # for speed. txt.close() txt_again.close()
true
c92c50974906711ba299f04599c268e490b17bc5
edoga7/git-flow-solution
/lessthan-10.py
967
4.40625
4
my_nums = [2, 3, 4, 35, 12, 2, 76, 1, 55, 85, 61, 5] # less_than_10 = [] # # to list numbers and display the onces less that 10 # # the num variable will not be defined initially but will assume each value of my_nums # for num in my_nums: # if num < 10: # # the append adds the required value to the initialized less_than_10 # less_than_10.append(num) # # print(less_than_10) # print(less_than_10) # method 2 same as above method # the print statement below: # 1. initializes an empty array # 2. begins to append num in the array # 3. from the list my_nums # 4. based on the condition that num less or greater than 10 # print([num for num in my_nums if num > 10]) # method 3:filter # lambda is used as an annonemous function which takes num as aurgument # and performs the operations after the column. it returns true or false based # on the outcome of the performed operation print(list(filter(lambda num: num < 10, my_nums)))
true
e898b960fee240817e4266ae8e2f9a25584b4a1d
z0k/PHY224
/square_cube.py
209
4.5
4
#Input a number that is converted to an integer. number = int(input("Enter a number: ")) #Conditional to check if the number is even or odd. if number % 2 == 0: print number**2 else: print number**3
true
82007a8253497973ad9dc7bcaa517e06bbb813cf
z0k/PHY224
/Assignment1/Exercise_2.py
661
4.375
4
#Assignment 1 #Exercise 2 #String to convert is created. person = 'Franklin Delano Roosevelt' #A list is created with each name as an object in the order shown above. list_person = person.split() #The middle object is assigned to a variable as a string. middle_name = list_person[1] #The first character of the middle name is taken as the middle initial and a #period is concatenated to it. list_person[1] = middle_name[0] + '.' #full_name = list_person[0].capitalize() + ' ' + middle_initial.capitalize() + ' ' + list_person[2].capitalize() #The 'full_name' string is created from the objects in the list. full_name = ' '.join(list_person) print full_name
true
1d066eafa59c014901be60ec07485800a5fbab6f
CThax12/Computer-Science-2
/HW1/PrimeNumberTest.py
1,568
4.21875
4
# I use a for loop and start with 2 then divide by every number up until the entered one. This checks to see if any number can divide into it and prove it is not a prime number. # I also added a function to list out the factors for numbers that are not prime. from symbol import factor import math #(make an is prime function) Make a function for testing whether a number is prime. # Prints out the list of factors. def listFactors(number): factors = 'Factors: ' for j in range(2, number): if (number % j == 0): factors += str(j) + ',' factorList.append(j) print(factors.rstrip(',')) def isNumberPrime(testNumber): for i in range(2, testNumber-1): if (testNumber % i == 0): isPrime = False return isPrime else: isPrime = True return True def getPrimeFactors(num): while num % 2 == 0: primeFactors.append(2) num = num / 2 for i in range(3,int(math.sqrt(num))): while num % i== 0: primeFactors.append(i) num = num / i # Condition if n is a prime # number greater than 2 if num > 2: primeFactors.append(num) # Use this function to find the number of prime numbers less than 10000. # Ask if user would like to check a number. userNumber = int(input('Enter number to get the prime factors. \n')) primeFactors = [] getPrimeFactors(userNumber) print(primeFactors)
true
4da8e51926d82a8d752cd37f3a018693ea82ab18
lmacionis/Exercises
/4. Functions/Exercise_8.py
389
4.5
4
# Write a function area_of_circle(r) which returns the area of a circle of radius r. import math # importing math because of pi def area_of_circle(r): """ Formula of the circle area""" s = math.pi * r ** 2 return s # Makes a function fruitful. # now that we have the function above, let us call it. r = int(input("Radiuis of a cicrle: ")) s = area_of_circle(r) print(s)
true
b6a2abfc1d5a1241445f13484bb47e6d9061b730
lmacionis/Exercises
/7. Iteration/Exercise_11.py
698
4.5625
5
""" Revisit the drunk pirate problem from the exercises in chapter 3. This time, the drunk pirate makes a turn, and then takes some steps forward, and repeats this. Our social science student now records pairs of data: the angle of each turn, and the number of steps taken after the turn. Her experimental data is [(160, 20), (-43, 10), (270, 8), (-43, 12)]. Use a turtle to draw the path taken by our drunk friend. """ import turtle wn = turtle.Screen() wn.bgcolor("hotpink") wn.title("Pirate") pirate = turtle.Turtle() # Good example off the loop for the list. for angle, steps in [(160, 20), (-43, 10), (270, 8), (-43, 12)]: pirate.left(angle) pirate.forward(steps) wn.mainloop()
true
4f656da5a93cc18de0e2922ba0c52b3a0c6a3b5c
lmacionis/Exercises
/4. Functions/Exercise_5.py
1,216
4.15625
4
# The two spirals in this picture differ only by the turn angle. Draw both. import turtle def spiral(t, sz): # Function. for i in range(1): t.forward(sz) t.right(angle) t.forward(sz) tess.right(angle) wn = turtle.Screen() # Set up the window and its attributes. wn.bgcolor("lightgreen") wn.title("Spirals") tess = turtle.Turtle() # Create tess and set up tess turtle. tess.color("hot pink") tess.speed(6) n = 40 # Define variables. sz = 5 angle = 90 tess.penup() # Turtles position tess.forward(-200) tess.pendown() for i in range(n): spiral(tess, sz) # Calling function. sz += 5 tess.stamp() # Turtles last position on the spiral, when finished. tess.penup() # Turtles new position for the new spiral. tess.goto(200, 0) tess.pendown() angle = 89 # Redefine variables. sz = 5 for i in range(n): spiral(tess, sz) # Calling function. sz += 5 tess.stamp() # Turtles last position on the spiral, when finished. wn.mainloop() # Wait for user to close window.
true
00eba2618c00168be4a2fe14d1db2795119b2d61
lmacionis/Exercises
/8. Strings/Exercise_4.py
497
4.3125
4
""" Now rewrite the count_letters function so that instead of traversing the string, it repeatedly calls the find method, with the optional third parameter to locate new occurrences of the letter being counted. """ # Answer is from: https://sites.google.com/site/usfcaixcacerescs110/homework-06 def count_letters(str, ch, start): index = start while index < len(str): if str[index] == ch: print(index) index += 1 return -1 count_letters("banana", "a", 0)
true
78b1fac7782b8e0c9047da5dd97cb2eeb4e0c7a4
lmacionis/Exercises
/7. Iteration/Exercise_2.py
276
4.21875
4
""" Sum up all the even numbers in a list. """ list = [1, 2, 3, 4, 5, 6, 7, 8, 8] def even_num(n): even_num_sum = 0 for i in n: if i % 2 == 0 : even_num_sum = even_num_sum + i return even_num_sum print(even_num(list)) # Done by the book
true
ea8798f6ad0b05b29b6563cf623cc3e232dc808c
lmacionis/Exercises
/11. Lists/Exercise_5.py
1,475
4.65625
5
""" Lists can be used to represent mathematical vectors. In this exercise and several that follow you will write functions to perform standard operations on vectors. Create a script named vectors.py and write Python code to pass the tests in each case. Write a function add_vectors(u, v) that takes two lists of numbers of the same length, and returns a new list containing the sums of the corresponding elements of each: test(add_vectors([1, 1], [1, 1]) == [2, 2]) test(add_vectors([1, 2], [1, 4]) == [2, 6]) test(add_vectors([1, 2, 1], [1, 4, 3]) == [2, 6, 4]) """ import sys # Found in a stackoverflow and modified by my conditions. def add_vectors(v1, v2): newVector = [] for index in range(len(v1)): newVector.append(v1[index] + v2[index]) # append is a list method which adds the argument passed to it to the end of the list. return newVector def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def test_suite(): """ Run the suite of tests for code in this module (this file). """ test(add_vectors([1, 1], [1, 1]) == [2, 2]) test(add_vectors([1, 2], [1, 4]) == [2, 6]) test(add_vectors([1, 2, 1], [1, 4, 3]) == [2, 6, 4]) test_suite() # Here is the call to run the tests
true
024f74eaf2c37eeb8c62993db6aaa497d35e4a79
ov1618/oviya
/day15.py
563
4.125
4
#number pyramid ''' num=5 for i in range(num): for j in range(i): print(j+1,end='') print() ''' #reverse pyramid ''' num=5 for i in range(num,0,-1): for j in range(i): print(j+1,end='') print() ''' #to get pyramid using odd length ''' num=5 for i in range(1,num+1): i=i*2-1 for j in range(1,i+1): print(j,end='') print() ''' #to get alpha as pyramid ''' num=5 for i in range(1,num+1): k=65 for j in range(i): print(chr(k),end='') k=k+1 print() '''
false
ca15a533f5476a020a31568e0255e37d04798fd4
damade/PythonPro
/Decorator/Decorators.py
672
4.65625
5
"""Decorators supercharges our function. It simply a function that accepts a function, wraps a function into another function and then enhances it or changes it""" def my_decorator(func): def wrap_func(): print("*************") func() print("*************") return wrap_func @my_decorator def hello(): print("hellloooo") @my_decorator def bye(): print("See you later") def helloa(): print("hellloooo") hello2 = my_decorator(helloa)() """"So function hello() is the same as helloa() irrespective of the method being used, although using Decorators makes it fasters""" hello(); print("\n") bye(); print("\n") hello2;
true
44f1010c333f7e59d1e488f8c013c46fcc149375
damade/PythonPro
/Basic Beginners Programs/PrimeNumber.py
296
4.125
4
def checkprime(n): k = 0 j = 2 while (j <= (n / j)): if not (n % j): break j = j + 1 if (j > (n / j)): print(f"{n} is a prime number") else: print(f"{n} is not a prime number") n = int(input("What is your input: ")) checkprime(n)
false
9745e73b33fbc554c0c9de54176a1367b17e8451
lpincus/go-fish-game-simulator
/go_fish/Player.py
2,666
4.4375
4
""" Use the knowledge you have gained to write a python simulation for the game of go fish. In go fish each person gets 5 cards with the remainder of the deck left as a draw pile or ‘pond’. At each turn one player asks another player if they have any cards of a given rank, such as 2, 10, King, Ace. If the opponent is holding such a card or many cards of the requested rank, regardless of the suit (diamonds, clubs, hearts, spades) they must give the card to the requestor. This is a ‘win’ for the requesting player, and they remove the cards from play. This increases the point count for the winning player’s score. If the requestor does not have a card they respond ‘go fish’ and the requestor must draw from the pond. Play continues until either all the cards are exhausted or there are no additional plays that can be made (e.g. each remaining card in play is of unique rank). Some considerations for your game: - Start simple - just two players, a single deck of cards, each person gets a turn in alternating fashion - Gradually get more complex - move to three and up to 4 players, change the rules to let a win result in an additional turn for that player until they don’t get a win, choose randomly for the starting player. - Run the simulation many times (1000) and see if any one player wins more than the others. """ from go_fish.CardDeck import CardDeck class Player: """ Player of go-fish, can - get 5 cards - ask other player for card of given rank - get asked for card of given rank & give card of given rank (or say go fish) - get card of given rank """ def __init__(self, name): self.name = name self.cards = CardDeck() self.cards.get_deck([]) self.points = 0 def __str__(self): return self.name def get_card(self, card): if type(card) is None: raise Exception("asdf") self.cards.append(card) def get_cards(self, cards): for card in cards: self.get_card(card) def win_cards(self, cards): for card in cards: # print("player", self, "won cards", cards) self.points = self.points + 1 def get_asked_for_cards(self, rank): cards_of_rank = self.cards.get_cards_of_rank(rank) self.cards.remove_cards(cards_of_rank) return cards_of_rank def random_suit(self): random_suit = self.cards.random_suit() return random_suit def out_of_cards(self): return not self.has_cards() def has_cards(self): if len(self.cards) > 0: return True return False
true
a22a59a5b4e9a0338edd8453d08ea671257fc249
FuJames/leetcode
/python/Ugly Number.py
992
4.28125
4
# coding:utf8 # Write a program to check whether a given number is an ugly number. # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. # Note that 1 is typically treated as an ugly number. # 理解题意: # 一个数字的因子指的是能够被这个数字整除的质数 # 因此,因子是本身不能再分解的数字 # 8是ugly number # 因此,一个数如果是ugly number,就一定能整除2或3,或5,直到商为1 import math class Solution(object): def isUgly(self, num): if num <= 0: return False if num == 1: return True while num % 2 == 0: num /= 2 while num % 3 == 0: num /= 3 while num % 5 == 0: num /= 5 if num == 1: return True return False s = Solution() print s.isUgly(2) print s.isUgly(4) print s.isUgly(14)
false
78df1d985db44a963ca6a7b353fa8e56261254a8
michael-grace/SOF1
/Week 2 Practical 2/P02.5 Heart Rate.py
468
4.25
4
'''Heart Rates''' max_rate = 208 - 0.7*int(input('Age: ')) heart_rate = int(input('Heart Rate: ')) if heart_rate >= 0.9*max_rate: print('Interval Training') elif (heart_rate >= 0.7*max_rate) and (heart_rate < 0.9*max_rate): print('Threshold Training') elif (heart_rate >= 0.5*max_rate) and (heart_rate < 0.7*max_rate): print('Aerobic Training') elif heart_rate < 0.9*max_rate: print('Couch Potato') else: print('Please enter a valid heart rate')
false
12a65ee77653b482079cb3cefb7238b2701c6b0a
mmmvdb/pythonPractice
/os/madLibs/madLibs.py
1,230
4.65625
5
# madLibs # This is going to take in a file, scan it for all the all caps words "ADJECTIVE", "NOUN", "ADVERB", "VERB" # then offer the user the ability to enter text to replace each one. Then we'll print the results to screen # and place the results in a file. import re # ==== Read in text file ==== madLibFile = open('madLib.txt') madLibString = madLibFile.read() print(madLibString) # The ADVERB NOUN ADJECTIVE VERB the NOUN's VERB. madLibSearch = re.compile(r'^(.*?)(ADJECTIVE|NOUN|ADVERB|VERB)(.*?)$') search = madLibSearch.search(madLibString) # ==== Loop over results where we find one of the keywords ==== while search != None: # prompt user for a replacement if search.group(2)[0] == 'A': replaceWord = input("Enter an " + search.group(2).lower() + ':') else: replaceWord = input("Enter a " + search.group(2).lower() + ':') # perform the replace madLibString = search.group(1) + replaceWord + search.group(3) search = madLibSearch.search(madLibString) # Take the string and append it to the result file and print the result resultFile = open('madLibResult.txt', 'a') resultFile.write(madLibString + '\n') resultFile.close() print(madLibString)
true
3bcc9d19167e983950d97f1f109153b25d62461a
noirvin/SPD-Technical-Interview-Practice
/excercism/leap.py
459
4.25
4
''' check if a given year is a leap year assumption: input is going to be years from gregorian calendar ''' def leap_check(year): # check if year is divisible by 4 and either indivisible by 100 or divisible by 400, # then it's leap year if year%4==0 and (year%100!=0 or year%400==0): return True # when it's a common year else: return False print(leap_check(1987),leap_check(-1987),leap_check(2000),leap_check(1200))
false