blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
11e98696fcd9a55656faf04307df23a648be4251
RyanBuitenhuis/pythonstartup
/rps.py
1,542
4.3125
4
# Rock, Paper, Scissors # Written by: GitHub @RyanBuitenhuis import random def rps(): user = input("Choose your option [rock, paper, scissors]: ") computer = random.choice(['rock', 'paper', 'scissors']) print() #Verification on input. if user == 'rock' or user == 'paper' or user == 'scissors': print('The user chose: ', user) print('The computer chose: ', computer) print() #User loses if user == 'rock' and computer == 'paper': print("The computer wins") elif user == 'paper' and computer == 'scissors': print("The computer wins!") elif user == 'scissors' and computer == 'rock': print("The computer wins!") # Computer loses. if computer == 'rock' and user == 'paper': print("Congratulations, you win!") elif computer == 'paper' and user == 'scissors': print("Congratulations, you win!") elif computer == 'scissors' and user == 'rock': print("Congratulations, you win!") #User and Computer tie. if user == 'rock' and computer == 'rock': print("It is a draw!") elif user == 'paper' and computer == 'paper': print("It is a draw!") elif user == 'scissors' and computer == 'scissors': print("It is a draw!") #End of the verification, if values don't match, force a new one. elif user != 'rock' or user != 'paper' or user != 'scissors': print("Enter a valid value!")
true
bd827c9ff48aabe9d4abfe88cc93d8483a1c23e6
awbogus/wcc_v2
/Python/Post_WCC/roll_the_dice.py
1,222
4.125
4
import random dice = [1, 2, 3, 4, 5, 6] def next_step(): next_action = raw_input("Do you want to play again? Answer yes or no.") next_action = next_action.lower() while next_action == "yes": random.shuffle(dice) print "You rolled " + str(dice.pop()) + "." next_action = raw_input("Do you want to play again? Answer yes or no.") if next_action == "no": print "Okay, have a nice day!" def roll_dice(): action = raw_input("Do you want to roll the dice? Answer yes or no.") action = action.lower() if action == "yes": random.shuffle(dice) print "You rolled " + str(dice.pop()) + "." next_step() if action == "no": print "Okay, have a nice day!" if action != "yes" and action != "no": action2 = raw_input("Sorry, I don't understand. Please answer yes or no.") action2 = action2.lower() if action2 == "yes": random.shuffle(dice) print "You rolled " + str(dice.pop()) + "." if action2 == "no": print "Okay, have a nice day!" if action2 != "yes" and action2 != "no": print "Sorry, I don't understand, and I'm out of energy." roll_dice()
true
396c72c98233ed8f809e7bc0cb55ce9fa7d9ae70
Tontuch/Pythoneducation
/homework5/homework5quest2.py
640
4.125
4
#2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, # количества слов в каждой строке. with open("forquest2.txt") as p_open: a = p_open.readlines() print(a) b = len(a) print(f"количество строк в файле {b}") n = 0 while n < b: word = [el for el in a[n].split(" ")] cnt_word = len(word) print(f"количество слов в {n + 1} строке равно {cnt_word}") n += 1
false
4e819a45dff4fab460ca4cb1b6e905277476e6f2
poettler-ric/junkcode_python
/basic/queens.py
1,328
4.1875
4
#!/usr/bin/env python3 """Solve the 8 queens puzzle using backtracking.""" BOARD_SIZE = 4 def is_attacked(row, column, queens): """Checks whether a field is attacked by a list of queens.""" for q in queens: if row == q[0]: return True if column == q[1]: return True if row + column == q[0] + q[1]: return True if row - column == q[0] - q[1]: return True return False def try_row(row, queens): """Try to place the queens using backtracking""" for column in range(BOARD_SIZE): attacked = is_attacked(row, column, queens) if not attacked: # place queen tmp_queens = set(queens) tmp_queens.add((row, column)) if row == BOARD_SIZE - 1: # we are on the last row return tmp_queens else: # try to solve next row result = trying(row + 1, tmp_queens) if not result: # we couldn't find a match continue else: # we successfully could place the last queen - break recursion return result return False if __name__ == '__main__': queens = try_row(0, set()) print(queens)
true
5bb60d0c1a756fe8e324379ac6d0f2e0d8d98120
ateixeiraleal/Curso_Python
/Mundo1_Fundamentos/manipulando_texto.py
1,415
4.125
4
frase = ' Que vivam os loucos de boas cabeças, pois no Mundo em que vivemos não temos motivos para ' \ 'sermos normais. ' print('1 ->', frase) n = len(frase) # Armazena a quantidade de caracteres contidos na frase. print('2 -> A frase contém {} caracteres.'.format(n)) print('3 -> Último caractere da frase: "{}"'.format(frase[n-1])) # Escreve o elemento na posição 10. Lembrando que é contado zero. print('4 ->', frase[::2]) # Escreve a frase pulando de 2 em 2 caracteres. print('5 ->', frase[:10]) # Escreve a frase até a posição n-1. print('6 -> A palavra "cabeça" está iniciando na posição {} da frase.'.format(frase.find('cabeça'))) print('7 -> Existe a palavra "Raul Seixas" na frase? {}'.format('Raul Seixas' in frase)) print('8 -> Existe a palavra "loucos" na frase? {}'.format('loucos' in frase)) print('9 ->', frase.replace('boas cabeças', 'bons pensamentos')) print('10 ->', frase.upper()) print('11 ->', frase.lower()) print('12 ->', frase.capitalize()) print('13 ->', frase.title()) frase1 = frase.strip() print('14 -> {}'.format(frase1)) palavras = frase.split() print('15 -> A frase contém {} palavras.'.format(len(palavras))) frase2 = '_'.join(palavras) print('16 ->', frase2) print('17 -> {}'.format(palavras[3][3])) print('18 -> A frase contém {} letras'.format(len(frase) - frase.count(' '))) print('19 -> A primeira palavra tem {} letras.'.format(frase1.find(' ')))
false
54de798c2cb3e6e65581808ae698a7989becc64a
OliBirgir/assignment5.1
/sequence.py
985
4.34375
4
#The algorithm for this assignment is like this: #user tells us the length of the sequence, which means that we will print out x amount of numbers in a sequence. #the code is supposed to print out all three numbers below. # for example: 1,2,3,(3+2+1) = 6, (6+3+2) = 11.... # you will need few integers. a_int, b_int and c_int, sum and a counter, which counts the input # while the input is more or the same as the counter, it should summarize a_int, b_int and c_int. #print out the sum and add 1 to the counter #While a_int is more or the same as two, the number c will be the same as b, which leads to correct printing for 3 #then b_int becomes a_int and the a_int becomes the sum. n = int(input("Enter the length of the sequence: ")) # Do not change this line a_int = 1 b_int = 0 c_int = 0 counter = 0 sum_int = 0 while n>counter: sum_int = (a_int + b_int + c_int) print(sum_int) counter+=1 if a_int >= 2: c_int = b_int b_int = a_int a_int = sum_int
true
fa38a54b4568d16fbabbd1450d7c99a7a863632d
WillianVieira89/Python_Geek_University
/Script_Python/Estudos/Funções/funcoes_com_retorno.py
2,280
4.21875
4
""" Funções com retorno numeros = [1, 2, 3] ret_pop = numeros.pop() print(f'Retorno de pop: {ret_pop}') ret_pr = print(numeros) print(f'Retorno de print: {ret_pr}') OBS: Em Python, quando uma função não retorna nenhum valor, o retorno e None OBS: Funções Python que retornam valores devem retornar estes valores com a palavra reservada return OBS: Não precisamos necessariamente criar uma variavel para receber o retorno de uma função. Podemos passar a execução da função para outras funções. def quadrado_de_7(): return 7 * 7 # Criamos uma variavel para receber o retorna da função ret = quadrado_de_7() print(f'Retorno: {ret}') print(f'Retorno: {quadrado_de_7()}') # Refatorando a primeira função def diz_oi(): return 'Oi ' alguem = 'Pedro!' print(diz_oi() + alguem) OBS: Sobre a palavra reservada return 1 — Ela finaliza a função, ou seja, ela sai da execução da função; 2 — Podemos ter, numa função, diferentes returns; 3 — Podemos, numa função, retornar qualquer tipo de dado e até mesmo múltiplos valores; # Exemplo 1 - Ela finaliza a função, ou seja, ela sai da execução da função; def diz_oi(): print('Estou sendo executado antes do return') return 'Oi' print('Estou sendo executado após o return') print(diz_oi()) # Exemplo 2 - Podemos ter, numa função, diferentes returns; def nova_funcao(): variavel = None if variavel: return 4 elif variavel is None: return 3.2 return 'b' print(nova_funcao()) # Exemplo 3 - Podemos, numa função, retornar qualquer tipo de dado e até mesmo múltiplos valores; def outra_funcao(): return 2, 3, 4, 5 # num1, num2, num3, num4 = outra_funcao() # print(num1, num2, num3, num4) print(outra_funcao()) print(type (outra_funcao())) # Vamos criar uma função para jogar a moeda from random import random def joga_moeda(): # gera um número pseudorrandômico entre 0 e 1 valor = random() if valor > 0.5: return 'Cara' return 'Coroa' print(joga_moeda()) # Erros comuns na utilização do retorno, que, na verdade nem é erro, mas sim codificações desnecessárias def eh_impar(): numero = 6 if numero % 2 != 0: return True return False print(eh_impar()) """
false
45efcb841a95dfbab7e6ad23963b3afc0139b017
WillianVieira89/Python_Geek_University
/Script_Python/Estudos/Funções/definindo_funções.py
2,691
4.53125
5
""" Definindo Funções — Funções são pequenos partes de códigos que realizam tarefas específicas: — Pode ou não receber entradas de dados e retornar uma saída de dados: — Muito utéis para executar procedimentos similares por repetidas vezes OBS: Se você escrever uma função que realiza várias tarefas dentro dela: é bom fazer uma verificação para que a função seja simplificada. Já utilizamos varías funções desde que iniciamos este curso: - print() - len() - max() - min() - count() _ e muitas outras; """ # Exemplo de utilização de funções: cores = ['verde', 'amarelo', 'branco'] # Utilizando a função integrada (Built-in) do Python print() # print(cores) curso = 'Programação em Python: Essencial' # print(curso) cores.append('roxo') # print(cores) cores.clear() # print(cores) # print(help(print)) # DRY - Don't Repeat Yourself - Não repita você mesmo / Não repita seu código """ Em Python, a forma geral de definir uma função é: def nome_da_função(parâmetros_de_entrada): bloco_da_função Onde: nome_da_função -> SEMPRE com letras minisculas, e se for nome composto, separado por underline (Snake Case): parâmetros_da_função -> Opcionais, onde tendo mais de um , cada um separado por virgula, podendo ser opcionais ou não; bloco_da_função -> Também chamado de corpo da função ou implementação, é onde o processamento da função acontece. Neste bloco, pode ter ou não retorno da função OBS: Veja que para definir uma função, utilizamos a palavra reservada 'def' informando ao Python que estamos definindo uma função. Também abrimos o bloco de código com o já conhecido dois pontos : que é utilizado em Python para definir blocos. """ # Definindo a primeira função def diz_oi(): print('Oi') """ OBS: 1 - Veja que, dentro das nossas funções podemos utilizar outras funções 2 - Veja que nossa função so executa 1 tarefa, ou seja, a única coisa que ela faz é dizer oi 3 - Veja que está função não recebe nenhum parâmetro de entrada: 4 - Veja que está função não retorna nada """ # Utilizando funções # Chamada de execução diz_oi() """ ATENÇÃO: Nunca esqueçã de utilizar o parênteses ao executra uma função Exemplos: # Errado diz_oi # Certo diz_oi() # Errado diz_oi () """ # Exemplo 2 def cantar_parabens(): print('Parabéns para você') print('Nesta data querida') print('Muitas felicidades') print('Muitos anos de vida') print('Viva o Aniversariante') cantar_parabens() # Em Python podemos inclusive criar variaveis do tipo de uma função e executar esta função atraves da variavel canta = cantar_parabens canta()
false
ccf349df87cecb207ecfd847826776ff6b74bb8b
WillianVieira89/Python_Geek_University
/Script_Python/Estudos/Coleções/default_dict.py
903
4.21875
4
""" Módulo Collections - Default Dict # Recap Dicionarios dicionario = {'curso': 'Programação em Python Essencial'} print(dicionario) print(dicionario['curso']) print(dicionario['outro']) # ??? Key Error Default Dict → Ao criar um dicionário utilizando-o, nos informamos um valor default, podemos utilizar um lambda para isso. Este valor será utilizado sempre que não houver um valor definido. Caso tentemos acessar uma chave que não existe, essa chave será criada e o valor default será atribuido OBS. Lambda são funções sem nome, que podem ou não receber parâmetros de entrada e retornar valores. """ from collections import defaultdict dicionario = defaultdict(lambda: 0) dicionario['curso'] = 'Programação em Python: Essencial' print(dicionario) print(dicionario['outro']) # Key Error no dicionário comum, mas no default dict retorna o valor indicado print(dicionario)
false
64214ef5e0e82f364d733289841c490a8d7ba7d5
zomblzum/DailyCoding
/task_1/sum_searcher.py
342
4.15625
4
def list_contain_equal_sum(array, result): """Find sum in array function Checks the array for two elements whose sum is equal to the result """ hash_array = {} for i in array: if hash_array.get(i): return True else hash_array[result - i] = i return False
true
3b648df3e9ee4239a55a36d465863cfe8e518909
lizzycooper/daylio-stats
/moods.py
705
4.21875
4
# Get user to enter all the moods in order for analysis def create_moods(): moods_dict = {} print('Enter each mood you have configured in Daylio, taking care to go from WORST MOOD (ie. "depressed", "awful") to BEST MOOD (ie. "rad", "great"). Ensure not to make any spelling errors. Press Enter after each mood, and after entering all moods just press Enter again.') # Creates a dictionary of moods with numbers assigned e.g. {'sad': 1, 'happy': 2} i = 1 current_mood = input('Enter mood ' + str(i) + ': ') while current_mood != '': i += 1 moods_dict[current_mood] = i current_mood = input('Enter mood ' + str(i) + ': ') return moods_dict
true
51aa5c10e66d44ab8dca671c5ab2f3f20c0e740c
akrish3/HW01_SSW567
/HW1_AK_SSW567WS.py
523
4.1875
4
""" Anish Krishnamoorthy HW 1 Check if the triangle is isosceles, right , scalene or equilateral """ def classify_triangle(a,b,c): """Check the triangle""" print("Input lengths of the triangle sides: ") print("Enter values for sides of the triangle: ") a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) if a == b == c: print("Equilateral Triangle") elif a==b or b==c or c==a: print("Isosceles Triangle") elif a*a + b*b == c*c: print("Right Angled Triangle") elif a!=b!=c: print("Scalene Triangle")
false
d0021cbe3290b8c651c4fa103110f732575993a1
chloetucker/Birthday-Counter
/program.py
1,207
4.15625
4
import datetime def print_header(): print('---------------------------------') print(' BIRTHDAY APP ') print('---------------------------------') def get_user_birthday(): print("What year were you born?") year = int(input("Year: [YYYY]: ")) print("What month were you born?") month = int(input("Month: [MM]: ")) print("What day were you born?") day = int(input("Day: [DD]: ")) birthday = datetime.date(year, month, day) return birthday def days_between_dates(birthday_date, todays_date): this_year = datetime.date(todays_date.year, birthday_date.month, birthday_date.day) delta = this_year - todays_date return delta.days def print_birthday_information(days): if days < 0: print("You had your birthday {} days ago this year".format(-days)) elif days > 0: print("Your birthday is in {} days!".format(days)) else: print("Today is your birthday - happy birthday!") def birthday_app(): print_header() birthday = get_user_birthday() today = datetime.date.today() number_of_days = days_between_dates(birthday, today) print_birthday_information(number_of_days) birthday_app()
false
c3988ef259d7d1ded7fa57f29112765c697d76a9
Fitzpa/learning-python
/02_control_flow/if_else_exercise.py
527
4.34375
4
"""Write a small program that assignes the name of 2 trees to 2 variables, called tree1 and tree2. If the values of the 2 variables are equal, print the message 'The trees are the same', otherwise print 'The trees are different' This exercise system doens't allow input to be used, so don't use input on lines 1 and 2 -- just enter your text inside the quotes for the 2 trees.""" tree1 = 'Birch' tree2 = 'Bonsai' if tree1 == tree2: print("The trees are the same") else: print("The trees are different")
true
f308f8909422b49961e989b9579d2ce67059e0bc
devtrainer14/DemoPython
/2020/if_demo.py
389
4.28125
4
x = int(input("Enter Any Number")) ''' if x>10: print(x,"is greater than 10") if (x%5==0): print(x,"is divisible with 5") else: print(x,"is not divisible with 5") else: print(x,"is less than 10") ''' if x==1: print('Today is sunday') elif x==2: print('Today is Monday') else: print('Invalid Number')
true
06a37439d7b93f3226a88127b2404564065088f2
satishhiremath/LearningPython
/dictionary.py
423
4.1875
4
## dictionary is key value pairs like json classmates = {'sali': 'carrom specialist', 'manju': 'bowling specialist', 'gowli': 'yoga specialist'} print(classmates['manju']) print(classmates['sali']) print(classmates['gowli']) for i in classmates: print(i) for k, v in classmates.items(): print(k , 'is', v) for i in classmates.values(): print(i) for i in classmates.keys(): print(i)
false
12a9a5ab0940111d141717e1f553db1bfe84afe1
satishhiremath/LearningPython
/ranges.py
644
4.40625
4
# tells how to use for loop for x in range(2,7,2): print(x) print('\n') constantVal = 2 # # ''' is for commenting multiple lines ''' # tells how to use while loop while constantVal < 5: print(constantVal) constantVal += 1 ''' print(9,"satish",10,11,1993) # program to find magic number magicNumber = 5 for i in range(10): if i is magicNumber: print(i, "is a magic number") break else: print(i) print("\n \n") # write a code looping through 0-100 and printtd number divided by 4 for i in range(101): if i%4 is 0: print(i) else: continue
true
dadfef8e332fad36be1c65d5791a84b74af555b4
satishhiremath/LearningPython
/Ver-2/print_object.py
755
4.4375
4
''' Defining a class special method __str__() to print class object in informative manner Without __str__() defined, python will print object as "<__main__.Omg at 0x7f66a473d240>" After __str__() is defined, python will print object as "Class car is a object with data attributes x = 10 and y = 20" isinstance(obj, class) returns 'True' if obj is instance of class else 'False' ''' class Car(object): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "Class car is a object with data attributes x = {} and y = {}".format(self.x, self.y) if __name__ == "__main__": car = Car(10, 20) print(car) # Python by default calls __str__() method of class object print(isinstance(car, Car))
true
04bb85191c11aa0f6f01bdf5a6d6087c3ecd6694
castertab10/SquareSum
/squaresum.py
387
4.3125
4
#function that returns the sum of the squares of first n natural numbers def squaresum(n): SquareSum = 0 temp = 1 if n<= 0: print("Please enter a natural number!") else: while temp <= n: SquareSum += temp*temp temp +=1 print("The sum of the square of first ", n, "number(s) is/are: ", SquareSum)
true
b9c2ca2a4d1f690b98b0d5c4c9b4c07abdf9faff
x612skm/Data_structures
/lg.py
855
4.21875
4
loop = "true" while(loop == "true"): username = input("Enter Username: ") password = input("Enter Password: ") h = input ("Do You Need Help [Y/N]: ") if(h == "Y" or h == "y" or h == "yes" or h == "Yes"): print ("Enter username and password to login. If you do not have an account yet, enter 'Guest' as the username and press enter when it asks for the password.") elif(h == "N" or h == "n" or h == "no" or h == "No"): print (" >> ") if(username == "Hello World" and password == "Hello World" or username == "Test User" and password == "Test User" or username == "Guest"): print ("Logged in Successfully as " + username) if(username == "Guest"): print ("Account Status: Online | Guest User") if not (username == "Guest"): print ("Account Status: Online | Standard User")
true
59fd17fa0643c505143c07a5fc03f42ccece801e
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter8/text.py
1,555
4.125
4
#Chapter 8 - Exercise 4 #text.py #.py is a Python file #Create a new HTML document containing a form with a #text area field and a submit button #---<!DOCTYPE HTML> #---<html lang="en"> #---<head> <meta charset="UTF-8"> #---<title>Text Area Example</title> </head> #---<body> #---<form method="POST" action="text.py"> #---<textarea name="Future Web" rows="5" cols="40"> #---</textarea> #---<input type="submit" value="Submit"> #---</form> #---</body> #---</html> #Next, start a new Python script by making CGI handling #features available and create a FieldStorage data object import cgi data = cgi.FieldStorage() #Now, test if the text area is blank then assign its content #string or a default string to a variable if data.getvalue('Future Web'): text = data.getvalue('Future Web') else: text='Please Enter Text!' #Then, add statements to output an entire HTML web #page including posted or default values in the output print('Content-type:text/html\r\n\r\n') print('<!DOCTYPE HTML>') print('<html lang="en">') print('<head> <meta charset="UTF-8">') print('<title>Python Response</title> </head>') print('<body>') print('<h1>',text,'</h1>') print('<a href="text.html">Back</a>') print('</body>') print('</html>') #Finally, save both files in the web server's /htdocs directory #and load the HTML document in a browser then push #the form button - to see values in the response #Examine the HTTP request and response components #using browser developer tools to see that the text gets #sent as a separate message in the HTTP "Request body"
true
fd13681539df7011cc7ecbb66ad91de9dbe00d6d
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter9/tk_entry.py
1,098
4.4375
4
#Chapter 9 - Exercise 4 #tk_entry.py #.py is a Python file #Start a new Python program by making GUI features #available and message box features available as a short alias from tkinter import * import tkinter.messagebox as box #Next, create a window object and specify a title window = Tk() window.title('Entry Example') #Now, create a frame to contain an entry field for input frame = Frame(window) entry = Entry(frame) #Then, add a function to display data currently entered def dialog(): box.showinfo('Greetings', 'Welcome' + entry.get()) #Now, create a button to call the function when clicked btn = Button(frame, text = 'Enter Name', command = dialog) #Add the button and entry to the frame at set sides btn.pack(side = RIGHT, padx = 5) entry.pack(side = LEFT) frame.pack(padx = 20, pady = 20) #Finally, add the loop to capture this window's events window.mainloop() #Save the file in your scripts directory then open a #Command Prompt window there and run this program #with the command python tk_entry.py - enter your name #and click the button to see a greeting message appear
true
b639409bb13472a484180053494e9a3285d5f968
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter6/modify.py
809
4.59375
5
#Chapter 6 - Exercise #3 #Modify.py #.py is a Python file #Start a new Python script by initializing a variable with a #string of lowercase characters and spaces string = 'python in easy steps' #Next, display the string capitalized, titled, and centered print('\nCapitalized:\t', string.capitalize()) print('\nTitled:\t\t', string.title()) print('\nCentered:\t', string.center(30, '*')) #Now, display the string in all uppercase and merged with #a sequence of two asterisks print('\nUppercase:\t', string.upper()) print('\nJoined:\t\t', string.join('**')) #Then, display the string padded with asterisks on the left print('\nJustified;\t', string.rjust(30, '*')) #Finally, display the string with all occurences of the 's' #character replaced by asterisks print('\nReplaced:\t', string.replace('s','*'))
true
a3078b1cd16192331cc3b4ce00cbdf1d670b2e8f
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter3/dict.py
699
4.6875
5
#Chapter 3 - Exercise #4 #Dict.py #.py is a Python file #Start a new Python script by initializing a dictonary then #display its key:value contents dict = {'name':'Bob','ref':'Python','sys':'Win'} print('Dictionary:',dict) #Next, display a single value referenced by its key print('\nReference:', dict['ref']) #Now, display all keys within the dictionary print('\nKeys:', dict.keys()) #Delete one pair from the dictionary and add a #replacement pair then dispay the new key:value contents del dict['name'] dict['user'] = 'Tom' print('\nDictionary:', dict) #Finally, search the dictionary for a specific key and display #the result of the search print('\nIs There A name Key?:', 'name' in dict)
true
d56664f5efca2eef1391b42d9cc22606beef0155
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter2/cast.py
1,018
4.5625
5
#Chapter 2 - Exercise 7 #cast.py #.py is a Python File #Start a new Python Script by initializing two variables #with numeric values from user input a = input('Enter A Number:') b = input('Now Enter Another Number:') #Next, add statements to add the variable values together #then, display the combined result and its data type - to #see a concatenated string value result sum = a + b print('\nData Type sum:',sum,type(sum)) #Now, add statements to add cast variable values together #then display the result and its data type - to see a total #integer value result sum = int(a) + int(b) print('Data Type sum:',sum,type(sum)) #Then, add statements to cast a variable value then display #the result and its data type - to see a total float value sum = float(sum) print('Data Type sum:',sum,type(sum)) #Finally,add statements to cast an integer representation of #a variable value then display the result and its data type - #to see a character string value sum = chr(int(sum)) print('Data Type sum:',sum,type(sum))
true
b1a72357181150d931017e70248bca5fbf47dd60
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter4/raise.py
697
4.5
4
#Chapter 4 - Exercise #10 #Raise.py #.py is a Python file #Start a new Python script by initializing a variable with #an integer value day = 32 #Next, add a try statement block that tests the variable #value then specifies an exception and custom message try: if day > 31: raise ValueError('Invalid Day Number') #More statements to execute get added here #Now, add an except statement block to display an error #message when a ValueError occurs except ValueError as msg: print('The program found An', msg) #Then, add a finally statement block to display a message #after the exception has been handled successfully finally: print('But Today Is Beautiful Anyway.')
true
13f0e47e194ca664cdefe25e1f10a8b677db492e
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter7/Bird.py
695
4.15625
4
#Chapter 7 - Exercise #1 #Bird.py #.py is a Python file #Start a new Python script by declaring a new class with a #descriptive document string class Bird: '''A base class to define bird properties.''' #Next, add an indented statement to declare and initialize #a class variable attribute with an integer zero value count = 0 #Now, define the initializer class method to initialize an #instance variable and to increment the class variable def __init__(self, chat): self.sound = chat Bird.count += 1 #Finally, add a class method to return the value of the #instance variable when called - then save this class file def talk(self): return self.sound
true
05e73c631b68f4635e240e9df5797dce6e5bd3d7
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter4/scope.py
871
4.4375
4
#Chapter 4 - Exercise #1 #Scope.py #.py is a Python file #Start a new Python script by initializing a global variable global_var = 1 #Next, create a function named "my_vars" to display the #value contained within the global variable def my_vars(): print('Global Variable:', global_var) #Now, add indented statements to the function block to #initialize a local variable and display the value it contains local_var = 2 print('Local variable:', local_var) #Then, add indented statements to the function block to #create a coerced global variable and assign an initial value global inner_var inner_var = 3 #Add a statement after the function to call upon that #function to execute the statement it contains my_vars() #Finally, add a statement to display the value contained in #the coerced global variable print('Coerced Global:', inner_var)
true
48a42fbd874b8ff345acd45a8f66ca82dae8491e
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter6/data.py
1,266
4.59375
5
#Chapter 6 - Exercise #8 #Data.py #.py is a Python file #Start a new Python script by making "pickle" and "os" #module methods available import pickle, os #Next, add a statement to test that a specific data file does #not already exist if not os.path.isfile('pickle.dat'): #Now, add a statement to create a list of two elements if #the specified file is not found data = [0,1] #Then, add statements to request user data to be assigned #to each of the list elements data[0] = input('Enter Topic:') data[1] = input('Enter Series:') #Next, add a statement to create a binary file for writing to file = open('pickle.dat','wb') #Now, add a statement to dump the values contained in #the variables as data into the binary file pickle.dump(data, file) #Then, after writing the file remember to close it file.close() #Next, add alternative statements to open an existing file to #read from if a specific data file does already exist else: file = open('pickle.dat','rb') #Now, add statements to load the data stored in that #existing file into a variable then close the file data = pickle.load(file) file.close() #Finally, add a statement to display the restored data print('Welcome Back To:' + data[0] + ',' + data[1])
true
d3da397281d71e274b71f429d8c58173de189704
jandrews2014/Projects
/PythonIES-SelfTaught/Chapter7/Songbird.py
677
4.40625
4
#Chapter 7 - Exercise #4 #Songbird.py #.py is a python file #Start a new Python script by declaring a class with an #initializer method creating two instances variables and a #method to display one of those variable values class Songbird: def __init__(self, name, song): self.name = name self.song = song print(self.name, 'Is Born...') #Next, add a method to simply display both variable values def sing(self): print(self.name, 'Sings:', self.song) #Now, add a destructor method for confirmation when #instances of the class are destroyed - then save this file def __del__(self): print(self.name, 'Flew Away!\n')
true
3bba795c75dfb810882741603a8935233002cc5b
realtech983/caesar_cipher
/caesar.py
1,354
4.21875
4
def encripted(string,shift): cipher = '' for char in string: if char == "": cipher = cipher + char elif char.isupper(): cipher = cipher + chr((ord(char)+shift - 65) % 26+65) elif char.isnumeric(): cipher = cipher + char elif char.islower(): cipher = cipher + chr((ord(char)+shift - 97) % 26+97) return cipher def decryption(string , shift): decipher = "" for char in string: if char.isnumeric(): decipher = decipher + char if char.isupper(): decipher = decipher + chr((ord(char) - shift - 65) % 26+65) if char.islower(): decipher = decipher + chr((ord(char)-shift - 97) % 26+97) return decipher print("what you want to do?") print("1.Encryption") print("2.Decryption") inputvalue = int(input("Enter Number ")) if inputvalue == 1: text = input("enter text ") s = int(input("enter the shift key ")) print("the original string is : ", text) print("encripted text is : ", encripted(text, s)) else: text = input("enter encripted text ") s = int(input("enter shift key ")) print("the encriptrd string is : ", text) print("Decripted or orginal text is : ",decryption(text,s))
false
befdf3c48741c3a5e5bea5e0189ce6e9081c3c0a
RPalaziuk/SSpractice
/python/binary_convert.py
335
4.28125
4
def bin_convert(num) : print("Enter the number : ") num = int(input()) binary = '' if num == 0: print("Binary representation : 0") quit() while num > 0: binary = str(num % 2) + binary num = num // 2 print("Binary representation : " + binary) bin_convert(int)
false
fdeef37012b08eadb8f3e82cc25dac0d77cf68ed
pratiksachaniya/Python-Program
/String.py
633
4.40625
4
str = "HI Welcome To Py." print(str) str = 20; print(str) str = 'This is Secound String' print(str) str = "Hi 'Pratik'" print(str) str = """ Hi "Pratik 'Sachaniya'" """ print(str) print("Str[9:]") print(str[9:]) print(str[1:5]) #The upper() method returns the string in upper case: print(str.upper()) #The lower() method returns the string in lower case: print(str.lower()) #The strip() method removes any whitespace from the beginning or the end: str = " PRTIK SACHANIYA " print(str.strip().lower().upper()) #The len() method returns the length of a string: str = str.strip() print(len(str))
true
4d81a79402447426b77b8f427630ebe8e0e5b169
smartielion/Coursework
/CS121/fib.py
675
4.28125
4
#Assignment Number 3 #Fibonnaci sequence #Casey Gilray def fib(N,depth): #sets up number of spaces for depth output space = " " #base case if N == 1 or N == 2: print space*depth, '1 : Base case' return (1) else: #recursive addition, #print what it is finding print space*depth, (N-1), ' and ',(N-2) return((fib((N-1),(depth+1)) + (fib((N-2),(depth + 2))))) def test(): #make assertions for base case assert fib(1,1) == 1 assert fib (2,1) == 1 #make assertions for other known cases assert fib(5,1) == 5 assert fib(7,1) == 13 assert fib(9,1) == 34 return
true
ba9658ecfdf14f035452b97f0eaa3a52255f4d21
Garv1Zarco/rsaCypher
/src/mathTools/Converters.py
1,191
4.375
4
# Those converters are made to get an int value of 3-digit number # from any alphanumeric character # based in unicode table and to undo this process # (from 3-digit number to a alphanumeric char) # Every 3 digit group belongs to a char in unicode def str2int(m): mb = "" for i in m: chi = str(ord(i)) if len(chi) < 3: # For the char which code is lower then 3 digits, a "0" is added schi = "0" + chi else: schi = chi mb = mb + schi mb = int(mb) print("Initial mb: ", mb) print("Initial m: ", m) return mb def int2str(mb): m = "" if len(str(mb)) % 3 != 0: mb = "0" + str(mb) # In case the first char code has 2 digits instead of 3, # the total length of the code will not be divider of 3 # Ex: "a" = "097" -> int("097") = 97 -> It's needed to add a "0" to get back "097" else: mb = str(mb) for j in range(int(len(mb) / 3)): # This loop gets every single character from the int code ch = "" for i in range(3): ch = ch + mb[j * 3 + i] m = m + chr(int(ch)) print("Final mb: ", mb) print("Final m: ", m) return m
true
c82743a9f521d8b230438ea5f696e00419c0507b
www2620552/Python-and-Algorithms-and-Data-Structures
/src/abstract_structures/linked_list/find_kth_from_the_end.py
1,066
4.34375
4
#!/usr/bin/python __author__ = "Mari Wahl" __email__ = "marina.w4hl@gmail.com" ''' Find the mth-to-last element of a linked list. One option is having two pointers, separated by m. P1 start at the roots (p1 = self.root) and p2 is m-behinf pointer, which is created when p1 is at m. When p1 reach the end, p2 is the node. ''' from linked_list_fifo import LinkedListFIFO from node import Node class LinkedListFIFO_find_kth(LinkedListFIFO): def find_kth_to_last(self, k): p1, p2 = self.head, self.head i = 0 while p1: if i > k: try: p2 = p2.pointer except: break p1 = p1.pointer i += 1 return p2.value if __name__ == '__main__': ll = LinkedListFIFO_find_kth() for i in range(1, 11): ll.addNode(i) print('The Linked List:') print(ll._printList()) k = 3 k_from_last = ll.find_kth_to_last(k) print("The %dth element to the last of the LL of size %d is %d" %(k, ll.length, k_from_last))
true
95015eec4cbe18f1574ec039d28d73c6f979e2cf
www2620552/Python-and-Algorithms-and-Data-Structures
/src/abstract_structures/queues/queue.py
948
4.125
4
#!/usr/bin/python __author__ = "Mari Wahl" __email__ = "marina.w4hl@gmail.com" ''' an (inefficient) class for a queue ''' class Queue(object): def __init__(self): self.items = [] def isEmpty(self): return not bool(self.items) def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def peek(self): return self.items[-1] def __repr__(self): return '{}'.format(self.items) if __name__ == '__main__': queue = Queue() print("Is the queue empty? ", queue.isEmpty()) print("Adding 0 to 10 in the queue...") for i in range(10): queue.enqueue(i) print("Queue size: ", queue.size()) print("Queue peek : ", queue.peek()) print("Dequeue...", queue.dequeue()) print("Queue peek: ", queue.peek()) print("Is the queue empty? ", queue.isEmpty()) print(queue)
false
46ee077b2c807af79a59f6a6082e9723f2d9e02f
rubenvazcode/python-labs
/labs/python_fundamentals-master/02_basic_datatypes/2_strings/02_07_replace.py
481
4.25
4
''' Write a script that takes a string of words and a symbol from the user. Replace all occurrences of the first letter with the symbol. For example: String input: more python programming please Symbol input: # Result: #ore python progra##ing please ''' # get sentence from user sentence = input("Insert a sentence: ") # get symbol symbol = input("Chose a symbol: ") # get first letter first = sentence[0] # replace occurences with symbol print(sentence.replace(first, symbol))
true
b7576ed01924d687f72e2a2afb62ac44744db0ac
lyndachiwetelu/compare-strings
/compare.py
458
4.125
4
# Compare Strings #run this program by typing python compare-strings.py on shell (with python installed) def compare_strings(first_string,second_string): switch = False for char in first_string: if char in second_string: switch = True break return switch def main(): first = str(raw_input("Enter first String: ")) second = str(raw_input("Enter Second String: ")) if compare_strings(first,second): print "YES" else: print "NO" main()
true
76c110fb1ae278459a5d7fcb0c1f4e39d13d73ae
rpasricha45/project1CS435
/part2/BSTInsert.py
1,502
4.1875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def helper(root, val): if root == None: # now we add the element return # base cases if root.val < val and root.right == None: root.right = TreeNode(val) return elif root.val > val and root.left == None: root.left = TreeNode(val) # recursion if root.val < val: # go to the right substree helper(root.right, val) elif root: helper(root.left, val) def recBstInsert( root, val): helper(root, val) return root def insertIntoBST( root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ # first find where to insert the node current = root if current == None: return None while (current != None): print("running") if current.val > val and current.left != None: current = current.left continue elif current.val < val and current.right != None: current = current.right continue # base cases if current.val > val and current.left == None: print("adding") current.left = TreeNode(val) break elif current.val < val and current.right == None: current.right = TreeNode(val) break return root
true
0f59afba25584f6658405a4004f146516811760c
ivanovkalin/myprojects
/softUni/area_of_figures.py
455
4.1875
4
from math import pi figure_type = input() area = 0 if figure_type == "square": a = float(input()) area = a * a elif figure_type == "rectangle": a = float(input()) b = float(input()) area = a * b elif figure_type == "circle": radius = float(input()) area = pi * radius * radius elif figure_type == "triangle": side = float(input()) height = float(input()) area = (side * height) / 2 print(f"{area:.3f}")
false
5b1ff423017d381f194af46e6fd68343379314b6
Banehowl/JuneDailyCode2021
/DailyCode06152021.py
625
4.15625
4
# ------------------------------------------------------------------------- # # Daily Code 06/14/2021 # "(One Line) Find the Perimeter of a Rectangle" Lesson from edabit.com # Coded by: Banehowl # ------------------------------------------------------------------------- # Create a function that takes length and width and finds the perimeter of a rectangle. # find_perimeter(6, 7) -> 26 # find_perimeter(20, 10) -> 60 # find_perimeter(2, 9) -> 22 def find_perimeter(length, width): return (length + width) * 2 print find_perimeter(6, 7) print find_perimeter(20, 10) print find_perimeter(2, 9)
true
ec672af5836961eaa9e7ff8b394922f33572c3f4
Vishvanth19/MyCaptain-Projects
/code snippets.py
774
4.375
4
#Assigning elements to different lists students=["Rohan","Naman","Mohit","Abhishek"] teachers=["Prateek","Vijay","Soumya","Devi"] print ("The names of students are",students) print ("The names of teachers are",teachers) students.append("Pranav") teachers.append("Vinny") print ("The updated student list is",students) print ("The updated teacher list is",teachers) #Accessing elements from a tuple students=("Rohan", "Naman", "Pranav") print("The students present today are",students) print("The 3rd student name is",students[2]) #Deleting different dictionary elements pairs={"Pranav":"Vinny", "Naman":"Vijay","Rohan":"Devi"} print("The student assigned to each teacher is",pairs) del pairs["Rohan"] print("The updated pairs are",pairs)
false
9802666baf4c9c409dc8981bab4d0a8343a1e4a8
matheus-Casagrande/ProjetoSudoku-ES4A4
/testes/testes_Resolvedor/posiciona_amostra.py
958
4.125
4
''' Este módulo serve para capturar da aplicação o objeto a ser analisado pelos testes. Para este teste de aceitação, esse algoritmo vai copiar do programa a matriz do sudoku para dentro de um txt nesta pasta, para que ela seja posta a experimento. ''' import sys sys.path.append('..') # faz o interpretador do python conhecer a pasta anterior sys.path.append('...') def sudokuToTxt(matriz): # Este endereço é relativo ao módulo "app_class.py" dentro da pasta jogo no diretório raiz f = open('../testes/testes_Resolvedor/sudoku.txt', 'w') print('Arquivo sudoku.txt criado em testes/testes_Resolvedor') matrizString = [] # transforma as linhas da matriz em linhas string e passa para matrizString essa informação for linha in matriz: matrizString.append(f'{str(linha)}\n') # retira o último '\n' de matrizString matrizString[-1] = matrizString[-1][0:-1] f.writelines(matrizString) f.close()
false
83d54ac31b222235923cecac9fdde4219a262b94
Clebom/exercicios-livro-introd-prog-python-3ed
/capitulo-07/ex10.py
1,150
4.3125
4
# Escreva um jogo da velha para dois jogadores # O jogo deve perguntar onde você quer jogar e alternar entre os jogadores # A cada jogada, verifique se a posição está livre # Verifique também quando um jogador venceu a partida # Um jogo da velha pode ser visto como uma lista de 3 elementos, na qual cada elemento é outra lista, também com 3 elementos # Exemplo do jogo: # # X | O | # ---+---+--- # | X | X # ---+---+--- # | | O # # Em que cada posição pode ser vista como um número # Confira a seguir um exemplo das posições mapeadas para a mesma posição de seu teclado numérico # # 7 | 8 | 9 # ---+---+--- # 4 | 5 | 6 # ---+---+--- # 1 | 2 | 3 # def line(size): print('-' * size) game = [['', '', ''], ['', '', ''], ['', '', '']] line(50) print('JOGO DA VELHA' .center(50)) line(50) print('COMO JOGAR: Para efetuar cada jogada, informe o\n' 'número que corresponde ao local que deseja marcar.') print(''' 7 | 8 | 9 ---+---+--- 4 | 5 | 6 ---+---+--- 1 | 2 | 3 ''') line(50) playerX = int(input('JOGADOR X, digite a posição para marcar: ')) playerO = int(input('JOGADOR O, digite a posição para marcar: '))
false
dff0d4ab6495ff1d1f7e603f5aacf5bdcbee7c6b
Clebom/exercicios-livro-introd-prog-python-3ed
/capitulo-07/ex06.py
849
4.3125
4
# Escreva um programa que leia três strings # Imprima o resultado da substituição na primeira, dos caracteres da segunda pelos da terceira # 1ª string: AATTCGAA # 2ª string: TG # 3ª string: AC # Resultado: AAAACCAA str1 = str(input('\nDigite a primeira string: ')) str2 = str(input('Digite a segunda string: ')) str3 = str(input('Digite a terceira string: ')) if len(str2) == len(str3): result = '' for letra in str1: position = str2.find(letra) if position != -1: result += str3[position] else: result += letra if result == '': print('\nTodos os caracteres foram removidos.') else: print(f'\nOs caracteres {str2} foram substituídos por {str3} em {str1}, gerando: {result}') else: print('\nERRO: A segunda e a terceira string devem ter o mesmo tamanho.')
false
3215d3d5838abb57f1e65cda0adb355e83d8e46f
Clebom/exercicios-livro-introd-prog-python-3ed
/capitulo-06/ex06.py
2,346
4.125
4
# Modifique o programa para trabalhar com duas filas # Para facilitar seu trabalho, considere o comando A para atendimento da fila 1; e B, para atendimento da fila 2 # O mesmo para a chegada de clientes: F para fila 1; e G, para fila 2 def line(size): print('-' * size) last = 10 queue1 = list(range(1, last + 1)) queue2 = list(range(1, last + 1)) while True: print() line(70) print(f'Existem {len(queue1)} clientes na FILA 1') print(f'Fila atual: {queue1}') line(70) print(f'Existem {len(queue2)} clientes na FILA 2') print(f'Fila atual: {queue2}') line(70) print('\nAdicionar cliente na fila:') print(' - Digite F para adicionar na fila 1, e G para adicionar na fila 2') print('Atendimento:') print(' - Digite A para atender da fila 1, e B para atender da fila 2') print('Sair do programa:') print(' - Digite S') operation = str(input('\nOperação (F, G, A, B ou S): ')).strip().upper() counter = 0 leave = False while counter < len(operation): if operation[counter] == 'A': if len(queue1) > 0: attended = queue1.pop(0) print(f'\nCliente {attended} da FILA 1 atendido') else: print(f'Fila 1 vazia! Ninguém para atender.') elif operation[counter] == 'B': if len(queue2) > 0: attended = queue2.pop(0) print(f'\nCliente {attended} da FILA 2 atendido.') else: print(f'Fila 2 vazia! Ninguém para atender.') elif operation[counter] == 'F': last = len(queue1) + 1 queue1.append(last) print('\nChegou um cliente ao final da fila 1.') print(f'Existem {len(queue1)} clientes na fila 1.') print(f'Fila atual: {queue1}') elif operation[counter] == 'G': last = len(queue2) + 1 queue2.append(last) print('\nChegou um cliente ao final da fila 2.') print(f'Existem {len(queue2)} clientes na fila 2.') print(f'Fila atual: {queue2}') elif operation[counter] == 'S': leave = True break else: print('\nOperação inválida! Digite apenas F, A ou S!') counter += 1 if leave: break print('\nFim da execução!')
false
308b13fc23f6ac90f3c82563a939dc018329ed9a
BaldvinAri/Python_verkefni
/Vika 02/PrimeNumber.py
471
4.125
4
n = int(input("Input a natural number: ")) # Do not change this line counter = 2 # Fill in the missing code below if n == 2: prime = True elif n < 2: prime = False elif n % 2 == 0: prime = False else: while counter < n: rem = n % counter if rem == 0: prime = False break counter += 1 else: prime = True # Do not changes the lines below if prime: print("Prime") else: print("Not prime")
true
70e352efa817d59dc97daff996f1043fea043e69
BaldvinAri/Python_verkefni
/Vika 05/assignment7_4.py
519
4.21875
4
def is_prime(n): counter = 2 if n == 2: return True elif n < 2: return False elif n % 2 == 0: return False else: while counter < n: rem = n % counter if rem == 0: return False counter += 1 else: return True max_num = int(input("Input an integer greater than 1: ")) for i in range(2,max_num + 1): if is_prime(i): print(i,"is a prime") else: print(i,"is not a prime")
false
451a039f95d2463a9d8237a36e11c49fbe832722
BaldvinAri/Python_verkefni
/Vika 05/assignment7_2.py
271
4.25
4
def count_digits(string): counter = 0 for i in string: if i.isdigit(): counter += 1 return counter input_str = input("Enter a string: ") digit_count = count_digits(input_str) # Call the function here print("No. of digits:", digit_count)
true
f0ee3932476390c07bfc28d9e048c2b5b573126b
amit0623/python
/Python_Crash_Course/Chapter4.py
1,817
4.5625
5
magicians = ['amit','karl','pench'] # Try to make the list of variable name as plural # Try to make the variable name in for loop as singular for magician in magicians: print(magician) for number in range ( 1,8): print (number) #If you want to make a list of numbers, you can convert the results of range() directly into a list using the list() function. numbers = list(range(1,11)) print(numbers) # generate a list of square of num square = [] for number in range ( 1, 11 ) : square.append(number ** 2 ) print(square) # Few stats functions of lists digits = list(range(1,12)) print(min(digits)) print(max(digits)) print(sum(digits)) # List Compre squares = [number ** 2 for number in range (1,12 )] print(squares) # working with slices players = ['charles', 'martina', 'michael', 'florence', 'eli'] print (players[0:3]) # To generate 2,3,4 items of this list print(players[1:4]) # if you omit the first index of this slice, then default index == 0 print(players[:3]) # if you want all elements from position 2 to end of list #then omit the last index print(players[2:]) for player in players[:3]: print(player) # Copying a list # To copy a list, you can make a slice that includes the entire original list by omitting the first index and the second index ([:]). # This tells Python to make a slice that starts at the first item and ends with the last item, producing a copy of the entire list. my_foods = ['mango','apple','roti','rice'] # Note how slicing produces a new list friends_food = my_foods[:] print(my_foods) print(friends_food) my_foods.append('guava') friends_food.append('pizza') print(my_foods) print(friends_food) # Working with Tples dimensions = (10,20) print(dimensions[0]) print(dimensions[1]) dimensions = (30,4) print(dimensions[0]) print(dimensions[1])
true
097ca5ff4bd93bed711c90e57d99bae5f4505756
kimjoshjp/python
/cinema.py
847
4.21875
4
# # # # # ages and number of seats films ={"Dory":[5,5], "Bourne":[18,5], "Tarzan":[16,5], "Ghost":[12,5] } while True: for name in films: print(name) choice = input("What file would you like to watch?: ").strip().title() if choice in films: age = int(input("How old are you?: ").strip()) #Check age if age >= films[choice][0]: num_seats = films[choice][1] #Set number of seat second element if num_seats > 0: print("Enjoy the film!") films[choice][1] = films[choice][1] -1 #Reduce number of ticket from 5 (elements) else: print("Sorry we are sold out.") else: print("You are too young to see that film!") else: print("There is no such a movie")
true
67ad34fd4c7adf40adfddb1fca1f35a3dab1390b
gabsw/LearningOOP
/oop/easy_exercises/dog.py
579
4.1875
4
class Dog: """Creates a class that represents a dog and its behavior""" def __init__(self, name, age): """Initializes attributes name and age""" self.name = name if name == '': raise Exception('Dog needs a name.') self.age = age if age < 0: raise Exception('Age cannot be below 0.') def sit(self): """Simulate a dog sitting""" return self.name + ' is now sitting.' def roll_over(self): """Simulate a dog rolling over""" return self.name + ' is now rolling over.'
true
cacbffcef5c4802772c2870c123cc7f3410f94af
gabsw/LearningOOP
/oop/easy_exercises/car.py
689
4.21875
4
class Car: """Create a class that models a car""" def __init__(self, brand, model, year): self.brand = brand self.model = model self.year = year self.odometer = 0 def get_descriptive_name(self): description = self.brand + ' ' + self.model + ' ' + str(self.year) return description def get_odometer(self): return self.odometer def set_odometer(self, mileage): if self.odometer < mileage: self.odometer = mileage else: raise Exception('You cannot turn back an odometer.') def increment_odometer(self, miles): if miles > 0: self.odometer += miles
true
40782ab3196d5550aa31e792765bb92cb5b84a17
sydteo/Data-Structure
/week4/majority_element.py
1,551
4.15625
4
# Uses python3 import sys #mergesort def get_majority_element(a, left, right): if left == right: return [a[left]] mid = (left+right)//2 B = get_majority_element(a, left, mid) C = get_majority_element(a, mid+1, right) sortedArray = merge(B, C) return sortedArray #merge called within mergesort def merge(left_array, right_array): sorted = [] left_index = 0 right_index = 0 while left_index < len(left_array) and right_index < len(right_array): if left_array[left_index] > right_array[right_index]: sorted.append(right_array[right_index]) right_index += 1 elif left_array[left_index] <= right_array[right_index]: sorted.append(left_array[left_index]) left_index += 1 if left_index < len(left_array): for i in left_array[left_index:]: sorted.append(i) if right_index < len(right_array): for j in right_array[right_index:]: sorted.append(j) return sorted #count -> called at runtime def findMajority(sortedList): # print(sortedList) count = 0 mid = len(sortedList)//2 maybe = sortedList[mid] for i in sortedList: if i == maybe: count += 1 if count > mid: return 1 else: return -1 if __name__ == '__main__': # input = sys.stdin.read() input=input() n, *a = list(map(int, input.split())) if findMajority(get_majority_element(a, 0, n-1)) == -1: print(0) else: print(1)
true
8dfc91e88408c1ff4324ae83086945c585a1e55c
anicholas4747/Re-Learning-Python
/Mosh Tutorial/Basics/listz.py
271
4.28125
4
# find the largest num in a list def find_max(arr): max = None for n in arr: if (max == None) or (max < n): max = n return max arr = [1,2,3,4,5] print(find_max(arr)) arr = [6, 2, 3, 4, 5] print(find_max(arr)) arr = [1, 2, 7, 4, 5] print(find_max(arr))
true
4b94f51836fbd0409050ead017138e1bdc1b7323
najae02/GWC-python-and-final-project-
/codingchallenge.py
526
4.15625
4
#imports the ability to get a random number (we will learn more about this later!) from random import * #Generates a random integer. aRandomNumber = randint(1, 5) # For Testing: print(aRandomNumber) i = 0 for i in range(3): tries = str(i) print(tries) guess = input("Guess a number between 1 and 5:") if(aRandomNumber > 5): print("Try Again") continue if(aRandomNumber < 1): print("Try Again") continue else: print(str(aRandomNumber)) print("You did it!") break print("Game Over")
true
742fb632bf624c15a7c52180838f84d05130126e
44823/Iteration-class-exercises
/Revision exercise 4.py
302
4.28125
4
#Matthew Beer #15/10/14 #Iteration revision exercise 4 num1 = int(input("Please enter a number between 10 and 20: ")) while num1 > 20 or num1 < 10: num1 = int(input("The number you have entered is invalid, please enter another number: ")) print("The number you have chosen is within the range")
true
2a3d3339fa819b661b4a7d2e747238bf23d93f20
ksimms5/project
/palindrome.py
323
4.125
4
print(" The largest palindrome made by the product of two three digit numbers: ") maxpal = 0 for i in range(100,999) : for j in range(100,999): product = i * j x = str(product) reverseit = "" for y in x: reverseit = y + reverseit if(x == reverseit): if maxpal < product: maxpal = product print(maxpal)
true
01aa841c027500d5e69b63f2c2ecba67d89a65a9
jjcano/ejercicios_python
/4.py
487
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def esvocal(vocal): vocales = ['\xc3\xa1', '\xc3\xa9', '\xc3\xad', '\xc3\xb3', '\xc3\xba','\xc3\xbc', 'a', 'e', 'i', 'o', 'u', '\xc3\x81', '\xc3\x89', '\xc3\x8d', '\xc3\x93', '\xc3\x9a','\xc3\x9c', 'A', 'E', 'I', 'O', 'U'] if vocal in vocales: print "Es una vocal" else: print "No es una vocal" vocal = raw_input("Ingrese una opción letra: ") print esvocal(vocal)
false
72a2a2db7df71408f9baf073c0e7c60d1d2ace04
RollinsonSoftware/MiraCosta-CS-138
/Project8/hw8project1.py
1,239
4.4375
4
#! /usr/bin/python # Exercise No. 01 # File Name: hw8project1.py # Programmer: John Rollinson # Date: 10/20/2019 # # Problem Statement: # Write a program that computes and outputs the nth Fibonacci number, where n is # is a value entered by the user. # # Overall Plan: # 1. Define the fibonacci function with n as the parameter. # 2. Initialize the base case as 1 and define the case for the first and second terms. # 3. Run a loop from the second term to the nth term. # 4. Each iteration should find the next term while also saving the last two terms. # 5. Ask user to enter the position to find desired value. # 6. Print the desired value. # # import the necessary python libraries def fibonacci(n): a = 1 b = 1 if(n < 0): print("Incorrect input.") elif(n == 0): return(a) elif(n == 1): return(b) else: for i in range(2, n): c = a + b a = b b = c return(b) def main(): print("This program will find the desired term of the fibonacci sequence!") n = int(input("Enter the nth term of the sequence: ")) print("The fibonacci number is:", fibonacci(n)) main()
true
9bef20f2bdba4e441af092f6aef5cab385428c6f
RollinsonSoftware/MiraCosta-CS-138
/Project2/hw2project1.py
841
4.5
4
#! /usr/bin/python #Exercise No. 01 #File Name: hw2project1.py #Programmer: John Rollinson #Date: 8/31/2019 # #Problem Statement: (what you want the code to do) #A program to convert Celsius temps to Fahrenheit. # #Overall Plan (step-by-step,how you want the code to make it happen): #1. Describe what the program does to the user with a print statement. #2. Read in a celsius value from the user. #3. Convert the temp to Fahrenheit. #4. print out the converted value to the user. # #import necessary python libraries #Create main function def main(): print("This program will convert a temperature given in Celsius to Fahrenheit!") celsius = eval(input("What is the Celsius temperature? ")) fahrenheit = 9/5 * celsius + 32 print("The temperature is", fahrenheit, "degrees Fahrenheit.") main()
true
4670bab7ae166387314b1c832397ed5b7c3ccd5e
RollinsonSoftware/MiraCosta-CS-138
/Project8/hw8project2.py
2,073
4.375
4
#! /usr/bin/python # Exercise No. 02 # File Name: hw8project2.py # Programmer: John Rollinson # Date: 10/20/2019 # # Problem Statement: # Write a program that converts a color image to grayscale. The user supplies # the name of a file containing a GIF or PPM image, and the program loads the # image and displays the file. At the click of the mouse, the program converts # the image to grayscale. The user is then prompted for a filename to store the # grayscale image in. # # Overall Plan: # 1. Import the graphics library for using graphics functions # 2. Define the main function # 3. Get the input and output file names # 4. Draw the image at a particular position # 5. Get the image width and height to iterate # 6. Change to greyscale based on the logic provided when user clicks on the image. # # import the necessary python libraries from graphics import* def main(): #Get input file name input_filename = input("Enter the name of the file: ") #Get the output file name output_filename = input("What will be the name of the new file?: ") #Set the image position my_image = Image(Point(120, 120), input_filename) #Get the width and height of the image image_width = my_image.getWidth() image_height = my_image.getHeight() #Set graphics window win = GraphWin("rgb", image_width, image_height) my_image.draw(win) row = 0 column = 0 win.getMouse() #Iterate through the image pixels using loops for row in range(image_width): for column in range(image_height): #Set to greyscale r, g, b = my_image.getPixel(row, column) brightness = int(round(0.299 * r + 0.587 * g + 0.144 * b)) #Set the new pixel my_image.setPixel(row, column, color_rgb(brightness, brightness, brightness)) #Update the window win.update() #Save the file to the new location my_image.save(output_filename) win.getMouse() win.close() main()
true
fc40b1db81052e3e15c62f12c85c5d22987f9291
Dylan-Morrissey/Python
/learnPythonHardWay/ex3.py
935
4.46875
4
# This line print the statement print "I will now count my chickens:" # This line prints Hens and 25/5 BOMDAS print "Hens", 25.00 + 30.00 / 6.00 # This line adds the Rooster again BOMDAS order print "Roosters", 100.00 - 25.00 * 3.00 % 4.00 # Print the line below print "Now I will count the eggs:" # Done the math using BOMDAS ordering print 3.00 + 2.00 + 1.00 - 5.00 + 4.00 % 2.00 - 1.00 / 4.00 + 6.00 # Print the line print "Is it true that 3 + 2 < 5 - 7?" # Does the Maths print 3.00 + 2.00 < 5.00 - 7.00 # Next two print the lines with the math answer after print "What is 3 + 2?", 3.00 + 2.00 print "What is 5 - 7?", 5.00 - 7.00 # Print the line print "Oh, that's why it's False." # Print the line print "How about some more." # Next 3 Print the line with the answer after it print "Is it greater?", 5.00 > -2.00 print "Is it greater or equal?", 5.00 >= -2.00 print "Is it less or equal?", 5.00 <= -2.00
true
4526994522a59fe13171703b1ca85155c1a90d17
JoeRoybal/CodingAssessmentProblems
/Python/arrayLeftRot.py
528
4.1875
4
# A left rotation operation on an array shifts each of the array's elements 1 unit to the left. # Function call # a = array # d = rotations def rotLeft(a, d): # for x in the range of 0 to the length of the array for x in range(0, len(a)): # if the current location is the number of rotations if x == d: # return the array return a # else remove the first element and save target = a.pop(0) # add the target to the end of the array a.append(target)
true
b38b6d0f565cc7deeba28c052f98a9391963c2b3
Shulin00/GreenPol
/telescope_control/examples/gui2_organizing_layout.py
877
4.375
4
from tkinter import * #creates a blank window root = Tk() #create invisible container in our window.. topFrame = Frame(root) #put it somewhere topFrame.pack() bottomFrame = Frame(root) #put it on the bottom bottomFrame.pack(side=BOTTOM) #make a button, (where to put it, what do you want in the button) button1 = Button(topFrame, text='Button 1', fg='red') button2 = Button(topFrame, text='Button 2', fg='blue') button3 = Button(topFrame, text='Button 3', fg='green') button4 = Button(bottomFrame, text='Button 4', fg='purple') #display them on your screen button1.pack(side=LEFT) # defaults to on top of each other button2.pack(side=LEFT) #can change that by passing argument to pack button3.pack(side=LEFT) #places as far left as possible button4.pack(side=BOTTOM) #keeps the window running, rather than shutting down right away root.mainloop()
true
87b07a779ff148955f31e0c7fdfd31b644e2ac6a
GSNCodes/Leetcode-Challenges-Python
/October_LeetCode_Challenge/Minimum_Domino_Rotations_For_Equal_Row.py
1,666
4.1875
4
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the ith domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same. If it cannot be done, return -1. Example 1: Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. Example 2: Input: A = [3,5,1,2,3], B = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal. Constraints: 2 <= A.length == B.length <= 2 * 104 1 <= A[i], B[i] <= 6 # O(n) Time and O(1) Space class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: min_swaps = min( self.swapCount(A[0], A, B), self.swapCount(B[0], A, B), self.swapCount(A[0], B, A), self.swapCount(B[0], B, A) ) return -1 if min_swaps == float('inf') else min_swaps def swapCount(self, target, arr1, arr2): numSwaps = 0 for i in range(len(arr1)): if arr1[i] != target and arr2[i] != target: return float('inf') elif arr1[i] != target: numSwaps += 1 return numSwaps
true
0bc779d577ea23b6ac46af800621559dcc49132a
GSNCodes/Leetcode-Challenges-Python
/December_LeetCode_Challenge/Pseudo_Palindromic_Paths_In_A_Binary_Tree.py
2,687
4.25
4
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. Example 1: Input: root = [2,3,1,3,1,null,1] Output: 2 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic p aths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome). Example 2: Input: root = [2,1,1,1,3,null,null,null,null,null,1] Output: 1 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome). Example 3: Input: root = [9] Output: 1 Constraints: The given binary tree will have between 1 and 10^5 nodes. Node values are digits from 1 to 9. Hint #1 Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Hint #2 Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity). # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # O(n) Time and O(h) Space class Solution: def pseudoPalindromicPaths (self, root: TreeNode) -> int: self.result = 0 self.digits = [0 for i in range(10)] self.dfs(root) return self.result def isPalindrome(self): is_odd = 0 for i in range(10): if self.digits[i] % 2 != 0: is_odd += 1 if is_odd > 1: return False return True def dfs(self, root): if root is None: return self.digits[root.val] += 1 if not root.right and not root.left: if self.isPalindrome(): self.result += 1 else: self.dfs(root.left) self.dfs(root.right) self.digits[root.val] -= 1
true
2fec5cdc9f64436de593c235fa1b45fcf99bc7df
SurajGutti/CodingChallenges
/Trees/invertbt.py
828
4.1875
4
'''Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ def recurse(node): if node: l = recurse(node.right) r = recurse(node.left) node.left = l node.right = r return node else: return None if root is None: return None return recurse(root)
true
647ca642767b46332f635049c41b2a953dbca81a
Muzz826/SWDV-610
/Week1/vote.py
386
4.40625
4
print("Input your age below to see if you are eligible to vote\n") # user inputs the age they want to check age = int(input("Enter Age: ")) # conditional statement checks whether the number input is >= 18 if age >= 18: print("\nCongrats! You are eligible to vote as you are old enough.") else: print("\nSorry, you are not eligible to vote as you are not old enough.")
true
4a812676e5f5b4223259a12cf72784cb50210c6d
Muzz826/SWDV-610
/Week3/reverse_list.py
684
4.3125
4
# This app will take a sequence of numbers and # reverse their by using recusion # Developed by: Ben Muzzy # sequence of numbers that will be reversed seq = "987654321" def ReverseList(seq): # Runs through the list until the list is empty if len(seq) < 1: return seq else: # Each pass the function makes it moves whatever # the current first number is to the end. # Once the list is empty the list is displayed in reverse order. return ReverseList(seq[1:]) + seq[0] print("This app takes a sequence of numbers and reverses their order:\n\n") print("Original order: " + seq) print("\nReverse Order: " + ReverseList(seq))
true
b0ce012c430ad604b2655775b518391e73c90357
thijshosman/python-playground
/letters_generator.py
700
4.15625
4
def letters_generator(): current='a' while current <= 'd': yield current current = chr(ord(current)+1) # chr() gives character corresponding to given number # ord() gives number of corresponding character for letter in letters_generator(): print(letter) # letters_generator returns a generator lett = letters_generator() lett.next() # used to be lett.__next__() def all_pairs(s): for item1 in s: for item2 in s: yield (item1, item2) print(list(all_pairs([1,2,3]))) class LetterIterable(object): def __iter__(self): current = 'a' while current <= 'd': yield current current = chr(ord(current)+1) letters1 = LetterIterable() a = all_pairs(letters1) print(a.next())
true
58283f25ef4fd3426b41cd31c4a79383cd63395c
john-ko/project-euler
/1.py
499
4.25
4
""" Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def natrual_numbers(limit): max = int(limit/3) + 1 sum = 0 for i in range(max): # multiple of 3 if i*3 < limit: sum+= i*3 # multiple of 5 if i*5 < limit: sum += i*5 return sum print(natrual_numbers(1000))
true
b662396b1ad19fb1b279fa9f51f1f444b6eeb20f
rohitkandiyal/Python_work
/self_syntax_codes/function/function.py
1,186
4.4375
4
def foo(x,y): "This is a function to add two numbers..." return x+y print(foo.__doc__) print(foo.__name__) print foo(3,8) print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" #lambda function mul=lambda x,y: x * y print foo(3,8) print mul(3,8) print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" #Use of map() #Suppose I want a function to be applied to the members of a list or lines of a file sqr=lambda a: a * a b=[1,3,5,2,8,7,9,4,6,17] print map(sqr,b) print map(sqr,map(sqr,b)) #now let's make the above example more FP compliant a=map(lambda x:x*x , b) print(list(a)) print(map(lambda x:x*x , b)) #So we don't hv the need to define sqr function here. print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" #Use of filter() #Find odd numbers in a list print filter(lambda x:(x%2)==0 , b) print "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" #Use of reduce() #Find largest number in a list print reduce(lambda a,c: a if (a > c) else c , b) print "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" #Done for url validation lambda a: "http" if (a == "www") else a
true
edee96a821b680207252a9501525e8da65297b96
dilshod-Cisco/my_week5
/functions/functions_return.py
1,896
4.375
4
# Return value def full_name(first, last): """Returns full name""" #print(f"{first.title()} {last.title()}") return f"{first.title()} {last.title()}" # "RETURN" keep the value in memory: def adding(a, b): return a + b # nums = [5, 55, 76, 1, -9, 0, 1, 456] # # # total = adding(456, 987) # print(f"Total is {adding(546, 987)}") def full_name_dict(first: str, last: str) -> dict: # "DICT" return type: "STR" data type i'm excepting: """Returns dictionary with first_name, last_name""" result = {'first_name': first.title(), 'last_name': last.title()} return result # public hashmap full_name_dict(String first, String last){ # JAVA way do this examples:(Type Language) # // JAVA code here, example of code, 1 of the reasons called type language: # } # ============ ==================== function return ======================== ======================== full_name('anvar', 'nosirov') name = full_name('john', 'doe') print(f"{name}, Welcome to the class !") total = adding(456, 987) print(f"Total is {adding(546, 987)}") student1 = full_name_dict('tatiana', 'shark') print(student1) print(student1['first_name']) # == full_name_dict() # ============= ==================== ===================== =================== # def find_num(num_list, number): # for num in num_list: # if num == number: # print(f"{number} is found !!.") # break # else: # print(f"{number} is not found !! ") # # # find_num(nums, 1) # find_num(nums, 46) # find_num([45, 0, 'hello'], 7) # ======== =========== ============ ============ ================ =============== # def desc_pizza(*toppings): # print("We have only cheese pizza with following toppings: ") # print(*toppings) # # desc_pizza('chicken') # desc_pizza('chicken', 'peperoni', 'bbq chicken') # print('hello', 32, ['D', 'A'], 'world')
true
96d524ccc859348a32aa176f257ee693ff4b6813
Hasibur-R/CSE-310-codes
/Problem 1.py
482
4.28125
4
#The initial velocity of a car is u m/s and the acceleration is a m/s2 u=float(input("Ente the Intitial velocty of CAR: ")) a=float(input("Enter the acceleration: ")) #a. Find out the velocity of the car after t sec. t=float(input("Enter the time: ")) T=u+(a*t) print(f"Velocity of the car after {t}sec: {T}") print("\n\n") #b. Find the distance covered by the car after t sec. s =u*t +0.5*a *t *t print(f"The distance covered by the car after {t}sec: {s}")
true
985182d2acff065a92afc60c52e514cf47210ad7
pardiiix/Games
/Tic-Tac-Toe.Py
2,951
4.21875
4
# -*- coding: utf-8 -*- """ Created on August 24th, 2017 @author: Pardis Ranjbar E-mail: pardis.ranjbar@gmail.com #============================================================================== # This is a code of a Tic-Tac-Toe game. #============================================================================== """ x=y=None matrix=[] player=None win=None def initialize(): #This is the first function of the code global player, win, matrix #globalizing to be able to use later on player=1 #player 1 starts win=False #at first there is no winner matrix=[[0,0,0] for i in range(3)] #an empty square matrix with a size of 3 def print_emptyboard(): #prints the empty board with no components for i in range(3): #three rows and columns are created print('-------') row='| | | |' print(row) print('-------') #prints the 4th line print('Player 1') #to indicate that the game starts with player 1 def print_board(): #prints the board after a component is given global matrix for i in range(len(matrix)): print('-------') #the first line row='|' #the first border for j in range(len(matrix[i])): if matrix[i][j]==0: #if no input has been given yet row+=' |' #an empty space and it's border should be added to row elif matrix[i][j]==2: #if player 2 enters a coordinate row+='O|' else: row+='X|' print(row) # prints a completed row with X's and O's print('-------') def check_winner(): global matrix,win for i in range(len(matrix)): s1=s2=d1=d2=1 for j in range(len(matrix[i])): s1*=matrix[i][j] #s1 is the multiplication of a row s2*=matrix[j][i] #s2 is the multiplication of a column if s1==1 or s1==8 or s2==1 or s2==8: print('player',player, 'wins') win=True for i in range (len(matrix)): for j in range(len(matrix)): if i==j: d1*=matrix[i][j] if i+j==2: d2*=matrix[i][j] if d1==1 or d1==8 or d2==1 or d2==8: print('player',player, 'wins') win=True def select_place(): global x,y, matrix ,player x=int(input('enter X position:\n')) y=int(input ('enter Y position:\n')) def set_selected_place(): global matrix, player, x, y matrix[x][y]=(player) def boardisfull(): for i in range (len(matrix)): for j in range(len(matrix)): if (matrix[i][j]==0): return False return True print('Game over') def winner(): return win def switch_player(): global player player=2 if player==1 else 1 print('Player', player) print_emptyboard() initialize() while True: while not boardisfull() and not winner(): select_place() set_selected_place() print_board() check_winner() switch_player() print('Game Over!\n')
true
244ef67110c0f49343a4fd3b80c525119ee7478a
miguelromero717/python-exercises
/4_flow_control_2.py
1,092
4.40625
4
# Make a program that reads 2 numbers by keyboard and determines the following aspects (it is sufficient to show True or False): # - If the two numbers are the same # - If the two numbers are different # - If the first is greater than the second # - If the second is greater than or equal to the first ## The user enters the two values number_one = int(input('Enter the first number ')) number_two = int(input('Enter the second number ')) ## Inline validation print("If the two numbers are the same. {}".format(number_one == number_two)) print("If the two numbers are different. {}".format(number_one != number_two)) print("If the first is greater than the second. {}".format(number_one > number_two)) print("If the second is greater than or equal to the first. {}".format(number_one <= number_two)) ## Flow validation if number_one > number_two: print("Number one is greater than number two") elif number_two >= number_one: print("Number two is greater than number one") if number_two > number_one else print("Numbers are equals") else: print("Numbers are different")
true
ff34190507eb762c02894c21aafd7331b1d3d5d2
Alok-source-0/cbse-xii-cs-proj
/practicals/python/q15_queue.py
1,748
4.15625
4
''' Program to implement Queue in Python using List ''' from tabulate import tabulate from utils import drive_menu class Queue(): def __init__(self, length=9999) -> None: self.q = [] if (type(length) != int) or (length <= 0): print(f'Invalid Limit : must be int greater than zero') return self.length = length def is_empty(self): return self.q == [] def front(self): if self.is_empty(): print('Empty Queue : No front element') return return self.q[0] def rear(self): if self.is_empty(): print('Empty Queue : No rear element') return return self.q[len(self.q)-1] def enqueue(self, data=None): if not data: data = input('Enter data to enqueue: ') if len(self.q) == self.length: print('Queue Overflow : Size of queue exceeded length') return self.q.append(data) def dequeue(self): if self.is_empty(): print('Queue Underflow : Empty queue, nothing to dequeue') return rm = self.q[0] del self.q[0] return rm def display(self): if self.is_empty(): return print('front') print(tabulate([self.q], tablefmt='fancy_grid')) def main(): qu = Queue() menus = {} menus['1'] = {'desc': 'Enqueue', 'func': qu.enqueue} menus['2'] = {'desc': 'Dequeue', 'func': qu.dequeue} menus['3'] = {'desc': 'Peek (front)', 'func': qu.front} menus['4'] = {'desc': 'Rear', 'func': qu.rear} menus['5'] = {'desc': 'Display', 'func': qu.display} drive_menu('Queue Operations', menus) if __name__ == "__main__": main()
true
ed5575ba0d513b8ce031a5120f02b63015bee367
Alok-source-0/cbse-xii-cs-proj
/practicals/python/q05_largestMax.py
939
4.5
4
''' Read a text file and display the largest word and maximum number of characters present in a line from text file. ''' def analyse(path: str) -> None: ''' Analyses a text file and display the largest word and maximum number of characters present in a line from text file. Args: path (str): path of the file to analyse ''' with open(path, 'r') as file: content = file.read() for line_no, line in enumerate(content.splitlines(), start=1): if len(line) != 0: print( f'''Line:{line_no} Character Count : {len(line)}''', end='\t') words = line.split() if words: print(f'Largest Word: {max(words)}') else: print('This line has no words') else: print(f'Line:{line_no} Empty Line') if __name__ == "__main__": # Run the function analyse(input('Enter file path\n>>> '))
true
f287232e15a3f129303568d226df323b0db75d0e
darkjeffbr/Python-Playground
/Demos/DataStructures.py
2,023
4.3125
4
#Python list syntax assorted_list = [True, False, 1, 1.1, 1+2j, 'Learn', b'Python'] first_element = assorted_list[0] print(first_element) print(assorted_list) for item in assorted_list: print(type(item)) simpleton = ['Learn', 'Pthon', '2'] print('id(simpleton) ',id(simpleton)) print(simpleton) print('Id simpleton[2] ', id(simpleton[2])) simpleton[2] = '3' print('Id simpleton[2] ', id(simpleton[2])) print('id(simpleton) ',id(simpleton)) print(simpleton) #Nesting inside a list nested = [[1,1,1],[2,2,2],[3,3,3]] print("Nesting inside a list \n") for items in nested: for item in items: print(item, end = ' ') #Slicing a list print('Slicing a list') languages=['C', 'C++', 'Python', 'Java', 'Go', 'Angular'] print('languages = ', languages) print('languages[0:3] = ', languages[0:3]) print('languages[2:] = ', languages[2:]) ## -------------------------------------------------------------- #Define tuple pure_tuple = () print(pure_tuple) #Nested tuples first_tuple = (3, 4, 5) second_tuple = ('learn', 'python 3') nested_tuple = (first_tuple, second_tuple) print(nested_tuple) #Repetition in tuples sample_tuple = ('Python 3', )*3 print("sample_tuple : ",sample_tuple) #Dictionaries sample_dict = {'key' : 'value', 'jan':31, 'feb':'28/29', 'mar':31} print(type(sample_dict)) print(sample_dict) #Accessing dictionaries elements with keys print(sample_dict['jan']) print(sample_dict['feb']) #Dictionaries methods to access elements print("Dictionaries methods to access elements") print(sample_dict.keys()) print(sample_dict.values()) print(sample_dict.items()) #Modifying a dictionary (Add/update/delete) print('Modifying a dictionary (Add/update/delete)') print("sample_dict['feb'] = 29") sample_dict['feb'] = 29 print('sample_dict : ' , sample_dict) print("sample_dict.update({'apr' : 30, 'key': 'newValue'})") sample_dict.update({'apr' : 30, 'key': 'newValue'}) print('sample_dict : ' , sample_dict) print("del sample_dict['key']") del sample_dict['key'] print('sample_dict : ' , sample_dict)
true
275c4d6a538bf57dd625a8fcb7d5133f7c037dc9
Ezi0aaudit0re/Cache-simuulator
/helper.py
1,392
4.1875
4
""" This is a helper file for the program """ __author__ = "Aman Nagpal" __email__ = "amannagpal4@gmail.com" """ Print the array provided in its hex value :param: list """ def print_hex_value(list_name): for value in list_name: print(hex(value)) """ THis function gets input from user :return: string in lower case letters """ def ask_question(): ans = input("(R)ead, (W)rite or (D)isplay Cache ? Enter 'quit' to exit the program\n") ans = ans.lower() if (ans == "q" or ans == "exit" or ans == "quit"): exit(0) return ans """ This function does the bitwise and comparision to isolate the particular field It then shifts it to the end :param: user_in -> hex value of the user_in :param: bitmask -> The bitmask required to isolate a particular field :param: shift -> the number of bits to shift default 0 :return: temp_value -> The shifted value """ def get_shifted_value(instr, bitmask, shift=0): # do a bitwise and temp_value = (instr & bitmask) # do the logical shift temp_value >>= shift #return that shifted value return temp_value """ This method checks if the value entered by user is within the range of data in memory [0x0) - 0x7ff] """ def user_in_check_range_in_memory(user_in): if(int(user_in, 16) <= 0x7ff): return True else: return False
true
0071d76689c3c3a442cbaca460a887807dafd868
ElliottBarbeau/Leetcode
/Problems/Connect Ropes.py
698
4.21875
4
from heapq import * import heapq def minimum_cost_to_connect_ropes(ropeLengths): heapify(ropeLengths) result = 0 while ropeLengths: num1 = heappop(ropeLengths) num2 = heappop(ropeLengths) num3 = num1 + num2 result += num3 if ropeLengths: heappush(ropeLengths, num3) return result def main(): print("Minimum cost to connect ropes: " + str(minimum_cost_to_connect_ropes([1, 3, 11, 5]))) print("Minimum cost to connect ropes: " + str(minimum_cost_to_connect_ropes([3, 4, 5, 6]))) print("Minimum cost to connect ropes: " + str(minimum_cost_to_connect_ropes([1, 3, 11, 5, 2]))) main()
false
00486d3b5ace454b937fb86e85ddd78d8aaae3c6
sai-byui/NeuralNetV2
/TrainingData.py
1,642
4.1875
4
class TrainingData: """TrainingData class, used to enable easier input of training and testing data for a neural network""" def __init__(self): self.data_points_list = [] self.size = 0 def append(self, data_point): """Adds a DataPoint to the list.""" if isinstance(data_point, DataPoint): self.data_points_list.append(data_point) self.size += 1 else: raise Exception("Can only append objects of type DataPoint to TrainingData.") def get_inputs(self): """Returns only the inputs from each data point.""" data_inputs = [] for data_point in self.data_points_list: data_inputs.append(data_point.inputs) return data_inputs def get_expected(self): """Returns only the expected output values from each data point.""" data_expected = [] for data_point in self.data_points_list: data_expected.append(data_point.expected) return data_expected def getCopy(self): output = TrainingData() for d in self.data_points_list: output.append(d) return output class DataPoint: """Simple structure to hold the inputs and associated expected outputs of a single piece of data.""" def __init__(self, inputs, expected_outputs): self.inputs = inputs self.expected = expected_outputs def getCopy(self): inputs = [] expected = [] for i in self.inputs: inputs.append(i) for e in self.expected: expected.append(e) output = DataPoint(inputs,expected)
true
e9422e0be5dc1c5a1d0060072b313e7472c1d76a
Viraculous/python
/Widget and Gizmo.py
2,142
4.28125
4
# Excercise 2 #This excercise is an hypothetical example of a store which sells only two items '''An online retailer sells two products: widgets and gizmos. Each widget weighs 75 grams. Each gizmo weighs 112 grams. Write a program that reads the number of widgets and the number of gizmos in an order from the user. Then your program should compute and display the total weight of the order.''' #Here are my global variables import random print("Buy your Gizmo and Widget at Viraculous store") wigdet_weight = 75 gizmo_weight = 112 #Error handling try: no_of_widget_ordered = float(input("order your widget: ")) except ValueError: print("Error...numbers only. Retry") quit() try: no_of_gizmo_ordered = float(input("order your gizmo: ")) except ValueError: print("Error...numbers only. Retry") quit() #This is the total weight of gizmo and widget ordered respectively order_weight_of_gizmo = gizmo_weight * no_of_gizmo_ordered order_weight_of_widget = wigdet_weight * no_of_widget_ordered #stock of goods for each item is randomly generated,thus, the available stock is flexible gizmo_stock_available = (random.randrange(1,1000)) - no_of_gizmo_ordered widget_stock_available = (random.randrange(1,1000)) - no_of_widget_ordered #since available stock is flexible given the available stock of the objects,the "available_stock" function can be positive or negative except being constrained by some conditional statements def available_stock(gizmo_stock_available,widget_stock_available): return gizmo_stock_available + widget_stock_available #The total order weight is the objective of this excercise but i decided to add some more functions to the excercise def total_order_weight(order_weight_of_gizmo,order_weight_of_widget): return order_weight_of_gizmo + order_weight_of_widget print("gizmo stock = ", gizmo_stock_available) print("widget stock = ", widget_stock_available) print("Total available stock is ", available_stock(gizmo_stock_available,widget_stock_available)," pieces") print ("Your total order weight is ",total_order_weight(order_weight_of_gizmo,order_weight_of_widget))
true
866a9fd4476bd660f44435b5a5ef83a9b934f26f
constant-mihai/learnpython
/hellow/lists_in_python.py
1,880
4.53125
5
#!/usr/bin/python3 # ripped off of: https://overiq.com/python/3.4/lists-in-python/ # # Main # def main(): # Numbers is a refernce. Array is alloced on the heap numbers = [11, 99, 66, 22] type(numbers) # <class 'list'> print(numbers) # [11, 99, 66, 22] # A list can contain elements of same or different types. mixed = ["a string", 3.14, 199] # list where elements are of different types # List Concatenation # # List can be joined too using + operator. When operands on # both side are lists + operator creates a new list by combing # elements from both the lists. For example: list1 = [1,2,3] # create list1 list2 = [11,22,33] # create list2 print(id(list1)) # address of list1 print(id(list2)) # address of list2 list3 = list1 + list2 # concatenate list1 and list2 and create list3 print(list3) # [1, 2, 3, 11, 22, 33] # Notice that concatenation doesn't affect the list1 and list2, # their addresses remains the same before and after the concatenation. id(list3) # address of the new list list3 id(list1) # address of list1 is still same id(list2) # address of list2 is still same # Repetition Operator # #We can use * operator with lists too. It's syntax is: # sequence * n # The * operator replicates the list and then joins them. # Here are some examples: list1 = [1, 5] list2 = list1 * 4 # replicate list1 4 times and assign the result to list2 print(list2) # [1, 5, 1, 5, 1, 5, 1, 5] # You can also compare lists print(list1 < list2) # List comprehension cube_list = [ i**3 for i in range(50, 101) ] print(cube_list) # List comprehension with condition even_list = [ i for i in range(1, 10) if i % 2 == 0 ] print(even_list) # # Module check # if __name__ == "__main__": main()
true
6b2b08b88224072d04c73b783451b2ce5add7683
kishan-pj/pythonProject_clz
/class/learning.py
570
4.28125
4
from math import sqrt def distance(x1,y1,x2,y2): '''Calculate length of the line between two points''' dx = x2 - x1 dy = y2 -y1 d = sqrt(dx**2 + dy**2) return d def areaTriangle(x1,y1,x2,y2,x3,y3): side1 = distance(x1,y1,x2,y2) side2 = distance(x2,y2,x3,y3) side3 = distance(x3,y3,x1,y1) p = (side1 + side2 +side3)/2 t1 = p-side1 t2 = p-side2 t3 = p-side3 if t1==0 or t2==0 or t3==0: print("Does not form a triangle") area = sqrt(p*t1*t2*t3) return(area) ans = areaTriangle(0,0 ,0,2,2,0) print(ans)
false
3ea01e3499d58b2a1eb4e98bbafc6abf863f3c12
MRajibH/Python_zero_to_expert
/functions.py
382
4.21875
4
''' Write a function called calculate_area that takes base and height as an input and returns and area of a triangle. Equation of an area of a triangle is, ''' def calculate_area(base, height): return(0.5 * base * height) base = float(input("Enter Base: ")) height = float(input("Enter Height:")) answer = calculate_area(base, height) print(f'Area of triangle is {answer}')
true
9ee736e06fc7131a677fcda21e33d10601cd7242
PJHalvors/Learning_Python
/ZedEx32.py
1,443
4.6875
5
#!/bin/env/python #Exercise 33 #Set list name the_count to equal numeric values 1,2,3,4,5 the_count = [1, 2, 3, 4, 5] #Set list name fruits to equal numeric values 'apples', 'oranges', 'pears', 'apricots' fruits = ['apples', 'oranges', 'pears', 'apricots'] #Set list name change to numeric and character values 1, 'pennies', 2, 'dimes', 3, 'quarters' change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] #This is the first kind of for-loop that goies through a list #print a statement that includes a formatter for each number in the_count list for number in the_count: print "This is count %d" % number #same as above #print a statement that includes a formatter for each character-term in the fruit list for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range(0,6): print "Adding %d to the list." % i #append is a function that lists understand elements.append(i) #now we can print them out too for i in elements: print "Element was: %d" % i #Could you have avoided that for-loop entirely on line 22 and just assigned range(0,6) directly to elements? NewList = [range(2,5)] print "Adding %r to the list." % range NewList.append(range) print NewList
true
d9af284f85c697deec5d40e7a138a3751e3ecfd3
PJHalvors/Learning_Python
/ZedEx29.py
1,067
4.40625
4
#!/bin/env/python #Exercise 29 What if #Set numbers to variables people, cats and dogs people = 20 cats = 30 dogs = 15 #Set an if statement with a string dependent on it. #if a string returns TRUE, do function #This statement is TRUE, so it should show up if people < cats: print "Too many cats! The world is doomed!" #This statement is FALSE, so it should not show up if people > cats: print "Not many cats! The world is saved!" #This statement is FALSE, so it should not show up if people < dogs: print "The world is drooled on!" #This statement is TRUE, so it should show up if people > dogs: print "The world is dry!" #Set variable dogs within a range of 5 more or 5 less than its original value dogs += 5 #This statement is TRUE, so it should show up if people >= dogs: print "People are greater than or equal to dogs." #This statement is TRUE, so it should show up if people <= dogs: print "People are less than or equal to dogs." #This statement is TRUE, so it should show up if people == dogs: print "People are dogs."
true
9e0557e337086ac1ae8a8d089b24a9e452cdd112
JYab/learnpython
/ex18.py
1,048
4.28125
4
# this one is like your scripts with argv def print_two(*args): # line2 defines the print2 function arg1, arg2 = args # defines what arguements go into args print "arg1: %r, arg2: %r" % (arg1, arg2) # prints the two arg variabls and shows what strings are put into the variables #ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) ''' gives the print2again var the two args directly into its parenthesis and prints out the strings from arg1,2 just like line6. ''' # thsi just takes one argument def print_one(arg1): print "arg1: %r" % arg1 # this one takes no arguments def print_none(): print "I got nothin'," print_two("Zed","Shaw") print_two_again("Zed","Shaw") ''' These line adds what each arg variable will have In this case, arg1 = Zed & arg2 = Shaw''' print_one("First!") # Since print1 only has one argument, there is only one string to put into it print_none() # print_none doesn't have any strings so it doesn't print anything
true
978f7de7a2f3caffe843fa74a664827fb6f523f6
ZorkinMaxim/Python_school_lvl1
/inputFunc.py
2,800
4.21875
4
""" Очень часто для ввода с клавиатуры в python используется функция input() которая может вывести сообщения на экран и возвращает то что ввел пользователь с клавиатуры: value = input("Enter some value: ") однако она всегда возвращает тип "символьная строка" - string, что требует несомненно применить "преобразование" типа - для дальнейшего применения вводимого значения в том или ином случае. Для облегчения разработки, требуется создать 3 простые функции, каждая из которых должна позволить ввести с клавиатуры значение и вернуть значение уже "преопразованым" в нужный тип данных. Их имена: inputInt( message ) inputFloat( message ) inputBoolean( message ) каждая из них должна внутри себя использовать "input()" каждая преобразует значение в тип который упоминается в ее название После того как код функций будет создан, можно запустить для проверки такого рода код: n = inputInt("Enter the first integer: ") m = inputInt("Enter the second integer: ") print( n + m ) """ # def inputInt(message): # int_number = input(message) # i = int(int_number) # return i # def inputInt(message): # int_number = input(message) # if int_number.isdigit(): # i = int(int_number) # return i # else: # print("It isn't a digital") def inputInt(message): int_number = input(message) f = float(int_number) i = int(f) return i def inputFloat(message): float_number = input(message) f = float(float_number) return f def inputBoolean(message): bool_number = input(message) if bool_number == "True": return True if bool_number == "False": return False # n = inputInt("Enter the first integer: ") # m = inputInt("Enter the second integer: ") # print(n+m) # # n = inputFloat("Enter the first float number: ") # m = inputFloat("Enter the second float number: ") # print(n+m) n = inputBoolean("Enter the first boolean: ") m = inputBoolean("Enter the second boolean: ") print(n) print(m) # i = n + m # print(i) # print(type(i)) # # print("**************************************") # # b = bool(0) # print(b) # print(type(b))
false
160eab93a53303fb9b99ea182336461f1ca697e0
ZorkinMaxim/Python_school_lvl1
/reverse_string.py
204
4.1875
4
word = input("Enter a word: ") print(word) if word.isalpha(): print("True") else: print("False") for c in reversed(word): print(c, end='') print() word = word[::-1] print(word)
true
f14bb4b1ead26857eac8cc97ac4d8dbd7599ebe4
ii6uu99/ipynb
/python-note/python-programs-set-1-master/exercise_29.py
2,255
4.21875
4
print( '-----------------------------------------\n'\ 'Practical python education || Exercise-29:\n'\ '-----------------------------------------\n' ) print( 'Task:\n'\ '-----------------------------------------\n'\ '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.\n' ) print( 'Solution:\n'\ '-----------------------------------------'\ ) #Default function for handling execution loop: def execution_loop(): data = input("Do you want to try again ? Enter [y] - for continue / [n] - for quit : ") if data == "y": return True elif data == "n": return False else: print("Error: your entered incorrect command. Please, try again...") execution_loop() #Function for handling input colors: def color_inputs_handling(index): print("Please, enter your ", index, "-st color_list:") col_loop_param = True color_counter = 0 c_list = [] start_par = True while col_loop_param: if start_par: color_counter = color_counter + 1 print("Color-%d:" % color_counter) c_list.append(input("")) par = input("Do you want to add a new color to the color_list_1 ? Enter [y] - for adding a new color / [n] - for launching input a new color_list_2 :") if par == "y": col_loop_param = True start_par = True elif par == "n": col_loop_param = False else: col_loop_param = True start_par = False print("Error: you entered incorrect command. Please, try again...") return set(c_list) #Default parameters for handling execution loop: again_exec = True counter_exec = 0 #Default loop for handling execution: while again_exec: color_list_1 = color_inputs_handling(1) color_list_2 = color_inputs_handling(2) print("You entered color_list_1 wihout color_list_2 elements:") print(color_list_1.difference(color_list_2)) again_exec = execution_loop() counter_exec = counter_exec + 1 #The end of execution: if again_exec == False: print("Program was executed: ",counter_exec, ' times.') break print( '\n-----------------------------------------\n'\ 'Copyright 2019 Vladimir Pavlov. All Rights Reserved.\n'\ '-----------------------------------------' )
true
df17b23261f2e320aa1a4ba9bec2beb37c02af00
ii6uu99/ipynb
/python-note/python-programs-set-1-master/exercise_18.py
771
4.25
4
print( '-----------------------------------------\n'\ 'Practical python education || Exercise-18:\n'\ '-----------------------------------------\n' ) print( 'Task:\n'\ '-----------------------------------------\n'\ 'Write a Python program to test whether a number is within 100 of 1000 or 2000."\n' ) print( 'Solution:\n'\ '-----------------------------------------'\ ) def near_thousand(n): return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100)) print(near_thousand(534)) print(near_thousand(956)) print(near_thousand(1101)) print(near_thousand(1899)) print(near_thousand(2003)) print( '\n-----------------------------------------\n'\ 'Copyright 2018 Vladimir Pavlov. All Rights Reserved.\n'\ '-----------------------------------------' )
false
3344c33ba7840b3b66205feff660f657585ac4a0
ii6uu99/ipynb
/python-note/python-programs-set-1-master/exercise_25.py
1,923
4.25
4
print( '-----------------------------------------\n'\ 'Practical python education || Exercise-25:\n'\ '-----------------------------------------\n' ) print( 'Task:\n'\ '-----------------------------------------\n'\ 'Write a Python program to check whether a specified value is contained in a group of values.\n' ) print( 'Solution:\n'\ '-----------------------------------------'\ ) #Default function for handling execution loop: def execution_loop(): data = input("Do you want to try again ? Enter [y] - for continue / [n] - for quit : ") if data == "y": return True elif data == "n": return False else: print("Error: your entered incorrect command. Please, try again...") execution_loop() #Function for checking out membership of the group data: def is_group_member(group_data, n): n = str(n) for value in group_data: if n == value: print(n, " is a member of group data!") return print(n, " is not a member of group data!") #Default parameter for handling execution loop: again_exec = True counter_exec = 0 #Default loop for handling execution: while again_exec: data_user = list(input("Enter your list of group data: ")) n = int(input("Enter number for searching on the group data = ")) print("Your data group: ", data_user) is_group_member(data_user, n) ''' is_mebebr+swig = new_$$$_user_HTTP.token_new_user() data_logij_http_token = is_user_function() data_logij_http_request = new_function_request() data_logij_http_request = new_function_request() - new_main_request() ''' again_exec = execution_loop() counter_exec = counter_exec + 1 #The end of execution: if again_exec == False: print("Program was executed: ", counter_exec, ' times.') break print( '\n-----------------------------------------\n'\ 'Copyright 2019 Vladimir Pavlov. All Rights Reserved.\n'\ '-----------------------------------------' )
true
ae647de07f21bc35379cd098a0b7f8063a1eb02e
A01376726/Mision_04
/Rectangulos.py
1,630
4.1875
4
#José Manuel Rivera Sosapavón #Rectangulos #Escribe un programa que lea las dimensiones (base y altura) de dos rectángulos y que calcule e imprima el perímetro y área de cada uno. #• Escribe una sola función que reciba las dimensiones del rectángulo y regrese el área. #• Escribe una sola función que reciba las dimensiones del rectángulo y regrese el perímetro. #• El programa debe indicar cuál rectángulo tiene mayor área (primero o segundo), o si las áreas son iguales. def calcularArea(base,altura): area = base*altura return area def calcularPerimetro(base,altura): perimetro = (base*2) + (altura*2) return perimetro def main (): b1 = float(input("Tamaño de la base en cm: ")) h1 = float(input("Tamaño de la altura en cm: ")) b2 = float(input("Tamaño de la base en cm: ")) h2 = float(input("Tamaño de la altura en cm: ")) a1 = calcularArea(b1,h1) p1 = calcularPerimetro(b1,h1) a2 = calcularArea(b2,h2) p2 = calcularPerimetro(b2,h2) print ("Area del primer rectangulo: %.2f cm cuadrados" % (a1)) print ("Base del primer rectangulo: %.2f cm " % (b1)) print ("Area del segundo rectangulo: %.2f cm cuadrados" % (a2)) print ("Base del segundo rectangulo: %.2f cm " % (b2)) if a1>a2: print ("El area del primer rectangulo (%.2f) es mayor a la del segundo (%.2f)" % (a1,a2)) if a2>a1: print ("El area del segundo rectangulo (%.2f) es mayor a la del primer (%.2f)" % (a2,a1)) if a2 == a1: print ("El area de los rectangulos son iguales") main()
false
900f74ddacfe71f09fc6d087ff8166423dcbec8b
icodeforfunandprofit/CSC-131
/main_countAllLetters copy.py
253
4.1875
4
def main(): import countAllLetters file_name = input('Enter a file name: ') input_file = open(file_name, 'r') line = input('Enter a string: ') list_count = countAllLetters.countALLLetters(line) print(list_count)
false
9638471ec2e23a0e483e6f289c45ff4b5d42bd28
icodeforfunandprofit/CSC-131
/lab2C.py
472
4.21875
4
######################################## #Zane Bernard 1/24/2018 #section 004 ######################################## # Request the input print("Today we are going to calculate kinetic energy using your computer!") print("It's easy! Just enter the mass") m = int(input()) print("Great! Now the velocity...") v = int(input()) # compute the kinetic energy K = .5*(m*(v**2)) # Display the kinetic energy print("The kinetic energy is:", K) ########################################
true
5b043e037d6d53327f341b14d2495d09ddbef001
icodeforfunandprofit/CSC-131
/temp-convert.py
974
4.34375
4
# Temperature Conversion Program (Celsius-Fahrenheit / Fahrenheit-Celsius) # Display program welcome def welcome(): print('This program will convert temperatures (Fahrenheit/Celsius)') print('Enter (F) to convert Fahrenheit to Celsius') print('Enter (C) to convert Celsius to Fahrenheit') def tempConvert(which, temp): # Determine temperature conversion needed and display results if which == 'F': converted_temp = format((temp - 32) * 5/9, '.1f') #print(temp, 'degrees Fahrenheit equals', converted_temp, 'degrees Celsius') else: converted_temp = format((9/5 * temp) + 32, '.1f') #print(temp, 'degrees Celsius equals', converted_temp, 'degrees Fahrenheit') return converted_temp welcome() print() # Get temperature to convert which = input('Enter selection: ') temp = int(input('Enter temperature to convert: ')) converted = tempConvert(which) print(converted)
true