blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2e54f9ee0938beb93b9caa2c5417bf60a8870e2d
pasinducmb/Python-Learning-Material
/Genarator Expressions.py
811
4.1875
4
# Generator Expressions from sys import getsizeof # Comprehension for Lists and Tuples value = [(x + 1)**2 for x in range(10)] print("List: ", value) value = ((x + 1)**2 for x in range(10)) print("Tuple: ", value) # (reason for error is due to tuples are not coprehendible objects as Lists, sets and dictionaries, therefore generator objects) # Use Case: when infinite number of data is present which could take more memory for operating # Comprehension for Tuples (defining generator objects) value = ((x + 1)**2 for x in range(10)) for x in value: print("Gen: ", x) # Size Comparison between Lists and Gen Objects value = ((x + 1)**2 for x in range(1000000)) print("Gen Size:", getsizeof(value), "Bytes") value = [(x + 1)**2 for x in range(1000000)] print("List Size:", getsizeof(value), "Bytes")
true
f15f1cc97586bb5fc23b23499328542f93204ea5
wobedi/algorithms-and-data-structures
/src/implementations/sorting/quicksort.py
1,074
4.15625
4
from random import shuffle from src.implementations.sorting.basic_sorts import insertion_sort from src.implementations.helpers.partition import three_way_partition def quicksort(arr: list) -> list: """Sorts arr in-place by implementing https://en.wikipedia.org/wiki/Quicksort """ shuffle(arr) # shuffling in O(N) to avoid O(N2) edge case return _quicksort(arr, lower=0, upper=len(arr)-1) def _quicksort(arr: list, lower: int, upper: int) -> list: """Recursive implementation of quicksort""" if upper <= lower: return if upper - lower < 10: # Optimizing performance by using insertion sort for small sub arrays insertion_sort(arr) else: lt, gt = three_way_partition(arr, lower, upper) _quicksort(arr, lower, lt-1) _quicksort(arr, gt+1, upper) return arr if __name__ == '__main__': keys = [1, 2, 3, 10, 34, 22, 14, 21, 0] keys_sorted = sorted(keys) quick_sorted = quicksort(keys) print(f'Quicksort output: {quick_sorted}') assert quick_sorted == keys_sorted
true
ac318511b95f4566985bbe95436348c9077d06cb
DanieleOrnelas/4Linux_Python
/aula4/objetos.py
2,858
4.5625
5
#!/usr/bin/python3 # Uma classe associa dados (atributos) e operações (métodos) numa só estrutura. # Um objeto é uma instância de uma classe - uma representação da classe. class Carro(): def __init__(self, marca, modelo, ano): self.marca = marca self.modelo = modelo self.ano = ano self.hodometro = 0 def descrever(self): print('{} {} {}'.format(self.marca,self.modelo,self.ano)) def ler_hodometro(self): print('Este carro rodou {} km'.format(self.hodometro)) def atualiza_hodometro(self,kms): if kms >= self.hodometro: self.hodometro = kms def incrementa_hodometro(self,kms): if kms >= 0: self.hodometro += kms else: print('Não é possível diminuir km') meu_carro = Carro('VW','fusca','1980') meu_carro.descrever() meu_carro.atualiza_hodometro(50) meu_carro.ler_hodometro() meu_carro.incrementa_hodometro(50) meu_carro.ler_hodometro() exit() class Restaurantes(): def __init__(self, nome, tipo, aberto): self.nome = nome self.tipo = tipo self.aberto = aberto def descrever(self): print(('{} é um restaurante de ' + 'comida {}').format( self.nome,self.tipo,self.aberto)) def status(self): if self.aberto == True: print (' Está aberto'.format(self.nome)) else: print (' Está fechado'.format(self.nome)) primeiro = Restaurantes('Mcdonalds','fast food', True) segundo = Restaurantes('Outback', 'australiana', False) terceiro = Restaurantes('Marianas', 'brasileira', False) primeiro.descrever() primeiro.status() segundo.descrever() segundo.status() terceiro.descrever() terceiro.status() exit() class Usuario(): def __init__(self,nome,sobrenome): self.nome = nome self.sobrenome = sobrenome def descrever(self): print('Nome do usuario: {} {}\n'.format(self.nome,self.sobrenome)) def saudar(self): print(' Bom dia {} {}\n'.format(self.nome,self.sobrenome)) dornelas = Usuario('Daniele','Ornelas') pclyra = Usuario('Andre','Lyra') dornelas.descrever() dornelas.saudar() pclyra.descrever() pclyra.saudar() exit() class Cachorro(): """ Para class usar primeira letra em maiusculo no nome da classe""" dono = None def __init__(self,nome,idade): # Definição dos atributos desta classe e todo metodo criado dentro de uma classe deve definir como primeiro parametro o self. self.nome = nome self.idade = idade def descrever(self): # Definição das funções ou métodos da classe print('nome: {}\nidade: {}'.format(self.nome,self.idade)) def sentar(self): print('{} está sentado'.format(self.nome)) def rolar(self): print(('{} está rolando de um lado' + ' para o outro').format(self.nome)) meu_cachorro = Cachorro('jake',2) print('O dono é {}'.format(meu_cachorro.dono)) meu_cachorro.dono = 'joao' meu_cachorro.descrever() print('O dono é {}'.format(meu_cachorro.dono)) meu_cachorro.sentar() meu_cachorro.rolar()
false
4ba0168721fbd3bc17cac579b53e962d8a0a6ca3
DanieleOrnelas/4Linux_Python
/aula4/exercicios/objeto1.py
2,174
4.21875
4
#!/usr/bin/python3 # PROGRAMA PARA: # Classe User # ATRIBUTOS: Nome / Sobrenome / Username / Senha / Numero de Tentativas # METODOS: Descrever / Saudacao / Login (usando input) / Incrementar tentativas / Reseta Tentativas # PROGRAMA DO TIO class Usuario(): def __init__(self,nome,sobrenome,username,password): self.nome = nome self.sobrenome = sobrenome self.username = username self.password = password self.tentativas = 0 def descrever(self): print('Usuario {} pertence a {} {}\n'.format(self.username,self.nome,self.sobrenome)) def saudar(self): print(' Bom dia {} {}\n'.format(self.nome,self.sobrenome)) def reseta_tentativas(self): self.tentativas += 0 exit() def incrementa_tentativas(self): self.tentativas += 1 print('Número de tentativas: {}'.format(self.tentativas)) def login(self): while self.tentativas <= 3: u = input('Entre com o usuario: ') s = input('Entre com a senha: ') if u == self.username and s == self.password: print('Login efetuado com sucesso') self.reseta_tentativas() else: self.incrementa_tentativas() exit() dornelas = Usuario('Daniele','Ornelas','dornelas','123654') while True: dornelas.login() exit() # MEU PROGRAMA class Usuario(): def __init__(self,nome,sobrenome,username,password): self.nome = nome self.sobrenome = sobrenome self.username = username self.password = password self.tentativas = 3 def descrever(self): print('Usuario {} pertence a {} {}\n'.format(self.username,self.nome,self.sobrenome)) def saudar(self): print(' Bom dia {} {}\n'.format(self.nome,self.sobrenome)) def login(self): t = 1 while t <= self.tentativas: u = input('Entre com o usuario: ') s = input('Entre com a senha: ') if u == self.username and s == self.password: print('Login efetuado com sucesso') exit() else: x = self.tentativas - t if x != 0: print('Usuario ou senha incorretos. Tentativas restantes: ', x) else: print('Número de tentativas esgotadas!') t += 1 dornelas = Usuario('Daniele','Ornelas','dornelas','123654') # dornelas.descrever() # dornelas.saudar() dornelas.login()
false
55e3ac37f644ea67052a1c21aea38dac9b2e7b52
EcoFiendly/CMEECourseWork
/Week2/Code/test_control_flow.py
1,387
4.15625
4
#!/usr/bin/env python3 """ Some functions exemplifying the use of control statements """ __appname__ = '[test_control_flow.py]' __author__ = 'Yewshen Lim (y.lim20@imperial.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code/program" ## Imports ## import sys # module to interface our program with the operating system import doctest # import the doctest module ## Constants ## ## Functions ## def even_or_odd(x=0): # if not specified, x should take value 0 """ Find whether a number x is even or odd. >>> even_or_odd(10) '10 is Even!' >>> even_or_odd(5) '5 is Odd!' whenever a float is provided, then the closest integer is used: >>> even_or_odd(3.2) '3 is Odd!' in case of negative numbers, the positive is taken: >>> even_or_odd(-2) '-2 is Even!' """ # Define function to be tested if x % 2 == 0: # the conditional if return "%d is Even!" % x return "%d is Odd!" % x def main(argv): """ Prints each of the function with given argument """ print(even_or_odd(22)) print(even_or_odd(33)) return 0 if (__name__ == "__main__"): status = main(sys.argv) # sys.exit(status) # Can suppress the block of code containing def main() and if # (__name__ == "__main__") because you don't want/need to unit test that section # of the output doctest.testmod() # To run with embedded tests
true
9fd4ea33278bd1c477c4d7451e5367e426633409
hebertmello/pythonWhizlabs
/estudo_tuples.py
810
4.40625
4
# Tuples in Python # ------------------------------------- # - It is a similar to a list in python # - It is ordered an unchangeable # - It allows duplicate elements tuple = () print(tuple) tuple = (1, 2, 3) print(tuple) tuple = (1, "hello", 4, 5) print(tuple) tuple = ("mouse", [8, 4,5], (1, 2, 3)) print(tuple) tuple = 1, 2, 3 print(tuple) # type = str tuple = "mouse" print(type(tuple)) # type = tuple tuple = "mouse", 1 print(type(tuple)) tuple = ("mouse", [1, 2, 3], [2, 4.4, 5.5]) print(tuple[0][3]) print(tuple[1][2]) print(tuple[2][2]) tuple = "mouse", 1, 4, 6, 7, 8, 9 print(tuple[2:5]) tuple = [1, 2, 3], [4, 5, 6] tuple[1][2] = 7 print(tuple) tuple = 1, 2, 2, 3, 4, 5, 1, 1, 1 print(tuple.count(1)) print(tuple.count(2)) print(tuple.count(3))
false
5c96975d02b72a1519f58eb440f497c617f64b9f
hebertmello/pythonWhizlabs
/project1.py
581
4.15625
4
import random print ("Number guessing game") number = random.randint(1, 20) chances = 0 print("Guess a number between 1 and 20") while(chances < 5): guess = int(input()) if (guess == number): print("Congratulations you won!!!") break elif guess < number: print("Your guess is low and kindly select a higuer number", guess) else: print("Your guess is high and kindly select a lower number", guess) chances = chances + 1 else: if not chances < 5: print("You lose!! The number is", number)
true
9cf18fd8d46e4aa2cf12c1c51ce563ee7f85c43f
AxolotlDev/PruebasPython
/Ej3.py
447
4.15625
4
#Ejercicio 3 #Dados los catetos de un triángulo rectángulo, calcular su hipotenusa. import math CatetoMayor = int(input("Introduzca el valor del cateto mayor: ")) CatetoMenor = int(input("Introduzca el valor del cateto menor: ")) Hipotenusa = (math.sqrt(math.pow(CatetoMenor,2)+math.pow(CatetoMayor,2))) print(f"Siendo el cateto mayor {CatetoMayor} y el cateto menor {CatetoMenor}, la Hipotenusa del triangulo rectangulo es {Hipotenusa}.")
false
cc8e5c295453c6ce967e6b302bec73b7858bae04
OmarBahmad/Projetos-Python
/Exercícios Python/DESCOBRINDO TRIANGULO.py
1,182
4.15625
4
print('\033[33m-='*30) print('DESAFIO DOS TRIANGULOS V2.0') print('-='*30) print('\033[37mINTRUÇÕES: Adicione 3 lados de um triangulo e descubra se ele existe e qual formato ele tem.') print('\033[m') a = int(input('LADO A: ')) b = int(input('LADO B: ')) c = int(input('LADO C: ')) print('') if abs(b-c) < a < b+c and abs(a-c) < b < a+c and abs(a-b) < c < a+b: if a == b and b == c and a == c: print('EQUILATERO') elif a == b or b == c or a == c: print('ISOSCELES') else: print('ESCALENO') #if abs(b-c) >= a >= b+c and abs(a-c) >= b >= a+c and abs(a-b) >= c >= a+b: # print('Esse triangulo não pode existir!') #elif abs(b-c) < a < b+c and abs(a-c) < b < a+c and abs(a-b) < c < a+b and a == b and b == c and a == c: # print('\033[1:35mEste triangulo é EQUILATERO!') #elif abs(b-c) < a < b+c and abs(a-c) < b < a+c and abs(a-b) < c < a+b and (a == b or b == c or a == c): # print('\033[1:34mEste triangulo é ISOSCELES!') #elif abs(b-c) < a < b+c and abs(a-c) < b < a+c and abs(a-b) < c < a+b and a != b and a != c and b != c: # print('\033[1:32mEsse triangulo é ESCALENO!') else: print('\033[31mESSE TRIANGULO NÃO EXISTE!')
false
8383a43b540f04be1f3e20a85017c9f42fe4e13c
ugant2/python-snippate
/pract/string.py
1,664
4.3125
4
# Write a Python function to get a string made of the first 2 # and the last 2 chars from a given a string. If the string # length is less than 2, return instead of the empty string. def string_end(s): if len(s)<2: return ' ' return len(s[0:2]) + len(s[-2:]) print(string_end('laugh out')) # Write a Python program to change a given string to a new string # where the first and last chars have been exchanged. # def change_string(s): # # for i in s: # d = s[0:2] # e = s[:-2] # c = e + d # return c # # print(change_string("Austrlia")) def change_string(s): return s[-1:] + s[1:2] + s[-2:-1] + s[:1] print(change_string("abcd")) #using lambda function r = lambda s: s[-1:] + s[1:2] + s[-2:-1] + s[:1] print(r("this")) print("\n") # Write a Python program to remove the characters which have odd index values of a given string def remove_odd_char(c): result = " " for i in range(len(c)): if i%2 == 0: result += c[i] return result print(remove_odd_char("bcdef")) print("\n") # Write a Python script that takes input from the user and # displays that input back in upper and lower cases. def upperLower(t): f = input("enter string: ") return f.upper()*2, f.lower() #return t.upper(), t.lower() result = upperLower(2) print(result) #print(upperLower("can ydou discover mystery in book...")) #using lambda function upperLowerCase = lambda c: (c.upper(), c.lower()) print(upperLowerCase("i shoot for the moon but i am too busy gazin stars")) print(upperLowerCase("udai lagyo panxi(bird) ley nadi tira, dana deya dhana ghatdina vancan bhakta kabira"))
true
75a068175dd23bd786319ab2df60e61aee8dbfa1
ugant2/python-snippate
/oop/inheritance Animal.py
651
4.34375
4
# Inheritance provides a way to share functionality between classes. # Imagine several classes, Cat, Dog, Rabbit and so on. Although they may # differ in some ways (only Dog might have the method bark), # they are likely to be similar in others (all having the attributes color and name). class Animal: def __init__(self, name, color): self.name = name self.color = color # class Cat, Animla is a supar class class Cat(Animal): def purr(self): print("Purr...") # class Dog class Dog(Animal): def bark(self): print("Woof!") #objects fido = Dog("Fido", "Brown") print(fido.color, fido.name) fido.bark()
true
7afc1fba01851dd2e64ff935580eba6b76f4efb2
viniromao159/converterBinDec
/main.py
1,629
4.25
4
import os def converter(operation, valor): #<----- Função de conversão if operation == 1: result = int(valor, base=2) return result else: valor = int(valor) return bin(valor)[2:] os.system('cls') or None # limpeza do terminal cont = 0 while cont < 1: # Menu do sistema print('\n--- Conversor de numero Binario ---\n') print('--- Escolha a operação ---') print('--- 1: Bin ----> Dec ---') print('--- 2: Dec ----> Bin ---') print('--- 3: Sair do programa ---\n') operation = int(input("Digite a operação: ")) print() if operation == 1: #<---- Validador de operação os.system('cls') or None valor = str(input("Digite o valor: ")) valor_int = list(valor)#<----validando o binario bin = True for num in valor_int: if num != "0" and num != "1": bin = False #<----Fim validador if bin == True: print() print("O valor {} convertido é {} \n".format(valor, converter(operation, valor))) else: print("Valor Invalido") elif operation == 2: os.system('cls') or None valor = int(input("Digite o valor: ")) print() print("O valor {} convertido é {} \n".format(valor, converter(operation, valor))) elif operation == 3: os.system('cls') or None cont += 1 print("--- Fim do programa! ---") else: os.system('cls') or None print("Operação invalida\n") #<---- Fim do validador de operação
false
a8af418b9cff8cb6ee6da6dea287fbd6b8e9034c
mikhael-oo/honey-production-codecademy-project
/honey_production.py
1,525
4.1875
4
# analyze the honey production rate of the country # import all necessary libraries import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model # import file into a dataframe df = pd.read_csv("https://s3.amazonaws.com/codecademy-content/programs/data-science-path/linear_regression/honeyproduction.csv") print(df.head()) # group into yearly average production prod_per_year = df.groupby('year').totalprod.mean().reset_index() # select the years X = prod_per_year.year X = X.values.reshape(-1, 1) # select the yearly produce y = prod_per_year.totalprod # using Linear Regression to predict regr = linear_model.LinearRegression() regr.fit(X, y) # getting the slope of the line print(regr.coef_[0]) # getting the intercept of the line print(regr.intercept_) # get the predicted y values y_predict = regr.predict(X) # plot the data plt.figure(figsize=(8,6)) plt.scatter(X, y, alpha=0.4) plt.plot(X, y_predict) plt.xlabel('Year') plt.ylabel('Average Produce') plt.title('Average Produce Per Year') plt.show() plt.clf() # to predict rate of produce for coming years # store the years into an array and rotate them X_future = np.array(range(2013,2051)) X_future = X_future.reshape(-1, 1) # future predictions of y_values future_predict = regr.predict(X_future) # plot the data plt.plot(X_future, future_predict) plt.title('Average Produce Per Year') plt.xlabel('Year') plt.ylabel('Average Produce') plt.show()
true
7cabb3d44067c67d5ed50700fa3120ad2277053c
vgates/python_programs
/p010_fibonacci_series.py
940
4.46875
4
# Python program to print first n Fibonacci Numbers. # The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... # The sequence is characterized by the fact that every number after the # first two is the sum of the two preceding ones. # get the user input and store it in the variable n # int function is used to convert the user input to integer n = int( input("Enter the value for n: ") ) a = 0 # first fibonacci number b = 1 # second fibonacci number sum = 0 # sum of the two preceding ones # Print first number, second number. # Print should not end with a new line, instead it ends with a space # since we need to print the sequence in the same line. Hence provided with end = " " print( a, b, end = " ") for i in range( 2, n ): sum = a + b # add previous two numbers a = b b = sum print(sum , end=" ") print("") # just to print a new line when the sequence is complete
true
4b2b1f3eb6ebadc10e0737b8affbfc0351d0e87d
vgates/python_programs
/p015_factorial.py
1,015
4.34375
4
# Python program to find factorial of a number # Factorial of a number n is the multiplication of all # integers smaller than or equal to n. # Example: Factorial of 5 is 5x4x3x2x1 which is 120. # Here we define a function for calculating the factorial. # Note: Functions are the re-usable pieces of code which # helps us to organize structure of the code. # Python uses def keyword to start a function. # Refer https://thepythonguru.com/python-functions/ def factorial( input_number ): temp_factorial = 1 for i in range(1, input_number + 1): temp_factorial = temp_factorial * i return temp_factorial # get the user input and store it in the variable input_number # int function is used to convert the user input to integer input_number = int( input("Enter the number: ") ) # call the factorial function which we have defined calculated_factorial = factorial( input_number ) # Print print("Factorial of {0} = {1}".format( input_number, calculated_factorial) )
true
fd73120ca7a5ac32608d0aec17003c45fb9198a0
JazzyServices/jazzy
/built_ins/slices.py
1,850
4.25
4
# encoding=ascii """Demonstrate the use of a slice object in __getitem__. If the `start` or `stop` members of a slice are strings, then look for those strings within the phrase and make a substring using the offsets. If `stop` is a string, include it in the returned substring. This code is for demonstration purposes only. It is not 100% correct. For example, it does not support negative steps in a "natural" way. """ class Phrase: """Demonstrate custom __getitem__ taking a slice argument.""" def __init__(my, phrase: str): """Initialise with a string phrase.""" my.phrase = phrase def __getitem__(my, item): """Get an item or a slice.""" if isinstance(item, slice): return my._getslice(item) return my.phrase[item] def _getslice(my, sli): start, stop, step = sli.start, sli.stop, sli.step try: # if start is a string, slice from there if isinstance(start, str): start = my.phrase.index(start) # if stop is a string, slice to the end of it if isinstance(stop, str): stop = my.phrase.index(stop) + len(stop) except ValueError: return '' return my.phrase[start:stop:step] def main(): """Demonstrate the Phrase class.""" phrase = Phrase('Now is the winter of our discontent.') print(f'Integer subscription: [8]={phrase[8]} [-1]={phrase[-1]}') print(f'Integer slicing: [7,10]={phrase[7:10]}') print('Slicing using strings ...') print(f"| from 'the' to 'of': ({phrase['the':'of']})") print(f"| from 'the' to 'unfound': ({phrase['the':'unfound']})") print(f"| upto the word 'winter': ({phrase[:'winter']})") print(f"| from the word 'winter' onwards: ({phrase['winter':]})") if __name__ == '__main__': main()
true
12a5c1259f669055442de8ddfb7dfd6245e2bcbf
chagaleti332/HackerRank
/Practice/Python/Collections/namedtuple.py
2,990
4.59375
5
""" Question: Basically, namedtuples are easy to create, lightweight object types. They turn tuples into convenient containers for simple tasks. With namedtuples, you don’t have to use integer indices for accessing members of a tuple. Example: Code 01 >>> from collections import namedtuple >>> Point = namedtuple('Point','x,y') >>> pt1 = Point(1,2) >>> pt2 = Point(3,4) >>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y ) >>> print dot_product 11 Code 02 >>> from collections import namedtuple >>> Car = namedtuple('Car','Price Mileage Colour Class') >>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y') >>> print xyz Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y') >>> print xyz.Class Y Task: Dr. John Wesley has a spreadsheet containing a list of student's IDs, marks, class and name. Your task is to help Dr. Wesley calculate the average marks of the students. Sum of all marks Average = ------------------ Total students Note: 1. Columns can be in any order. IDs, marks, class and name can be written in any order in the spreadsheet. 2. Column names are ID, MARKS, CLASS and NAME. (The spelling and case type of these names won't change.) Input Format: * The first line contains an integer n, the total number of students. * The second line contains the names of the columns in any order. * The next lines contains the marks, IDs, name and class, under their respective column names. Constraints: * 0 <= N <= 100 Output Format: Print the average marks of the list corrected to 2 decimal places. Sample Input: TESTCASE 01 5 ID MARKS NAME CLASS 1 97 Raymond 7 2 50 Steven 4 3 91 Adrian 9 4 72 Stewart 5 5 80 Peter 6 TESTCASE 02 5 MARKS CLASS NAME ID 92 2 Calum 1 82 5 Scott 2 94 2 Jason 3 55 8 Glenn 4 82 2 Fergus 5 Sample Output: TESTCASE 01 78.00 TESTCASE 02 81.00 Explanation: TESTCASE 01 Average = (97 + 50 + 91 + 72 + 80)/5 Can you solve this challenge in 4 lines of code or less? NOTE: There is no penalty for solutions that are correct but have more than 4 lines. """ # Solution: # Enter your code here. Read input from STDIN. Print output to STDOUT from collections import namedtuple if __name__ == '__main__': no_of_students = int(input()) Student = namedtuple('Student', input().strip()) total_marks = sum([int(Student(*input().strip().split()).MARKS) for _ in range(no_of_students)]) print('{:02f}'.format(total_marks / no_of_students))
true
24a0e80c3f81577f00b5b2096e4b32992914db5e
chagaleti332/HackerRank
/Practice/Python/Math/integers_come_in_all_sizes.py
960
4.4375
4
""" Question: Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there is: 2^31 - 1(c++ int) or 2^63 - 1(C++ long long int). As we know, the result of a^b grows really fast with increasing b. Let's do some calculations on very large integers. Task: Read four numbers, a, b, c, and d, and print the result of a^b + c^d. Input Format: Integers a, b, c, and d are given on four separate lines, respectively. Constraints: * 1 <= a <= 1000 * 1 <= b <= 1000 * 1 <= c <= 1000 * 1 <= d <= 1000 Output Format: Print the result of a^b + c^d on one line. Sample Input: 9 29 7 27 Sample Output: 4710194409608608369201743232 Note: This result is bigger than 2^63 -1. Hence, it won't fit in the long long int of C++ or a 64-bit integer. """ # Solution: a = int(input()) b = int(input()) c = int(input()) d = int(input()) print(pow(a, b) + pow(c, d))
true
56049a2b6eaef72e1d4381a7f76a1d4cb9800912
chagaleti332/HackerRank
/Practice/Python/Introduction/python_print.py
441
4.4375
4
""" Question: Read an integer N. Without using any string methods, try to print the following: 123....N Note that "" represents the values in between. Input Format: The first line contains an integer N. Output Format: Output the answer as explained in the task. Sample Input: 3 Sample Output: 123 """ # Solution: if __name__ == '__main__': n = int(input()) for i in range(1, n + 1): print(i, end='')
true
08605343a771a0837e3383972c370a03516db4aa
chagaleti332/HackerRank
/Practice/Python/Sets/set_add.py
1,440
4.5625
5
""" Question: If we want to add a single element to an existing set, we can use the .add() operation. It adds the element to the set and returns 'None'. Example >>> s = set('HackerRank') >>> s.add('H') >>> print s set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R']) >>> print s.add('HackerRank') None >>> print s set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R']) Task: Apply your knowledge of the .add() operation to help your friend Rupal. Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of country stamps. Find the total number of distinct country stamps. Input Format: The first line contains an integer N, the total number of country stamps. The next N lines contains the name of the country where the stamp is from. Constraints: * 0 < N < 1000 Output Format: Output the total number of distinct country stamps on a single line. Sample Input: 7 UK China USA France New Zealand UK France Sample Output: 5 Explanation: UK and France repeat twice. Hence, the total number of distinct country stamps is 5 (five). """ # Solution: if __name__ == '__main__': n = int(input()) s = set() for _ in range(n): s.add(input()) print(len(s))
true
59e25fa8a6649f0d23deaa9fe33e4df78f674c03
chagaleti332/HackerRank
/Practice/Python/Introduction/python_loops.py
458
4.1875
4
""" Question: Task Read an integer N. For all non-negative integers i < N, print i^2. See the sample for details. Input Format: The first and only line contains the integer, N. Constraints: * 1 <= N <= 20 Output Format: Print N lines, one corresponding to each . Sample Input: 5 Sample Output: 0 1 4 9 16 """ # Solution: if __name__ == '__main__': n = int(input()) for i in range(n): print(i ** 2)
true
2d0beaf86a1f65715dbdacdcf07aec623856b6cb
chagaleti332/HackerRank
/Practice/Python/Sets/the_captains_room.py
1,570
4.15625
4
""" Question: Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms. One fine day, a finite number of tourists come to stay at the hotel. The tourists consist of: → A Captain. → An unknown group of families consisting of K members per group where K ≠ 1. The Captain was given a separate room, and the rest were given one room per group. Mr. Anant has an unordered list of randomly arranged room entries. The list consists of the room numbers for all of the tourists. The room numbers will appear times per group except for the Captain's room. Mr. Anant needs you to help him find the Captain's room number. The total number of tourists or the total number of groups of families is not known to you. You only know the value of K and the room number list. Input Format: * The first line consists of an integer, K, the size of each group. * The second line contains the unordered elements of the room number list. Constraints: * 1 < K < 1000 Output Format: Output the Captain's room number. Sample Input: 5 1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2 Sample Output: 8 Explanation: The list of room numbers contains 31 elements. Since K is 5, there must be 6 groups of families. In the given list, all of the numbers repeat 5 times except for room number 8. Hence, 8 is the Captain's room number. """ # Solution: k = int(input()) room_nos = list(map(int, input().strip().split())) rooms = set(room_nos) print((sum(rooms) * k - sum(room_nos)) // (k - 1))
true
4735407294bd47ed69477087a1f628d3426d0cfb
chagaleti332/HackerRank
/Practice/Python/RegexAndParsing/group_groups_groupdict.py
2,019
4.4375
4
""" Question: * group() A group() expression returns one or more subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com') >>> m.group(0) # The entire match 'username@hackerrank.com' >>> m.group(1) # The first parenthesized subgroup. 'username' >>> m.group(2) # The second parenthesized subgroup. 'hackerrank' >>> m.group(3) # The third parenthesized subgroup. 'com' >>> m.group(1,2,3) # Multiple arguments give us a tuple. ('username', 'hackerrank', 'com') * groups() A groups() expression returns a tuple containing all the subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com') >>> m.groups() ('username', 'hackerrank', 'com') * groupdict() A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name. Code >>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)', 'myname@hackerrank.com') >>> m.groupdict() {'website': 'hackerrank', 'user': 'myname', 'extension': 'com'} Task You are given a string S. Your task is to find the first occurrence of an alphanumeric character in S(read from left to right) that has consecutive repetitions. Input Format: A single line of input containing the string S. Constraints: 0 < len(S) < 100 Output Format: Print the first occurrence of the repeating character. If there are no repeating characters, print -1. Sample Input: ..12345678910111213141516171820212223 Sample Output: 1 Explanation: .. is the first repeating character, but it is not alphanumeric. 1 is the first (from left to right) alphanumeric repeating character of the string in the substring 111. """ # Solution: # Enter your code here. Read input from STDIN. Print output to STDOUT import re string = input() ans = re.search(r'([^\W_])\1+', string) print(ans.group(1) if ans else -1)
true
6ab8e6e334434326b8d52145366e35ac535e8dd9
chagaleti332/HackerRank
/Practice/Python/BasicDataTypes/lists.py
1,968
4.34375
4
""" Question: Consider a list (list = []). You can perform the following commands: * insert i e: Insert integer e at position i. * print: Print the list. * remove e: Delete the first occurrence of integer e. * append e: Insert integer e at the end of the list. * sort: Sort the list. * pop: Pop the last element from the list. * reverse: Reverse the list. Initialize your list and read in the value of n followed by n lines of commands where each command will be of the 7 types listed above. Iterate through each command in order and perform the corresponding operation on your list. Input Format: The first line contains an integer, n, denoting the number of commands. Each line i of the n subsequent lines contains one of the commands described above. Constraints: * The elements added to the list must be integers. Output Format: For each command of type print, print the list on a new line. Sample Input: 12 insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print pop reverse print Sample Output: [6, 5, 10] [1, 5, 9, 10] [9, 5, 1] """ # Solution: ACTION = 0 if __name__ == '__main__': N = int(input()) dlist = [] for _ in range(N): command = input().strip().split() if command[ACTION] == 'insert': position, data = int(command[1]), int(command[2]) dlist.insert(position, data) elif command[ACTION] == 'remove': data = int(command[1]) dlist.remove(data) elif command[ACTION] == 'print': print(dlist) elif command[ACTION] == 'reverse': dlist.reverse() elif command[ACTION] == 'sort': dlist = sorted(dlist) elif command[ACTION] == 'append': data = int(command[1]) dlist.append(data) elif command[ACTION] == 'pop': dlist.pop()
true
162cd5c5c636f39d116bb3b928b70ce60f1bf25c
khidmike/learning
/Python/caesar.py
849
4.21875
4
# Simple program using a Caesar Cipher to encode / decode text strings import sys def main(): print("Welcome to the Caesar Cipher Encoder / Decoder") print() coding = str(input("What would you like to do? Type 'e' to encode / 'd' to decode: ")) if (coding != "e") and (coding != "d"): print("I'm sorry... I don't understand what you want me to do") sys.exit() key = int(input("What is the key you would like to use? Type a number 1-25: ")) text = list(str(input("What is the text you would like to encode: "))) result = [] if coding == "e": for char in text: result.append(chr(ord(char) + key)) elif coding == "d": for char in text: result.append(chr(ord(char) - key)) print("Your result is: ") print() print("".join(result)) main()
true
69fb03d6f9a26a2b1633c09ec2b9f72133c40627
kmenon89/python-practice
/dictionary.py
1,030
4.125
4
#all about dictiionaries #create dicti={1:'a',2:'b',3:'c'} print(dicti) print(dicti[1]) #append dicti[4]='d' print(dicti) #deletion del dicti[4] print(dicti) #get a value print(dicti.get(2)) #clear whole dicti dicti.clear() print(dicti) #sort dicti dicti={2:'a',3:'b',1:'c'} print(dicti) order=dicti.keys() print(order) order=list(dicti.keys()) print(order) order.sort() print(order) print(dicti) ordered=sorted(list(dicti)) print(ordered) print(dicti) print(list(dicti)) #print items of dicti print(dicti.values()) print(dicti.keys()) print(dicti.items()) #conv tup=tuple(dicti.items()) print(tup) print(dict(tup)) #update,copy print(dicti) dict2={4:"d",5:"e",6:"f"} print(dict2) #print(dicti.update(dict2))--> prints none but updates the dictionary #print(dict2.update(dicti))--> prints none but updates the dictionary dicti.update(dict2) print(dicti) print(dict2) dict3=dict2.copy() print(dict3) print(dict3.update(dicti)) print(dict3) print(dict2)
false
bf45447e0c258970584c89c445b40d7d84193812
kmenon89/python-practice
/whileloopchallenge.py
613
4.53125
5
#get the line length ,angle,pen color from user and keep drawing until they give length as 0 #import turtle to draw import turtle # declare variables len=1 angle=0 pcolour="black" #use while loop while len != 0 : #get input from user about length angle and pen colour len=int(input("welcome to sketch /n please enter the length of the line you want to sketch:")) angle=int(input("please give the angle of the line to be drawn:")) pcolour=input("please eneter the color of pen you want to use:") turtle.color(pcolour) turtle.right(angle) turtle.forward(len)
true
679a164e1ffe6086681b2ec1c990633cadb673ba
kmenon89/python-practice
/fibonacci.py
929
4.1875
4
#fibinacci series a=0 b=1 #n=int(input("please give the number of fibonacci sequence to be generated:")) n=int(input("please give the maximum number for fibonacci sequence to be generated:")) series=[] series.append(a) series.append(b) length=len(series)-1 print(length,series[length]) while len(series)<n:#--> comment when print fibonacci for a number lesser than equal to given number #while series[length]<=n: #-->uncomment when print fibonacci for a number lesser than equal to given number x=len(series) print(x) n1=series[x-1]+series[x-2] #if n1<=n : #--> uncomment when print fibonacci for a number lesser than equal to given number if len(series)<n:#--> comment when print fibonacci for a number lesser than equal to given number series.append(n1) print(series) length=len(series)-1 else: break print(series)
true
e8c815f504f17c7909b98324c18d1a9ef3d06c47
gustavopierre/Introduction_to_Programming_using_Python
/list_demo.py
986
4.125
4
empty_list = list() print("empty_list ->", empty_list) list_str = list("hello") print("list_str ->", list_str) list_tup = list((1, 2, (3, 5, 7))) print("list_tup ->", list_tup) empty_list = [] print("empty_list ->", empty_list) list_syn = [3, 4, "a", "b"] print("list_syn ->", list_syn) print("'a' in list_syn ->", 'a' in list_syn) print("3 not in list_syn ->", 3 not in list_syn) empty_list.append(5) print("empty_list ->", empty_list) empty_list.append([6, 7]) print("empty_list ->", empty_list) last_elem = empty_list.pop() print("last_elem ->", last_elem) print("empty_list ->", empty_list) empty_list.extend([6, 7]) print("empty_list ->", empty_list) first_elem = empty_list.pop(0) print("first_elem ->", first_elem) print("empty_list ->", empty_list) empty_list.insert(0,10) print("empty_list ->", empty_list) empty_list.insert(3,100) print("empty_list ->", empty_list) empty_list.remove(7) print("empty_list ->", empty_list) empty_list.clear() print("empty_list ->", empty_list)
false
d2015bc58d2c72e4d91ea716ba2cc6cf05f064ec
bartkim0426/deliberate-practice
/exercises4programmers/ch03_operations/python/07_rectangle.py
1,462
4.375
4
''' pseudocode get_length_and_width length: int = int(input("What is the length of the room in feet? ")) width: int = int(input("What is the width of the room in feet? ")) end calculate_feet_to_meter squre_meter: float = round(square_feet * 0.09290304, 3) end calculate_squre_feet squre_feet = length * width end main length, width = get_length_and_width() squre_feet = calculate_squre_feet(length, width) squre_meter = calculate_feet_to_meter(squre_feet) print_out result end ''' SQUARE_METER = 0 def get_length_and_width() -> tuple: '''get length and width from std input''' length: int = int(input("What is the length of the room in feet? ")) width: int = int(input("What is the width of the room in feet? ")) return length, width def calculate_feet_to_meter(square_feet: int) -> float: square_meter: float = round(square_feet * 0.09290304, 3) return square_meter def calculate_square(length: int, width: int) -> int: return length * width def rectangle_squre(): '''calculate rectangle square from feet into meter''' length, width = get_length_and_width() square_feet = calculate_square(length, width) global SQUARE_METER SQUARE_METER = calculate_feet_to_meter(square_feet) print(f'''You entered dimensions of {length} feet by {width} feet The area is {square_feet} square feet {SQUARE_METER} square meters''') if __name__ == '__main__': rectangle_squre()
true
db4e3b325d7041142680a0ceff285d6f7a8fdb39
brunacarenzi/thunder-code
/maior e menor num..py
751
4.21875
4
# mostrar qual valor é o maior e qual e o menor print('Olá, por favor teste este esse programa.') n1 = int(input('Informe o 1º número: ')) n2 = int(input('Informe o 2º número:')) n3 = int(input('Informe o 3º número:')) # Verificando o menor número menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 # Verificando o maior número maior = n1 if n2 > n1 and n2 > n3: maior = n2 if n3 > n1 and n3 > n2: maior = n3 print('O menor número é:{}'.format(menor)) print('O maior número é: {}'.format(maior)) print(f'Multiplicação entre maior e menor número: {maior} * {menor} = {maior * menor}') print(f'Soma entre maior e menor número: {maior} + {menor} = {maior + menor}' )
false
91ce1227c7ee2803c148909cf6bf59246429fad2
brunacarenzi/thunder-code
/meses.py
1,046
4.21875
4
'''Escreva o método chamado getMesPorExtenso() que recebe um inteiro, referente ao mês do ano, um código referente ao idioma (1 para português e 2 para inglês) e retorne o mês por extenso. A tabela a seguir ilustra alguns exemplos.''' #meses em Português mesesp = ('zero', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro') #meses em Inglês mesesi = ('zero', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', ' October', 'November', 'December') while True: numero = int(input('*Digite um número entre 1 e 12 que te direi qual é o mês: ')) if 0 <= numero <= 12: break print('Tente novamente', end='') op = int(input('* Digite 1 para português ou 2 para ingles: ')) if op == 1: print(f'* Você digitou opção 1 [português]: o mês é {mesesp[numero]}') elif op == 2: print(f'* Você digitou opção 2 [inglês]: the month is {mesesi[numero]}')
false
f3ac0037df5a2ecca66736e8a54739d6b178e093
Shweta-yadav12/if-else
/calcualator.py
394
4.34375
4
num1=int(input("enter the number")) num2=int(input("enter the number")) num3=input("enter the number") if num3=="+": print(num1+num2) elif num3=="-": print(num1-num2) elif num3=="*": print(num1*num2) elif num3=="/": print(num1/num2) elif num3=="%": print(num1%num2) elif num3=="**": print(num1**num2) elif num3=="//": print(num1//num2) else: print("wrong")
false
fe290593c81f87f7e51b979d896b3b64a38d0c6d
DilaraPOLAT/Algorithm2-python
/5.Hafta(list,tuple)/venv/ornek2.py
1,187
4.375
4
""" ornek2: rasgele uretilen bir listenin elemanlarinin frekans degerlerini bulan ve en yuksek frekans degerine sahip sayiyi gosteren python kodunu yazınız. """ import random randlist=[random.randint(1,100) for i in range(100)] print(randlist) freq=[0]*100 max_freq=0 max_num=0 # for num in range(1,100): # for item in randlist: # if num ==item: # freq[num]+=1 # if max_freq < freq[num]: # max_freq=freq[num] # max_num=num # print(freq) # print("maks.frekans = {} ,sayi ={}".format(max_freq,max_num)) #2.YOL: # for num in range(1,100): # for item in randlist: # if num ==item: # freq[num] += 1 # max_freq=max(freq) # max_num=freq.index(max_freq) # print(freq) # print("maks.frekans = {} ,sayi ={}".format(max_freq,max_num)) #3.yol: # for num in range(1,100): # freq[num] = randlist.count(num) # max_freq = max(freq) # max_num=freq.index(max_freq) # print(freq) # print("maks.frekans = {} ,sayi ={}".format(max_freq,max_num)) #4.YOL: freq=[randlist.count(num) for num in range(1,100)] max_freq = max(freq) max_num=freq.index(max_freq) print(freq) print("maks.frekans = {} ,sayi ={}".format(max_freq,max_num))
false
beadb79ce6c4df356833bf50da1c989b1f18bbb0
hanyunxuan/leetcode
/766. Toeplitz Matrix.py
884
4.5
4
""" A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an M x N matrix, return True if and only if the matrix is Toeplitz. Example 1: Input: matrix = [ [1,2,3,4], [5,1,2,3], [9,5,1,2] ] Output: True Explanation: In the above grid, the diagonals are: "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". In each diagonal all elements are the same, so the answer is True. Example 2: Input: matrix = [ [1,2], [2,2] ] Output: False Explanation: The diagonal "[1, 2]" has different elements. """ # my solution matrix = [ [1,2,3,4], [5,1,2,3], [9,5,1,2] ] numrows=len(matrix) numcols=len(matrix[0]) for i in range(numrows-1): for j in range(numcols-1): if matrix[i][j] != matrix[i+1][j+1]: a=1 # amazing solution all(matrix[row+1][1:] == matrix[row][:-1] for row in range(len(matrix)-1))
true
e77bbe516fc274f1e9cd3c8614f614ccfd4ab490
Raushan117/Python
/014_Append_Mode.py
827
4.5
4
# Reference: https://automatetheboringstuff.com/chapter8/ # Writing in plaintext mode and appending in plaintext mode # Passing a 'w' or 'a' in the second arugment of open() # If the file does not exist, both argument will create a new file # But remember to close them before reading the file again. # About: # Creating a simple program that ask user for filename (with extension) # and then create this file and write the message to the file. import os filename = input('Please enter the filename: ') information = input('What do you want to write? ') currentDir = os.getcwd() # Create a file with the name defined by user # If it is the same file, you can keep writing to it :) newFile = open(os.path.join(currentDir, filename), 'a') newFile.write(information) newFile.close() print(filename + ' is created. Thanks!')
true
6beca592164142ea3b6381ec9185b4791ca208ad
sagsh018/Python_project
/18_Tuple_unpacking_with_python_function.py
2,410
4.625
5
# in this lecture we are going to learn more about function, and returning multiple items from function using tuple # unpacking # Suppose we want to write a function, which takes in a list of tuples having name of employee and number of hrs worked # We have to decide who is the employee of the month based number of hours employee worked. so highest number of hours # more chances of wining. # notice that we need to return the name of the employee who worked the most(in short employee of the month along with # number of hours he worked my_list = [('vivek', 200), ('sahil', 300), ('ramya', 500)] print(my_list) # [('vivek', 200), ('sahil', 300), ('ramya', 500)] def emp_of_month(my_list): for item in my_list: print(item) emp_of_month(my_list) # ('vivek', 200) # ('sahil', 300) # ('ramya', 500) # Now lets tuple unpacking into consideration def emp_of_month(my_list): for emp, hrs in my_list: print(f'{emp} worked for {hrs} this month') emp_of_month(my_list) # vivek worked for 200 this month # sahil worked for 300 this month # ramya worked for 500 this month # now lets write a function who worked for maximum hours in office for the month def emp_of_month(my_list): hours = 0 employee = '' for emp, hrs in my_list: if hrs > hours: hours = hrs employee = emp else: pass return employee, hours no_of_emp = int(input('Please enter how many employees do you have : ')) x = 1 my_list = [] while x <= no_of_emp: emp_name = input('Enter emp name : ') hours_detail = int(input('Enter his hours details : ')) my_list.append((emp_name, hours_detail)) x += 1 print(f'Employees detail you have entered : {my_list}') choice = input('Is the information entered by you correct (yes/no) : ') if choice == 'yes': name, hour = emp_of_month(my_list) # So here we are doing tuple unpacking with what is returned by a function print(f'Employee of the month is {name} and he worked for {hour} hours') else: print('Thanks for entering the details but you choose to discontinue') # Notice that we did tuple unpacking here inside the function definition as well as while calling it. # but during calling function, if you are not sure how many values does function returns, then its always a better # option to store the function value first into single variable and then explore that first.
true
4b31604397b17724d8a249c691a7828d0c07719c
sagsh018/Python_project
/9_Logical_Operators.py
1,242
4.78125
5
# In This lecture we are going to learn how to chain the comparison operators we have learnt in the previous lecture # We can chain the comparison operator with the help of below listed logical operators # and # or # not # Suppose we want to do two comparisons print(1 < 2) # True print(2 < 3) # True # another way of doing them in same line is print(1 < 2 < 3) # True # Now this is returning true because it is checking whether 1 is less than 2 and also whether 2 is less than 3 print(1 < 2 > 3) # False, as second condition failed # This same thing can be done with logical operator "and" print((1 < 2) and (2 < 3)) # True print((1 < 2) and (2 > 3)) # False # Also we can do the same in case of character and string with all the comparison operators print(('h' == 'h') and (2 == 2)) # Ture # So basically and logical operator follows below concept # T and T = T # T and F = F # F and T = F # F and F = F # or # === print((1 < 2) or (2 < 3)) # True print((1 < 2) or (3 < 2)) # True print((2 < 1) or (2 < 3)) # True print((2 > 3) or (4 < 3)) # False # or follows below rules # T or T = T # T or F = T # F or T = T # F or F = F # not # ==== print(1 == 1) # True print(not 1 == 1) # False # not follows below rules # not T = F # not F = T
true
acb345bad9c7a7be1c51586ca0587931d864b99b
sagsh018/Python_project
/14_List_comprehensions_in_python.py
2,803
4.84375
5
# List comprehensions are unique way of quickly creating list in python # if you find yourself creating the list with for loop and append(). list comprehensions are better choice my_list = [] print(my_list) # [], so we have an empty list for item in range(1, 10): my_list.append(item) print(my_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9] # another example with this method my_list = [] for letter in 'hello': my_list.append(letter) print(f'created list is : {my_list}') # created list is : ['h', 'e', 'l', 'l', 'o'] # So the better way of doing this is with the help of list comprehensions my_string = 'something' my_list = [letter for letter in my_string] print(my_list) # ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g'] # So here we have basically flattened down our for loop. # another example my_list = [x for x in 'word'] print(my_list) # ['w', 'o', 'r', 'd'] my_word = input('Enter the word you want list to be created for : ') print(f'The list created for the word you entered : {[x for x in my_word]}') # Enter the word you want list to be created for : sagar # The list created for the word you entered : ['s', 'a', 'g', 'a', 'r'] # Also lets try to flatten the for loop for our first example my_list = [] print(my_list) # [], so we have an empty list for item in range(1, 10): my_list.append(item) print(my_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9] my_list = [num for num in range(1, 10)] print(my_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9] # we can even perform operations in this method # to print double of numbers in range from 1 to 10 my_list = [num*2 for num in range(1, 10)] print(my_list) # [2, 4, 6, 8, 10, 12, 14, 16, 18] # To print square of numbers in range from 1 to 10 print([num**2 for num in range(1, 10)]) # [1, 4, 9, 16, 25, 36, 49, 64, 81] # To print only even numbers from range 1 to 10 print([num for num in range(1, 10) if num%2 == 0]) # [2, 4, 6, 8] # To print square of even numbers print([num**2 for num in range(1, 10) if num%2 == 0]) # [4, 16, 36, 64] # Suppose we have temperature in Celsius and we want to convert it into Fahrenheit Celsius = [0, 10, 20, 30, 40] fahrenheit = [((9/5)*temp + 32) for temp in Celsius] print(fahrenheit) # [32.0, 50.0, 68.0, 86.0, 104.0] # we can not only do if statements in list comprehensions but we can also do the if and ele both # but this change the order of statement a little bit my_list = [x if x%2 == 0 else 'Odd' for x in range(1, 10)] print(my_list) my_list = [] # Now lets consider the example of nested loops for x in [1, 2, 3]: for y in [10, 100, 1000]: my_list.append(x*y) print(my_list) # [10, 100, 1000, 20, 200, 2000, 30, 300, 3000] # Lets try to do this with list comprehension my_list = [x*y for x in [1, 2, 3] for y in [10, 100, 1000]] print(my_list) [10, 100, 1000, 20, 200, 2000, 30, 300, 3000]
true
2e97e48539eaae2d4a43533487c5d263baa1e587
sagsh018/Python_project
/12_While_loop_in_python.py
1,948
4.4375
4
# While loop will continue to execute a block of code while some condition remains true # Syntax # =============================== # while some_boolean_condition: # do something # =============================== # We can also combine while statement with the else statement # =============================== # while some_boolean_condition: # do something # else: # So something else # =============================== # example # ======= x = 0 while x < 5: print(f'Value of x {x+1}th time is : {x}') x += 1 else: print(f'{x+1}th time x is not less than 5') # Value of x 1th time is : 0 # Value of x 2th time is : 1 # Value of x 3th time is : 2 # Value of x 4th time is : 3 # Value of x 5th time is : 4 # 6th time x is not less than 5 # break, continue, pass # ====================== # break : breaks out of the current closest enclosing loop # continue : Goes to the top of the closest enclosing loop # pass: does absolutely nothing # pass # ==== new_list = [1, 2, 3] for item in new_list: pass # This will do nothing but it will not throw error because python do expect us to write something and we can't leave # that blank. So this is a use of pass keyword. We often use it while declaring the functions. when we don't want # to define whats goes inside the function immediately # continue # ========= for letter in 'sammy': print(letter) # s # a # m # m # y # Suppose we don't want to print letter a in sammy, then we will use continue here for letter in 'Sammy': if letter == 'a': continue print(letter) # S # m # m # y # break # ====== # suppose we want to print letters of word sammy until letter a occurs for letter in 'sammy': if letter == 'a': break print(letter) # s # break is more useful with while loop. lets see the example of while loop along with break statement x = 0 while x < 5: if x == 2: break print(x) x += 1 # 0 # 1
true
b67420e180277e8abd7908d95a410427a30373ea
homanate/python-projects
/fibonacci.py
711
4.21875
4
'''Function to return the first 1000 values of the fibonacci sequence using memoization''' fibonacci_cache = {} def fibonacci(n): # check input is a positive int if type(n) != int: raise TypeError("n must be a positive int") if n < 1: raise ValueError("n must be a positive int") # check for cached value, if found then return if n in fibonacci_cache: return fibonacci_cache[n] # compute n if n == 1: value = 1 elif n == 2: value = 2 elif n > 2: value = fibonacci(n-1) + fibonacci(n-2) # cache value and return fibonacci_cache[n] = value return value for n in range(1, 1001): print(n, ":", fibonacci(n))
true
a1c4e25c5608a1097f71d22db51a3b51aabcafaa
RadchenkoVlada/tasks_book
/python_for_everybody/task9_2.py
1,098
4.3125
4
""" Exercise 2: Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with “From”, then look for the third word and keep a running count of each of the days of the week. At the end of the program print out the contents of your dictionary (order does not matter). Sample Line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Sample Execution: python dow.py Enter a file name: mbox.txt {'Fri': 20, 'Thu': 6, 'Sat': 1} """ def find_a_day(filename): with open(filename, "r") as file: dictionary = {} # firstNlines = file.readlines()[0:100] for line in file: if line[:5] == "From ": word_list = line.split() day = word_list[2] if day not in dictionary: dictionary[day] = dictionary.get(day, 1) else: dictionary[day] = dictionary.get(day) + 1 return dictionary if __name__ == '__main__': # filename = input("Enter a file name: ") print(find_a_day("mbox.txt"))
true
804ec370c29b1d0cafdae1cf1a2615abf4b3f766
RadchenkoVlada/tasks_book
/python_for_everybody/task10_2.py
1,521
4.3125
4
""" Exercise 2: This program counts the distribution of the hour of the day for each of the messages. You can pull the hour from the “From” line by finding the time string and then splitting that string into parts using the colon character. Once you have accumulated the counts for each hour, print out the counts, one per line, sorted by hour as shown below. Sample Execution: python timeofday.py Enter a file name: mbox.txt 04 3 06 1 07 1 09 2 10 3 11 6 14 1 15 2 16 4 17 2 18 1 19 1 """ def time_of_day(filename): with open(filename, "r") as file: dictionary = {} for line in file: if line[:5] == "From ": word_list = line.split() exact_time = word_list[5] # s.find(), s.rfind(). They return the indices of the first and last occurrence of the required # substring. # If the substring is not found, the method returns the value -1. hour = exact_time[:exact_time.find(":")] if hour not in dictionary: dictionary[hour] = dictionary.get(hour, 1) else: dictionary[hour] = dictionary.get(hour) + 1 t = list() for key, val in dictionary.items(): t.append((key, val)) t.sort() for key, val in t: print(key, val) if __name__ == '__main__': filename = input("Enter a file name: ") print(time_of_day(filename)) # print(time_of_day("data/mbox.txt"))
true
86de60fccaa7393daa94e67f1e0e8c25e59f8e30
RadchenkoVlada/tasks_book
/python_for_everybody/task7_2.py
2,907
4.46875
4
""" Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form: X-DSPAM-Confidence:0.8475 When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence. Enter the file name: mbox.txt Average spam confidence: 0.894128046745 Enter the file name: mbox.txt Average spam confidence: 0.750718518519 Test your file on the mbox.txt and mbox_long.txt files. Exercise 3: Sometimes when programmers get bored or want to have a bit of fun, they add a harmless Easter Egg to their program Modify the program that prompts the user for the file name so that it prints a funny message when the user types in the exact file name “na na boo boo”. The program should behave normally for all other files which exist and don’t exist. Here is a sample execution of the program: python egg.py Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt python egg.py Enter the file name: missing.tyxt File cannot be opened: missing.tyxt python egg.py Enter the file name: na na boo boo NA NA BOO BOO TO YOU - You have been punk'd! """ def opening_file(name_file): # how if name_file == "na na boo boo": # a harmless Easter Egg print("NA NA BOO BOO TO YOU - You have been punk'd!") try: with open(name_file, "r") as file: count = 0 total_sum = 0 average = 0 for line in file: line = line.rstrip() if not line.startswith('X-DSPAM-Confidence:'): continue atpos = line.find(":") after_pos = line[atpos + 1:] number = float(after_pos) # can be this situation X-DSPAM-Confidence: 0.8475jj total_sum += number count += 1 average = total_sum / count print("There is a match string", number) print("Average spam confidence: ", average) except FileNotFoundError: print('File {0}'.format(name_file), "cannot be opened") except ValueError: print("Incorrect float value.") except Exception as exception: print('File {0}'.format(name_file)) print(exception) if __name__ == '__main__': # name_file = input("Enter a file name: ") opening_file("mbox.txt") """ Correct answer: Enter the file name: mbox.txt Average spam confidence: 0.7507185185185187 ANSWER IN MY PROGRAM Average spam confidence: 0.750718518519 ANSWER IN BOOK Enter the file name: mbox_long.txt Average spam confidence: 0.894128046745 ANSWER IN BOOK Average spam confidence: 0.8941280467445736 ANSWER IN MY PROGRAM """
true
e164e4a1b53cdc17bb06540817987c815e4610c0
Jasonzyy9/PythonTraining
/weight converter.py
336
4.15625
4
print("What's your weight? ") weight = int(input("Weight: ")) select = input("(L)bs or (K)g: ") if select.upper() == "L": weight = weight * 0.45 print(f"You are {weight} kilograms") elif select.upper() == "K": weight = weight * 2.2 print(f"You are {weight} pounds") else: print("Please type a right unit!")
false
10ec91dd7721225830f0ce8d658188b389cc0b03
Arverkos/GeekBrains-Homeprojects
/Lesson06/Lesson06.Task04.py
2,262
4.15625
4
class Car: def __init__(self, speed, colour, name, is_police): self.speed = speed self.colour = colour self.name = name self.is_police = is_police def go(self): print(f'Машина {self.name} {self.colour} поехала') def stop(self): print(f'Машина {self.name} {self.colour} остановилась') def turn(self, direction): print(f'Машина {self.name} {self.colour} повернула {direction}') def show_speed(self): print(f'Скорость машины {self.name} {self.colour} составляет {self.speed}') class TownCar(Car): def show_speed(self): if self.speed <= 60: print(f'Скорость машины {self.name} {self.colour} составляет {self.speed}') else: print(f'Скорость машины {self.name} {self.colour} превышена на {self.speed - 60} - сбавьте скорость!') class SportCar(Car): pass class WorkCar(Car): def show_speed(self): if self.speed <= 40: print(f'Скорость машины {self.name} {self.colour} составляет {self.speed}') else: print(f'Скорость машины {self.name} {self.colour} превышена на {self.speed - 40} - сбавьте скорость!') class PoliceCar(Car): pass car_1 = TownCar(50, 'Black', 'Kia', False) car_2 = SportCar(150, 'Red', 'Ferrari', False) car_3 = WorkCar(50, 'Yellow', 'Fiat', False) car_4 = PoliceCar(80, 'White-Blue', 'Ford', True) print(f' Машина {car_1.name} {car_1.colour} Скорость {car_1.speed} Полицейская? - {car_1.is_police}') print(f' Машина {car_2.name} {car_2.colour} Скорость {car_2.speed} Полицейская? - {car_2.is_police}') print(f' Машина {car_3.name} {car_3.colour} Скорость {car_3.speed} Полицейская? - {car_3.is_police}') print(f' Машина {car_4.name} {car_4.colour} Скорость {car_4.speed} Полицейская? - {car_4.is_police}') car_1.turn('Налево') car_2.stop() car_3.go() car_4.show_speed() car_3.show_speed()
false
342ec86d210a77162b489c42d788703070c8a694
nd955/CodingPractice
/HighestProductOfThree.py
858
4.15625
4
import math def get_highest_product_of_three(input_integers): highest_product_of_3 = 0 highest_product_of_2 = 0 highest_number = 0 lowest_product_of_2 = 0 lowest_number = 0 for i in range(len(input_integers)): highest_product_of_3 = max(highest_product_of_3, highest_product_of_2 * input_integers[i]) highest_product_of_2 = max(highest_product_of_2, highest_number * input_integers[i]) highest_number = max(highest_number, input_integers[i]) lowest_product_of_2 = max(lowest_product_of_2, lowest_number * input_integers[i]) lowest_number = min(lowest_number, input_integers[i]) highest_product_of_3 = max(lowest_product_of_2 * highest_number, highest_product_of_3) return highest_product_of_3 print(get_highest_product_of_three([1,1,-8,1,10,2,5,6,-7,-7]))
true
486501ac24a31929fb1f621562a4f610de01c13c
green-fox-academy/fehersanyi
/python/dataStructures/l3.py
533
4.125
4
# Create a function called 'create_new_verbs()' which takes a list of verbs and a string as parameters # The string shouldf be a preverb # The function appends every verb to the preverb and returns the list of the new verbs verbs = ["megy", "ver", "kapcsol", "rak", "nez"] preverb = "be" def create_new_verbs(preverb, verbs): new_list = [] for words in verbs: new_list.append(preverb + words) return new_list print(create_new_verbs(preverb, verbs)) # The output should be: "bemegy", "bever", "bekapcsol", "berak", "benez"
true
87fbe9b832ecf321d9514a2f769d52a02ca17765
jessymiyoshi/401-exercicios
/python.py
1,033
4.15625
4
# #PROGRAMA QUE CALCULA A MÉDIA n1 = int(input("Digite a sua N1: ")) n2 = int(input("Digite a sua N2: ")) n3 = int(input("Digite a sua N3: ")) n4 = int(input("Digite a sua N4: ")) media = (n1+n2+n3+n4)/4 print("Sua média é {}" .format(media)) # #PROGRAMA ESTATISTICA DE LETRA frase = input("Digite uma frase: ") letra = input("Digite uma letra: ") procura = frase.count(letra) print(procura) #PROGRAMA MEDIA E ESTATISTICA qutd = int(input("Digite a quantidade de notas que você tem: ")) soma = 0 for i in range(qutd): notas = int(input("Digite uma nota: ")) soma += notas media = soma/qutd print(media) #PROGRAMA QUE MOSTRA TUDO numero1 = float(input("Digite o primeiro número: ")) numero2 = float(input("Digite o segundo número: ")) soma = numero1+numero2 subtracao = numero1-numero2 multiplicacao = numero1*numero2 divisao = numero1/numero2 resultado = (input("O resultado da soma é {}, subtração {}, multiplicação {}, divisão {}." .format(soma, subtracao, multiplicacao, divisao))) print(resultado)
false
49b5e88a53fd9e1d0965ec3e72931135e06ab8d5
Allien01/PY4E
/02-data-structure/files/01.py
255
4.15625
4
fname = input("Enter the name of the file: ") try: fhandle = open(fname) except: print("This is not a existing file!") exit() for line in fhandle: # imprime cada linha do arquivo em maiúsculo line = line.rstrip() print(line.upper())
false
be90e83b67be93177d2aa6797044fb6504b28473
olegrok/TrackUIAutomatization
/lesson1/6.py
539
4.28125
4
#!/usr/bin/python3 # Написать программу, определяющую является ли фраза палиндромом или нет. # Входные данные содержат строку. # Ответ должен содержать: "полиндром" если это палиндром или "не полиндром" если нет. import re str1 = str(input()) str1 = re.sub(r'\W', '', str1).lower() if str1 == str1[::-1]: print("Полиндром") else: print("Не полиндром")
false
5ec90b5061479057ab0be74166f7662897056973
KyeCook/PythonStudyMaterials
/LyndaStudy/LearningPython/Chapter 3/time_delta_objects.py
1,347
4.34375
4
###### # # # Introduction to time delta objects and how to use them # # ###### from datetime import date from datetime import datetime from datetime import time from datetime import timedelta def main(): # Constructs basic time delta and prints print(timedelta(days=365, hours=5, minutes=1)) # print date print("Date now is " + str(datetime.now())) # print date in one year by adding 365days on with timedelta print("Date in one year will be " + str(datetime.now() + timedelta(days=365))) # Use timedelta that has more than one argument print("Date in two weeks and 3 days will be : " + str(datetime.now() + timedelta(weeks=2, days=3))) # Calculate time one week ago using timedelta and format t = datetime.now() - timedelta(weeks=1) s = t.strftime("%A %B %d, %Y") print("One week ago it was " + s) # ## Calculate How long it is until April fools day today = date.today() afd = date(today.year, 4, 1) # Compare dates to see if it has already been. # Use replace functin if it has if(afd < today): print("April fools day has already passed %d days ago" % ((today-afd).days)) afd = afd.replace(year=today.year+1) time_to_afd = abs(afd - today) print(time_to_afd.days, " days until next April Fools Day") if __name__ == '__main__': main()
true
48cf608faab61973d1a3660ca5e466728f0db0f9
KyeCook/PythonStudyMaterials
/LyndaStudy/LearningPython/Chapter 2/loops.py
820
4.28125
4
######## # # # Introduction to loops # # ######## def main(): x = 0 # Defining a while loop while (x < 5): print(x) x =+ 1 # Defining a for loop for x in range(5,10): print(x) # Looping over a collection (array, list etc.) days = ["mon", "tues", "wed", "thurs", "fri", "sat", "sun"] for d in days: print(d) # Using break and continue in loops for x in range(5, 10): if(x==7): break if(x % 2 == 0): continue print(x) # Using enumerate() to get index days = ["mon", "tues", "wed", "thurs", "fri", "sat", "sun"] for i, d in enumerate(days): print(i, d) if __name__ == "__main__": main()
false
c73bbcb19f8fefe0c8ac9a03af30f84878398d34
rafianathallah/modularizationsforum
/modnumber10.py
395
4.125
4
def pangramchecker(str): alphabet = "abcdefghijklmnopqrstuvwxyz" for characters in alphabet: if characters not in str.lower(): return False return True sentence = str(input("Enter a sentence: ")) if(pangramchecker(sentence) == True): print("This sentence is a pangram.") else: print("This sentence is not a pangram.")
true
b2681199c636f8d3cf67f2e3211100e512f951d8
CamiloYate09/Python_Django
/FACTORIAL.py
334
4.21875
4
# factorial = int(input("Ingresa Un numero para saber su factorial")) # # acum = 1 # # while factorial>0: # acum *=factorial # factorial = factorial-1 # # # # print('%i' % acum) #FACTORIAL DE FORMA RECURSIVA def factorial(x): if (x==0): return 1 else: return x * factorial(x-1) print(factorial(5))
false
e9c023d8afffb2b4d28954c7bc2ff4311c3e1a94
Ryan149/Bioinformatics-Repository
/bioinformatics/coding/month.py
705
4.15625
4
name={} name[0]="January" name[1]="February" name[2]="March" name[3]="April" name[4]="May" name[5]="June" name[6]="July" name[7]="August" name[8]="September" name[9]="October" name[10]="November" name[11]="December" def daysInMonth(month): days = 30 if (month < 7): if (month % 2 == 0): days = 31 if (month == 1): days = 28 else: if (month % 2 == 1): days = 31 return days daysInYear=0 for i in range(0,12): print "There are",daysInMonth(i),"days in",name[i] daysInYear=daysInYear+daysInMonth(i) print "There are",daysInYear,"days in a non-leap year"
true
87e82f31d1624d627eed4c122307fc3762165e75
EdBali/Python-Datetime-module
/dates.py
1,626
4.3125
4
import datetime import pytz #-----------------SUMMARRY OF DATETIME module------------ #-------------The datetime module has 4 classes: # datetime.date ---(year,month,date) # datetime.time ---(hour,minute,second,microsecond) # datetime.datetime ---(year,month,date,hour,minute,second,microsecond) # datetime.timedelta ---this deals with duration in days,month,years,hour,minute,second,microsecond #printing the current date today = datetime.date.today() print(today) #printing my birthday birthday = datetime.date(2000,12,18) print(birthday) #calculating number of days since birth days_since_birth = (today - birthday).days print(days_since_birth) #Adding and subtracting days using timedelta ten_days = datetime.timedelta(days = 10) print(today + ten_days) #How to get specifc day,month,weekday print(datetime.date.today().month) # print(datetime.date.today().day) # print(datetime.date.today().weekday) #Adding 10hours to current time ten_hours = datetime.timedelta(hours = 10) print(datetime.datetime.now() + ten_hours) #Working with time zones..You have to pip install "pytz" module, then import it datetime_day = datetime.datetime.now(tz = pytz.UTC) datetime_pacific = datetime_day.astimezone(pytz.timezone('US/Pacific')) print(datetime_pacific) #Printing list of available timezones # for tz in pytz.all_timezones: # print(tz) #String Formatting Dates print(datetime_pacific.strftime('%B %d, %Y')) #Turning a normal String date to a datetime object datetime_object = datetime.datetime.strptime('March 09, 2010','%B %d, %Y') print(datetime_object) #NB: look for "MAYA" for easier manipulation of dates
true
a1d69d9a43163882862a5460605a20086fc8f334
marcemq/csdrill
/strings/substrInStr.py
665
4.125
4
# Check if a substring characters are contained in another string # Example # INPUT: T = ABCa, S = BDAECAa # OUTPUT: ABCa IN BDAECAa import sys from utils import _setArgs def checkSubstrInStr(substr, mystr): frec = {key:0 for key in substr} for key in substr: frec[key] += 1 counter = len(frec) for si in mystr: if si in frec: frec[si] -= 1 if frec[si] == 0: counter -= 1 if counter == 0: print("{} IN {}".format(substr, mystr)) else: print("{} NOT IN {}".format(substr, mystr)) if __name__ == "__main__": args = _setArgs() checkSubstrInStr(args.T, args.S)
true
e1010fcef38081827ce65150ea93eb922d87e2be
kemoelamorim/Fundamentos_Python
/exercicios/Ex018.py
528
4.125
4
""" Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. """ from math import sin, cos, tan, radians # lendo ângulo angulo = int(input("Digite o ângulo: ")) # valores de seno e cosseno seno = sin(radians(angulo)) print("O ângulo de %d tem o seno de %.2f" %(angulo, seno)) cosseno = cos(radians(angulo)) print("O ângulo de %d tem o seno de %.2f" %(angulo, cosseno)) tangente = tan(radians(angulo)) print("O ângulo de %d tem o seno de %.2f" %(angulo, tangente))
false
4fe669ddce4a2ec9e5df71d9c408a37b4ecc65f4
kemoelamorim/Fundamentos_Python
/Tipos_primitivos/1-Strings/1.0-tipos_primitivos.py
2,007
4.3125
4
# Variaveis e Tipos nome = 'kemoel' # valor com o tipo string ou 'str' idade = 26 # valor com o tipo inteiro ou 'int' salario = 4.728 # valor com o tipo ponto flutuante ou 'float' masculino = True # valor com tipo boleano 'bool' # Função type() mostra o tipo que valor da variável possui print(type(nome)) # tipo string print(type(idade)) # tipo inteiro print(type(salario)) # tipo ponto flutuante print(type(masculino)) # tipo boleano # Criando variáveis vazias inteiro = 0 real = 0.0 texto = "" print(type(inteiro)) print(type(real)) print(type(texto)) # O None é um valor nulo. Não tem tipo e muito menos valor nulo = None print(type(nulo)) """ O caractere de sublinhar (_) pode aparecer em um nome de variável. Muitas vezes é usado em nomes com várias palavras, como seu_nome ou data_de_nascimento. Se você der um nome ilegal a uma variável, recebe um erro de sintaxe: >>>76trombones = 'big parade' (76trombones é ilegal porque começa com um número.) SyntaxError: invalid syntax >>>more@ = 1000000 (more@ é ilegal porque contém um caractere @.) SyntaxError: invalid syntax >>>class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax Mas o que há de errado com class? A questão é que class é uma das palavras-chave do Python. O interpretador usa palavras-chave para reconhecer a estrutura do programa e elas não podem ser usadas como nomes de variável. O Python 3 tem estas palavras-chave: and del from None True as elif global nonlocal try assert else if not while break except import or with class False in pass yield continue finally is raise def for lambda return Você não precisa memorizar essa lista. Na maior parte dos ambientes de desenvolvimento, as palavras-chave são exibidas em uma cor diferente; se você tentar usar uma como nome de variável, vai perceber. """
false
2a3c4c11d5fbcb16d69d2c18ebc3c0ef30d0b352
PsychoPizzaFromMars/exercises
/intparser/intparser.py
1,951
4.40625
4
'''In this kata we want to convert a string into an integer. The strings simply represent the numbers in words. Examples: - "one" => 1 - "twenty" => 20 - "two hundred forty-six" => 246 - "seven hundred eighty-three thousand nine hundred and nineteen" => 783919 Additional Notes: - The minimum number is "zero" (inclusively) - The maximum number, which must be supported is 1 million (inclusively) - The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not - All tested numbers are valid, you don't need to validate them ''' def parse_int(string): target_number = 0 cur_number = 0 num_dict = { 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90, 'hundred': 100, 'thousand': 1000, 'million': 1000000, } string = string.replace('-', ' ').replace(' and ', ' ').split() for word in string: if word == 'thousand' or word == 'million': cur_number *= num_dict[word] target_number += cur_number cur_number = 0 elif word == 'hundred': cur_number *= num_dict[word] elif word == 'and': pass else: cur_number += num_dict[word] target_number += cur_number return target_number if __name__ == "__main__": print(parse_int('seven hundred eighty-three thousand nine hundred and nineteen'))
true
3b1cc3621fdd084d179c4e7a3c8a5b82bb82fa60
fp-computer-programming/cycle-5-labs-p22rlugo
/lab_5-2.py
412
4.28125
4
# Ryan Lugo: RJL 10/27/21 first_string = input("First Word?: ") second_string = input("Second Word?: ") if first_string > second_string: print(first_string + " is bigger than " + second_string) elif first_string < second_string: print(second_string + " is bigger than " + first_string) elif first_string == second_string: print(first_string + " is equal to " + second_string) else: print("Error")
false
80d2008455dc937de197802177241472e75c8f1a
Afnaan-Ahmed/GuessingGame-Python
/guessingGame.py
1,036
4.4375
4
import random #Generate a random number and store it in a variable. secret_number = random.randint(1,10) #Initially, set the guess counter to zero, we can add to it later! guess_count = 0 #set a limit on how many guesses the user can make. guess_limit = 3 print('Guess a number between 1 and 10.') #Do this so the program terminates after the set amount of guesses. while guess_count < guess_limit: guess = int(input('Guess: ')) #Ask for input and increment guess count by 1 so that our program doesn't loop infinately. guess_count += 1 #Define the rules and conditions of the game. if guess == secret_number: print('Yay, you guessed right!, You Won!') break #Break it so it doesn't continue after the user wins the game. elif guess < secret_number: print("Your guess is too low.") elif guess > secret_number: print('Your guess is too high.') else: print("Invalid input! Terminating the program.") else: print('You hit the guess limit! You lose.')
true
14fb59b01f99399e6c623d2f84ae9a2e357fb6ba
sourabh06986/devopsprac
/pythonexp/ec2-user/script3.py
317
4.28125
4
#!/usr/bin/python users = ["user1","user2","user3"] print (users[0]) #Accessing last element print (users[len(users)-1]) print (users[-1]) print (users[-2]) users.append("peter") print users print users[-1] + " " + users[-2] #insert element at specific index users.insert(1,"marry") users.remove("user1") print users
false
5dbb4db96d384b13f027ca6adba424dae8f8b7a0
vishnupsingh523/python-learning-programs
/gratestofThree.py
543
4.375
4
# this program is to find the greatest of three numbers: def maxofThree(): # taking the input of three numbers x = int(input("A : ")); y = int(input("B : ")); z = int(input("C : ")); #performing the conditions here for finding the greatest if x>y: if x>z: print(x," is the greatest") else: print(z," is the greatest") elif y>z: print(y, " is the greatest") else: print(z, " is the gretest") # calling the maxofThree function here: maxofThree()
true
4db1862dd0c6508368c515de5ebedc672ae1f5e5
klaus2015/py_base
/剑指offer算法/练习.py
1,340
4.1875
4
'''给定一个只包括 '(',')','{','}','[',']' ,'<','>' 的字符串,判断字符串是否有效。 有效字符串需满足:  左括号必须用相同类型的右括号闭合。  左括号必须以正确的顺序闭合。  注意空字符串可被认为是有效字符串。  示例 1: 输入: "()" 输出: true  示例 2: 输入: "()[]{}<>" 输出: true  示例 3:输入: "(<{)]}" 输出: false  示例 4: 输入: "([{ }]" 输出: false  示例 5:输入: "(<{[()]}>)" 输出: true  ''' class QueueError(Exception): pass class Node: def __init__(self, val,next=None): self.val = val self.next = next class LQueue: def __init__(self): self.front = self.rear = Node(None) def is_empty(self): return self.front == self.rear def enqueue(self, val): node = Node(val) self.rear.next = node self.rear = self.rear.next def dequeue(self): if self.front == self.rear: raise QueueError("Queue is empty") # 认为front指向的节点已经出队 self.front = self.front.next return self.front.val if __name__ == "__main__": sq = LQueue() lq = LQueue() lq.enqueue(10) lq.enqueue(20) lq.enqueue(30) print(lq.dequeue()) print(lq.dequeue()) print(lq.dequeue())
false
cdd383d3959b8ea02086267fe51163a1f79e7aa6
klaus2015/py_base
/code/day04/r6.py
252
4.15625
4
""" 在控制台中获取一个整数作为边长. """ length = int(input("请输入边长: ")) string = "*" space = ' ' print(string * length-2) for item in range(length): print(string + space * (length - 2) + string) print(string * length)
false
3349311b8347f6eac17c3dfb9b87da5816f57e0c
eestey/PRG105-16.4-Using-a-function-instead-of-a-modifier
/16.4 Using a function instead of a modifier.py
945
4.1875
4
import copy class Time(object): """ represents the time of day. attributes: hour, minute, second""" time = Time() time.hour = 8 time.minute = 25 time.second = 30 def increment(time, seconds): print ("Original time was: %.2d:%.2d:%.2d" % (time.hour, time.minute, time.second)) new_time = copy.deepcopy(time) new_time.second += seconds if new_time.second > 59: quotient, remainder = divmod(new_time.second, 60) new_time.minute += quotient new_time.second = remainder if new_time.minute > 59: quotient, remainder = divmod(new_time.minute, 60) new_time.hour += quotient new_time.minute = remainder if new_time.hour > 12: new_time.hour -= 12 print "Plus %g seconds" % (seconds) print ("New time is: %.2d:%.2d:%.2d" % (new_time.hour, new_time.minute, new_time.second)) increment(time, 234)
true
302bee99dec0d511bda305ec8ba4bdc6fa028138
Rossnkama/AdaLesson
/linear-regression.py
1,181
4.25
4
# Importing our libraries import numpy as np import matplotlib.pyplot as plt # Our datasets x_data = [1.0, 2.0, 3.0] y_data = [2.0, 4.0, 6.0] # Forward propagation in our computational graph def feed_forward(x): return x * w # Loss function def calculate_loss(x, y): return (feed_forward(x) - y)**2 # To plot an error graph later all_weights = [] all_mses = [] # Mean squared errors # To loop though floats for w in np.arange(0.0, 4.1, 0.1): print('W=', w) # Show the weight sum_of_all_loss = 0 for x, y in zip(x_data, y_data): hypothesis_x = feed_forward(x) # This is our predicted y loss = calculate_loss(x, y) sum_of_all_loss += loss print("x:", x) print("y:", y) print("Our hypothesis of x (y):", hypothesis_x) print("Our loss/error squared for this weight {}:".format(w), loss) print("") print("MSE:", loss/3); print("") print("-------------------------\n") all_weights.append(w) all_mses.append(loss/3) # Plotting graph of how weights effect the loss plt.title("Loss vs Weights") plt.plot(all_weights, all_mses) plt.ylabel('Loss') plt.xlabel('Weights') plt.show()
true
26003c0363ef59d0a28dbc9e3ba40b835c803f09
D4r7h-V4d3R/Ornekler
/class1,__init__,self.py
1,115
4.125
4
#normal OOP Programmlama tarzı (basit programlama) #uninit un self class work: pass emplo1 = work() emplo1.ad = "Hasan" emplo1.soyad = "Kılıc" emplo1.maas = "3100" emplo2 = work() emplo2.ad = "Kemal" emplo2.soyad = "Ok" emplo2.maas = "2300" print(emplo1) print(emplo1.ad,emplo1.soyad) #With init,self; #su anki kesfime gore __init__ kullanıca calısanın bilgilerine sadece calıs. deyince ulasılabilir #ama def fonksiyonu sorun cıkarmaya daha yatkındır calıs.fullname() diye __init__ de ise calıs.fullname #denilmesi yeterlidir.. class worke: def __init__(self,ad,soyad,maas): self.ad = ad self.soyad = soyad self.maas = maas self.mail = self.ad+self.soyad+"@corp.com" def fullname(self): return "Ad :{}, Soyad :{}".format(self.ad,self.soyad) def email(): print(self.ad+self.soyad+"@corp.com") calıs1 = worke("Hasan","Kılıc",3100) calıs2 = worke("Kemal","Ok",2300) print(calıs1) print(calıs1.ad,calıs1.soyad) print(calıs1.fullname()) print(calıs2.mail) print(calıs1.mail) #hold to line
false
9621fb0236eaf16068f246c7bc199679c51c24d2
Snakanter/FunStuff
/rps.py
1,832
4.1875
4
#!/usr/bin/env python3 """ File: rps.py Name: A rock-paper-scissors game against the CPU Concepts covered: Random, IO, if/else, printing """ import random import sys import os def main(): # Code here print("READY FOR A GAME OF ROCK, PAPER, SCISSORS!?") PlayerChoice = input("Choose between options by typing first letter. (R = Rock. P = Paper. S = Scissors.) ") while ( PlayerChoice != "R" and PlayerChoice != "S" and PlayerChoice != "P" ): PlayerChoice = input("Choose between options by typing first letter. (R = Rock. P = Paper. S = Scissors.) ") choice = ai_guess(PlayerChoice) checkWin(PlayerChoice, choice) def ai_guess(PlayerChoice): # Code here #1 = rock 2 = paper 3 = scissors choice = random.randint(1,3) return choice def checkWin(PlayerChoice, choice): # Code here if (PlayerChoice == "R") and (choice == 1): print("It's a tie!") elif (PlayerChoice == "R") and (choice == 2): print("You lose!") elif (PlayerChoice == "R") and (choice == 3): print("You win!") elif (PlayerChoice) == ("P") and (choice) == (1): print("You win!") elif (PlayerChoice) == ("P") and (choice) == (2): print("It's a tie!") elif (PlayerChoice) == ("P") and (choice) == (3): print("You lose!") elif (PlayerChoice) == ("S") and (choice) == (1): print('You lose!') elif (PlayerChoice) == ("S") and (choice) == (2): print('You win!') elif (PlayerChoice) == ("S") and (choice) == (3): print("It's a tie!") else: print("") if __name__ == "__main__": main() while True: awnser = input("Would you like to try again?") if awnser == "Yes": os.system("cls") main() else: break
true
52a19ec7a20ac94d87dd8d26a9492df110792804
hsqStephenZhang/Fluent-python
/对象引用-可变性-垃圾回收/8.4函数的参数作为引用时2.py
2,010
4.375
4
""" 不要使用可变类型作为函数的参数的默认值 """ class HauntedBus(object): def __init__(self, passengers=[]): # python会提醒,不要使用mutable value self.passengers = passengers def pick(self, name): self.passengers.append(name) def drop(self, name): try: self.passengers.remove(name) except ValueError: print("student not in the bus") class TwilightBus(object): def __init__(self, passengers=None): # python会提醒,不要使用mutable value if passengers is None: self.passengers = [] else: self.passengers = list(passengers) def pick(self, name): self.passengers.append(name) def drop(self, name): try: self.passengers.remove(name) except ValueError: print("student not in the bus") def show1(): bus1 = HauntedBus(['Alice', 'Bill']) bus1.pick('charlie') bus1.drop("Alice") bus2 = HauntedBus() bus2.pick('Carrie') bus3 = HauntedBus() print(bus3.passengers) bus3.pick('Dave') print(bus2.passengers) print(bus2.passengers is bus3.passengers) """ 这里出现了灵异事件:bus3中的乘客出现在了bus2中,bus2中的乘客出现在了bus3中 这是因为没有指定初始乘客的bus会共享一个乘客列表 默认值是函数对象的属性,如果其是可变对象,则修改了之后对之后的所有的初始化默认值都会影响 """ def show2(): team = list("abcde") bus = TwilightBus(team) """ 这里TwilightBus中的passengers共享了team这个list,应当使用team的副本 也就是将self.passengers=passengers 修改为 self.passengers=list(passengers) 这样该类中操作的就是team的副本,而其中的元素又是不可变的类型,所以不会对原参数影响 """ bus.drop('a') bus.drop('b') print(team) if __name__ == '__main__': # show1() show2()
true
baa67284aac469155cfd13d9a5b9a5a2d465fbb5
hsqStephenZhang/Fluent-python
/接口-从协议到抽象基类/11.2Python喜欢序列.py
592
4.1875
4
""" Python尽量支持基本协议 对于一个序列来说,协议要求其实现__getitem__,__contains__,__iter__,__reversed__ index,count的方法 但是,鉴于序列的重要性,在类没有实现__contains__和__iter__方法的时候,只需要定义了 __getitem__方法,也可以实现in,和迭代运算符 """ class Func(object): def __init__(self): self.data = range(0,20,2) def __getitem__(self, item): return self.data[item] if __name__ == '__main__': func=Func() print(1 in func.data) for i in func.data: print(i,end=" ")
false
7cc3efabd755c0aba8f2e650dfcf5a043b89b5c1
baki6983/Python-Basics-to-Advanced
/Collections/Tuple.py
328
4.46875
4
#tuples are ordered and unchangable fruitsTuples=("apple","banana","cherry") print(fruitsTuples) print(fruitsTuples[1]) # if you try to assign value to fruitsTuples[1] , it will change because its Unchangeable # With DEL method you can completely List , but you cant item in the list for i in fruitsTuples: print(i)
true
6705d4095c282200d0c3f2ca1c7edfb15cdc7009
akshayreddy/yahtzee
/yahtzee.py
2,427
4.25
4
''' .) Programs creats a list of dices .) ProbailityInfo is used to keep track of the positions of dices which will be used to re rolled in future .) probability contais the list of probanilities ''' from decimal import Decimal from random import randint import sys j,k=0,0 dices,ProbabilityInfo,probaility=[],[],[] for i in range(3): dices.append(int(sys.argv[i+1])) def roll_one(x): return (6-x)/float(6) def roll_two(x,y): return ((6-x)/float(6))*((6-y)/float(6)) def roll_three(x,y,z): return (6-x)/float(6)*(6-y)/float(6)*(6-z)/float(6) if dices[0]==dices[1]==dices[2]: print "Its a yahtzee!!\nNo dice needs to be re-rolled\nScore:25" exit() else: for i in range(3): if dices[i]==dices[(i+1)%3]: #If two dices have same value k=1 ProbabilityInfo.append([(i+2)%3]) probaility.append(roll_one(dices[(i+2)%3])) ProbabilityInfo.append([(i+1)%3,(i+2)%3]) probaility.append(roll_two(dices[(i+1)%3],dices[(i+2)%3])) ProbabilityInfo.append([i,(i+1)%3]) probaility.append(roll_two(dices[i],dices[(i+1)%3])) ProbabilityInfo.append([i,(i+1)%3,(i+2)%3]) probaility.append(roll_three(dices[i],dices[(i+1)%3],dices[(i+2)%3])) if k!=1: for i in range(7): if i<3: ProbabilityInfo.append([i]) probaility.append(roll_one(dices[(i)])) elif i<6: ProbabilityInfo.append([j,(j+1)%3]) probaility.append(roll_two(dices[j],dices[(j+1)%3])) j=j+1 else: ProbabilityInfo.append([0,1,2]) probaility.append(roll_three(dices[0],dices[1],dices[2])) for i in range(len(ProbabilityInfo)): print "Position=%s Probability=%f"%(ProbabilityInfo[i],probaility[i]) MaxProbablityPosition=probaility.index(max(probaility)) if max(probaility)>0.33333333: # Setting a Threshold for probability print "\n%d dice can be re-rolled\n"%len(ProbabilityInfo[MaxProbablityPosition]) for i in ProbabilityInfo[MaxProbablityPosition]: print "dice number %d" % (i+1) for i in ProbabilityInfo[MaxProbablityPosition]: dices[i]=randint(0,6) print "New Roll:%s"%(dices) if dices[0]==dices[1]==dices[2]: print "Its a yahtzee!!\nNo dice needs to be rolled\nScore:25" else: print "Score:%d" % (dices[0]+dices[1]+dices[2]) else: print "\nRe rolling not required, less gain probability\n" print "Score:%d" % (dices[0]+dices[1]+dices[2])
true
50a19615d64c0c8e015d625211e2404dd322b0f6
defytheflow/cs50
/week6/caesar.py
1,223
4.375
4
# This program encrypts the given message by a given key using Caesar Cipher import sys def main(): check_args() key = int(sys.argv[1]) % 26 message = input("plaintext: ") encrypt_caesar(message, key) def check_args() -> bool: """ Checks provided command lines arguments. """ if len(sys.argv) == 2: key = sys.argv[1] if not key.isdigit(): print("Usage caesar.py k") sys.exit(1) else: print("Usage caesar.py k") sys.exit(1) def encrypt_caesar(message: str, k: int) -> None: """ Encrypts te message using Caesar Cipher. """ encr_message = "" for ch in message: if 64 < ord(ch) and ord(ch) < 91: if 64 < ord(ch) + k and ord(ch) + k < 91: encr_message += chr(ord(ch) + k) else: encr_message += chr(ord(ch) + k - 26) elif 96 < ord(ch) and ord(ch) < 123: if 96 < ord(ch) + k and ord(ch) + k < 123: encr_message += chr(ord(ch) + k) else: encr_message += chr(ord(ch) + k - 26) else: encr_message += ch print("ciphertext:", encr_message) if __name__ == "__main__": main()
false
cc35a2f8ef7f5c1c81d6d491abdfb6263c632769
denze11/BasicsPython_video
/theme_4/13_why_range.py
604
4.21875
4
# Когда нам может помочь range winners = ['Max', 'Leo', 'Kate'] # Простой перебор for winner in winners: print(winner) # Что делать если нам нужно вывести место победителя? # использовать while? # или есть способ лучше? # вывести нечетные цифры от 1 до 5 numbers = [1, 3, 5] for number in numbers: print(number) # как это сделать если цифр будет 100? 1000? # использовать while? # или есть способ лучше?
false
10be9e035cd80484fcb8a5eef1531a9545f9f30b
denze11/BasicsPython_video
/theme_14/14_copy_list.py
547
4.3125
4
a = [1, 2, 3] # копия с помощью среза b = a[:] b[1] = 200 # список а не изменился print(a) # копия с помощью метода copy b = a.copy() b[1] = 200 # список а не изменился print(a) # Эти способ бы не будут работать если есть вложенные списки a = [1, 2, [1, 2]] b = a[:] b[2][1] = 200 # список а сного меняется print(a) b = a.copy() b[2][1] = 200 # список а снова меняется print(a)
false
d5d129c657c35a21983e77972370f67e146bdfe7
NatheZIm/nguyensontung-homework-c4e14
/Day4/ex3.py
287
4.25
4
isPrime=0 n=int(input("Enter Number to Check: ")) if n == 1 or n == 0: print(n,"Is Not Prime Number ") else: for i in range(1,n+1): if n%i==0: isPrime+=1 if (isPrime==2): print(n,"Is Prime Number") else: print(n,"Is Not Prime Number")
false
1d62f6a708016a46f4ec143529a47ba0fd7fd0a9
MFRoy/pythonchallenges
/python/grade_calculator.py
520
4.1875
4
print("Welcome to average grade calculater ") maths = int(input(" Please imput your Maths mark : ")) physics = int(input(" Please imput your Physics mark : ")) chemistry = int(input(" Please imput your Chemistry mark : ")) average =((maths+physics+chemistry)/3) print ("your percentage is", " ",average,"%") grade= "Fail" if average < 40: grade = "Fail" elif average >= 40 and average <60: grade = "C" elif average >=60 and average <80: grade = "B" else: grade = "A" print("your final grade is",grade)
false
09fd2d4e77c3bb2ce2401f583a567c6351aaf2d7
veryobinna/assessment
/D2_assessment/SOLID/good example/liskov_substitution.py
1,345
4.125
4
''' Objects in a program should be replaceable with instances of their base types without altering the correctness of that program. I.e, subclass should be replaceable with its parent class As we can see in the bad example, where a violation of LSP may lead to an unexpected behaviour of sub-types. In our example, "is-a" relation can not directly applied to `Person` and `Prisoner`. The cause is that these two classes "behave" differently. How to fix it? Maybe a better naming will do the trick: ''' class FreeMan(object): def __init__(self, position): self.position = position def walk_North(self, dist): self.position[1] += dist def walk_East(self, dist): self.position[0] += dist # "is-a" relationship no longer holds since a `Prisoner` is not a `FreeMan`. class Prisoner(object): PRISON_LOCATION = (3, 3) def __init__(self): self.position = type(self).PRISON_LOCATION def main(): prisoner = Prisoner() print "The prisoner trying to walk to north by 10 and east by -3." try: prisoner.walk_North(10) prisoner.walk_East(-3) except: pass print "The location of the prison: {}".format(prisoner.PRISON_LOCATION) print "The current position of the prisoner: {}".format(prisoner.position) if __name__ == "__main__": main()
true
eeb4417e9f419a311fb639aeada768728c113f28
tekichan/teach_kids_python
/lesson5/circle_pattern.py
897
4.34375
4
from turtle import * bgcolor("green") # Define Background Color pencolor("red") # Define the color of Pen, i.e our pattern's color pensize(10) # Define the size of Pen, i.e. the width of our pattern's line radius = 100 # Define the radius of each circle turning_angle = 36 # Define how much the next circle turns away from the previous one. # A counter of totally how much the angle is turned. It starts with zero. total_turned_angle = 0 while total_turned_angle < 360: # While loop, when the total angle is less than 360, i.e a round. circle(radius) # Draw a circle # Turn right after you finish a circle, to prepare the new position of the next circle. right(turning_angle) # Accumulate the turning angle into the counter total_turned_angle = total_turned_angle + turning_angle exitonclick() # Exit when you click the screen
true
15e49688c27e8237138889efa46963ffa4775c91
kenifranz/pylab
/popped.py
309
4.28125
4
# Imagine that the motorcycles in the list are stored in chronological order according to when we owned them. # Write a pythonic program to simulate such a situation. motorcycles = ['honda', 'yamaha','suzuki'] last_owned = motorcycles.pop() print("The last motorcycle I last owned was "+ last_owned.title())
true
17f39a18c96ac3f6a3bb1646da4d01875b1889e6
JaredColon-Rivera/The-Self-Taught-Programmer
/.Chapter-3/Challenge_4.py
233
4.375
4
x = 10 if x <= 10: print("The number is less than or equal to 10!") elif x > 10 and x <= 25: print("The number is greater than equal to 10 but it is less than or equal to 25!") elif x > 25: print("The number is greater than 25!")
true
d6bd643d0da7cfb11fd22a0d0b346171fba82b24
sureshbvn/leetcode
/recursion/subset_sum.py
952
4.25
4
# Count number of subsets the will sum up to given target sum. def subsets(subset, targetSum): # The helper recursive function. Instead of passing a slate(subset), we are # passing the remaining sum that we are interested in. This will reduce the # overall complexity of problem from (2^n)*n to (2^n). def helper(sum, index): # Base condition. Only when we are at a leaf node, the subset is # completely formed. if index == len(subset): # If sum reaches zero, this is equivalent to subset sum. # In the slate world, we will have actual subset at this stage. if sum == 0: return 1 return 0 if sum < 0: return 0 return helper(sum-subset[index], index+1) + helper(sum, index+1) return helper(targetSum, 0) count = subsets([1,2,3,4], 6) print("The total number of subsets with target sum", count)
true
5d0d3522cee1193cb0765c366e7d5d73a583aab2
pravinv1998/python_codeWithH
/newpac/read write file.py
339
4.15625
4
def read_file(filename): ''' 'This function use only for read content from file and display on command line' ''' file_content = open(filename) read_data = file_content.read() file_content.close() return read_data n=read_file("name.txt") print(n) print(read_file.__doc__) # read the content from file
true
bc4906e63fbb7278109151edfd73f7d06cc38630
abalulu9/Sorting-Algorithms
/SelectionSort.py
701
4.125
4
# Implementation of the selection sorting algorithm # Selection sort takes the smallest element of the vector, removes it and adds it to the end of the sorted vector # Takes in a list of numbers and return a sorted list def selectionSort(vector, ascending = True): sortedVector = [] # While there are still elements in the vector while len(vector) > 0: # Find the smallest element in the vector index = 0 for i in range(len(vector)): if (vector[i] < vector[index] and ascending) or (vector[i] > vector[index] and not ascending): index = i # Remove the smallest element and add it to the end of the sorted vector sortedVector.append(vector.pop(index)) return sortedVector
true
2f28f3c4f6c93913345c688e688662eb228879ed
stanislav-shulha/Python-Automate-the-Boring-Stuff
/Chapter 6/printTable.py
997
4.46875
4
#! python3 # printTable.py - Displays the contents of a list of lists of strings in a table format right justified #List containing list of strings #rows are downward #columns are upward tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] #Prints the list containing list containing strings #table is the passed list #numRows is the number of rows in table #numCols is the number of columns in the table def print_Table(table, numRows, numCols): #For loop to get the widths for each column #Widths stored in colWidths max = 0 for list in tableData: for item in list: if len(item) > max: max = len(item) #Code used in a previous program (Chapter 4 - GridPicture) to do the display portion line = '' for r in range(numRows): for c in range(numCols): line += table[c][r].rjust(max) print(line) line = '' #Test case print_Table(tableData, len(tableData[0]), len(tableData))
true
96a3ec7334436703a69c3d4bd396eb3f99ca5bf2
stanislav-shulha/Python-Automate-the-Boring-Stuff
/Chapter 4/CommaList.py
733
4.59375
5
#Sample program to display a list of values in comma separated format #Function to print a given list in a comma separated format #Takes a list to be printed in a comma separated format def comma_List(passedList): #Message to be printed to the console message = '' if len(passedList) == 0: print('Empty List') elif len(passedList) == 1: print(passedList[0]) else: #Loop through the list and add each element except for the last one to the message for i in range(len(passedList) - 1): message += passedList[i] + ', ' message += 'and ' + passedList[-1] print(message) #Testing cases test = ['apples', 'bananas', 'tofu', 'cats'] comma_List(test) test2 = [] comma_List(test2) test3 = ['one'] comma_List(test3)
true
2b7df14561403960fe975298193f7863d79d2987
charlesumesi/ComplexNumbers
/ComplexNumbers_Multiply.py
1,049
4.3125
4
# -*- coding: utf-8 -*- """ Created on 16 Feb 2020 Name: ComplexNumbers_Multiply.py Purpose: Can multiply an infinite number of complex numbers @author: Charles Umesi (charlesumesi) """ import cmath def multiply_complex(): # Compile one list of all numbers and complex numbers to be multiplied a = int(input('How many numbers and complex numbers are you multiplying? : ')) b = "Enter one real and its corresponding imaginary part in the format R,I\n(for absent real or imaginary part, enter '0', as in R,0 or 0,I) : " c = [list(input(b)) for _ in [0]*a] # Tidy the list by converting to string and reconverting back to a list d = [] for i in c: e = ''.join(i) d.append(e) # Use concatenation to convert each item in the list to string complex f = [] for i in d: g = 'complex(' + i + ')' f.append(g) del(c, d) # Convert the edited list to string proper and evaluate return eval('*'.join(f)) print(multiply_complex())
true
3d354cd1c4e773dee69e1b41201c83e943a11ed7
PurpleMyst/aoc2017
/03/first.py
878
4.1875
4
#!/usr/bin/env python3 UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) NEXT_DIRECTION = { RIGHT: UP, UP: LEFT, LEFT: DOWN, DOWN: RIGHT } def spiral_position(target): assert target >= 1 x, y = 0, 0 value = 1 magnitude = 1 direction = RIGHT while True: for _ in range(2): for _ in range(magnitude): if value == target: return (x, y) x += direction[0] y += direction[1] value += 1 direction = NEXT_DIRECTION[direction] magnitude += 1 def spiral_distance(target): x, y = spiral_position(target) return abs(x) + abs(y) def main(): with open("input.txt") as input_file: target = int(input_file.read()) print(spiral_distance(target)) if __name__ == "__main__": main()
false
007f176e9d38b1d07543cda8113ae468d31daa28
andresjjn/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
779
4.375
4
#!/usr/bin/python3 """ Module Print square This document have one module that prints a square with the character #. Example: >>> print_square(4) #### #### #### #### """ def print_square(size): """Add module. Args: size (int): The size length of the square. Reises: TypeError: - If size is not an integer. - If size is a float and is less than 0 ValueError: -If size is less than 0. """ if type(size) == int: if size >= 0: pass else: raise ValueError("size must be >= 0") else: raise TypeError("size must be an integer") for i in range(size): for j in range(size): print("#", end="") print("")
true
e23a809a3a920c566aa857d70f684fc787381bbb
GbemiAyejuni/BubbleSort
/bubble sort.py
828
4.28125
4
sort_list = [] # empty list to store numbers to be sorted list_size = int(input("Enter the size of list: ")) # variable to store size of list indicated by the user for i in range(0, list_size): number = int(input("Enter digit: ")) sort_list.append(number) # adds each number the user gives to sort_list print("Unsorted List: ", sort_list) for i in range(0, len(sort_list) - 1): swapped = False # swapped initialized as false for j in range(0, len(sort_list) - 1): if sort_list[j] > sort_list[j + 1]: sort_list[j], sort_list[j + 1] = sort_list[j + 1], sort_list[j] swapped = True # sets swapped to true if swapping of numbers occurs in the iteration if not swapped: break print("Sorted List: ", sort_list) input('Press Enter to Exit...')
true
bba7a6b1f479e572f02d49c019ad5e3acffe17ad
mbollon01/caesar
/caesar.py
1,968
4.15625
4
def main(): print ("Welcome to Caesar shift\n") print ("=======================\n") print ("1.Encrypt\n2.Decrypt") option = int(input("please input an option: ")) message = input('Enter Message: ') shift = int(input("input the shift: ")) if option ==1: encrypt(message, shift) elif option ==2: decrypt(message, shift) else: print("incorrect input") def encrypt(message, shift): encrypted = '' for i in range(len(message)): if message[i].isalpha(): if message[i].islower(): num = ord(message[i]) + shift if num > ord('z'): num -= 26 encrypted += chr(num) else: encrypted += chr(num) elif message[i].isupper(): num = ord(message[i])+shift if num > ord('Z'): num -= 26 encrypted += chr(num) else: encrypted += chr(num) elif ord(message[i]) == 32: encrypted += ' ' else: encrypted += chr(num) print (encrypted) f = open('encrypted.txt','w') f.write(encrypted) f.close print("This message has been successfully written to encrypted.txt") def decrypt(message, shift): decrypted = '' for i in range(len(message)): if message[i].isalpha(): if message[i].islower(): num = ord(message[i]) - shift if num > ord('z'): num -= 26 decrypted += chr(num) else: decrypted += chr(num) elif message[i].isupper(): num = ord(message[i]) - shift if num > ord('Z'): num -= 26 decrypted += chr(num) else: decrypted += chr(num) elif ord(message[i]) == 32: decrypted += ' ' else: decrypted += chr(num) print(decrypted) fileWrite(decrypted) def fileWrite(decrypted): file = open('decrypted.txt','w') file.write(decrypted) file.close print("This message has been successfully written to decrypted.txt") def fileRead(): message = '' file = open("encrypted.txt","r") message += file.readline() shift = int(input("Enter shift: ")) file.close() decrypt(message, shift) if __name__ == "__main__": main()
false
d9a69fbda9ed1346f9475dd255278948ae5038de
arifams/py_coursera_basic_
/for_test2.py
352
4.40625
4
print("before, this is the total number") numbers = 3,41,15,73,9,12,7,81,2,16 for number in numbers: print(number) print("now python try to find the largest number") largest_so_far = 0 for number in numbers: if number > largest_so_far: largest_so_far = number print(largest_so_far, number) print("Now the current largest is", largest_so_far)
true
7b9e12083faf0278926f41cc4c60562e24332697
lasupernova/book_inventory
/kg_to_PoundsOrOunces.py
1,806
4.125
4
from tkinter import * #create window-object window = Tk() #create and add 1st-row widgets #create label Label(window, text="Kg").grid(row=0, column=0, columnspan=2) #create function to pass to button as command def kg_calculator(): # get kg value from e1 kg = e1_value.get() # convert kg into desired units gram = float(kg)*1000 lbs = float(kg)*2.20462 oz = float(kg)*35.274 #output calculated units into respective fields upon clicking b1 t1.delete("1.0", END) # Deletes the content of the Text box from start to END t1.insert(END, f"{int(gram)}") # Fill in the text box with the value of gram variable t2.delete("1.0", END) t2.insert(END, f'{lbs:.2f}') t3.delete("1.0", END) t3.insert(END, f'{oz:.2f}') #get text variable to pass to textvariable-parameter e1_value=StringVar() #create and add entry-widget e1=Entry(window, textvariable=e1_value) e1.grid(row=0, column=2, columnspan=2) #create button-widget b1 = Button(window, text="Convert", command=kg_calculator) #NOTE: do NOT pass () after function-name, as command is only referencing the function #add button to specific window-Object location b1.grid(row=0, column=4, columnspan=2) #create and add second-row widgets #create label Label(window, text="g", justify=CENTER).grid(row=1, column=0) #create and add text-widget1 t1=Text(window,height=1, width=20) t1.grid(row=1,column=1) #create label Label(window, text="lb", justify=CENTER).grid(row=1, column=2) #create and add text-widget2 t2=Text(window,height=1, width=20) t2.grid(row=1,column=3) #create label Label(window, text="oz.", justify=CENTER).grid(row=1, column=4) #create and add text-widget3 t3=Text(window,height=1, width=20) t3.grid(row=1,column=5) #shoudl always be at the end of Tkinter-code window.mainloop()
true
6e8d17c385229344a5ba7cfddfdc9679de7e09eb
jelaiadriell16/PythonProjects
/pset2-1.py
736
4.1875
4
print("Paying the Minimum\n") balance = int(raw_input("Balance: ")) annualInterestRate = float(raw_input("Annual Interest Rate: ")) monthlyPaymentRate = float(raw_input("Monthly Payment Rate: ")) monIntRate = annualInterestRate/12.0 month = 1 totalPaid = 0 while month <= 12: minPayment = monthlyPaymentRate * balance monthBalance = balance - minPayment remBalance = monthBalance + (monIntRate * monthBalance) print("Month: %d" % month) print("Minimum monthly payment: "), round(minPayment, 2) print("Remaining balance: "), round(remBalance, 2) balance = remBalance month += 1 totalPaid += minPayment print "Total paid: ", round(totalPaid, 2) print "Remaining balance: ", round(balance, 2)
true
ba3b85ec95dc22ecb4c91ada9c2f61512e5359ea
Gabe-flomo/Filtr
/GUI/test/tutorial_1.py
1,950
4.34375
4
from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow import sys ''' tutorial 1: Basic gui setup''' # when working with PyQt, the first thing we need to do when creating an app # or a GUI is to define an application. # we'll define a function named window that does this for us def window(): # this is where we always have to start off # passing in sys.argv sets up the configuration for the application # so that it knows what OS its running on app = QApplication(sys.argv) # next we have to create some kind of widget/window that were actually going # to show in our application (you can use QMainWindow or QWidget) win = QMainWindow() # set the size and title of our window by calling the setGeametry() method # the arguments are the x position, y position, width, and height # the x,y positions are where on your screen do you want the window to appear # the width and height is the size of the window xpos = 200 ypos = 200 width = 300 height = 300 win.setGeometry(xpos, ypos, width, height) # next were going to set a window title which is what you will see in the # status bar of the application. win.setWindowTitle("Filtr") # Displaying something in the window # in this case its just going to be a basic label # by passing in the window to the .QLabel() method were telling # the label where we want it to appear, which is on the window. label = QtWidgets.QLabel(win) # this is how we make the label say something label.setText("A Label") # now we can tell the label to appear in the window by using the move() method xlabel = 50 ylabel = 50 label.move(xlabel,ylabel) # now to show the window we have to use the .show() method along with # another line that basically makes sure that we exit when we close the window win.show() sys.exit(app.exec_()) window()
true
75f4e3cd2ccfe294c9940f3cc7332c3626dcb139
Muhammad-Yousef/Data-Structures-and-Algorithms
/Stack/LinkedList-Based/Stack.py
1,303
4.21875
4
#Establishing Node class Node: def __init__(self): self.data = None self.Next = None #Establishing The Stack class Stack: #Initialization def __init__(self): self.head = None self.size = 0 #Check whether the Stack is Empty or not def isEmpty(self): return self.head == None #Display The Stack def display(self): if self.isEmpty(): print("Stack is Empty!") return currentNode = self.head while currentNode != None: print("[{}]".format(currentNode.data)) currentNode = currentNode.Next print() #Peek def peek(self): if self.isEmpty(): print("Stack is Empty!") return print("{}".format(self.head.data)) print() #Pushing def push(self, x): newNode = Node() newNode.data = x newNode.Next = self.head self.head = newNode self.size += 1 #Popping def pop(self): if self.isEmpty(): print("Stack is Empty!") value = -1 else: currentNode = self.head self.head = currentNode.Next value = currentNode.data self.size -= 1 return value
true
43f674a715ad3f044bc2a5b406dc3b5edabe1323
DoozyX/AI2016-2017
/labs/lab1/p3/TableThirdRoot.py
838
4.4375
4
# -*- coding: utf-8 -*- """ Table of third root Problem 3 Create a table with third root so that the solution is a dictionary where the key is the integer and the value is the third root of the integer. The keys should be numbers whose third root is also an integer between two values m and n. or a given input, print out the third root if it is already calculated in the dictionary. If the dictionary doesn't contain the value print out that there is no data. After that print out the sorted list of the key-value pairs from the dictionary. """ if __name__ == "__main__": m = input() n = input() x = input() # your code here tablica = {} for i in range(m, n+1): tablica[i*i*i] = i if x in tablica: print(tablica[x]) else: print("nema podatoci") print(sorted(tablica.items()))
true