blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7deb2d43fbf45c07b5e2186c320e77bdad927c18
iAmAdamReid/Algorithms
/recipe_batches/recipe_batches.py
1,487
4.125
4
#!/usr/bin/python import math def recipe_batches(recipe, ingredients, count=0): # we need to globally track how many batches we've made, and pass recursively # TODO: find how to do this w/o global variables global batches batches = count can_cook = [] # if we do not have any necessary ingredient, return 0 if len(recipe) > len(ingredients): return 0 # we need to see if we are able to make a batch for item in ingredients: if ingredients[item] >= recipe[item]: can_cook.append(True) else: can_cook.append(False) # if we have all necessary ingredients, add a batch to count and subtract from ingredients if all(can_cook): batches += 1 remainder = {key: ingredients[key] - recipe.get(key, 0) for key in ingredients.keys()} # recursion call with the remaining ingredients recipe_batches(recipe, remainder, batches) return batches ### NOTES # this subtracts the recipe from the ingredients and gives the remainder # remainder = {key: ingredients[key] - recipe.get(key, 0) for key in ingredients.keys()} if __name__ == '__main__': # Change the entries of these dictionaries to test # your implementation with different inputs recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
true
32cd09efb118604e0d5c2e521046e64e8ad1c33f
solcra/pythonEstudio
/cadenas.py
524
4.15625
4
texto = "Prueba dos dos" print("Upper") print(texto.upper()) print("Lower") print(texto.lower()) print("Capitalize") print(texto.capitalize()) print("Count") #print(texto.count()) print("Fing") #print(texto.fing()) print("Isdigit") print(texto.isdigit()) print("Isalnum") print(texto.isalnum ()) print("Isalpha") print(texto.isalpha()) print("Split") print(texto.split()) print("Strip") print(texto.strip()) print("Replace") print(texto.replace(" ","-")) print("Rfind") print(texto.rfind("o")) print("Len") print(len(texto))
false
9d6c5130c61b682b0de8397aee721303d56f4685
noahhenry/python_for_beginners
/notes/built-in_module_random.py
322
4.15625
4
import random for i in range(3): print(random.random()) # what if you want to limit the range of random numbers returned? # use random.randint() and pass in the range... for i in range(3): print(random.randint(10, 20)) members = ["John", "Marry", "Bob", "Mosh", "Noah"] leader = random.choice(members) print(leader)
false
1f0d340225be278ee074362f280207a60be9ed63
Ardra/Python-Practice-Solutions
/chapter3/pbm11.py
332
4.125
4
'''Problem 11: Write a python program zip.py to create a zip file. The program should take name of zip file as first argument and files to add as rest of the arguments.''' import sys import zipfile directory = sys.argv[1] z = zipfile.zipfile(directory,'w') length = len(sys.argv) for i in range(2,length): z.write(sys.argv[i])
true
09c3839dbbe5c8cfc50eff2e5bd07fa5851695c0
Ardra/Python-Practice-Solutions
/chapter6/pbm1.py
203
4.21875
4
'''Problem 1: Implement a function product to multiply 2 numbers recursively using + and - operators only.''' def mul(x,y): if y==0: return 0 elif y>0: return x+mul(x,y-1)
true
c19f67d6f4a5d2448fb4af73f1e3f12d3786bd1c
Ardra/Python-Practice-Solutions
/chapter3/pbm2.py
742
4.21875
4
'''Problem 2: Write a program extcount.py to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension.''' def listfiles(dir_name): import os list = os.listdir(dir_name) return list def word_frequency(words): frequency = {} for w in words: frequency[w] = frequency.get(w, 0) + 1 return frequency def ext_count(dir_name): list1 = listfiles(dir_name) #print list1 list2 = [] for x in list1: list2.append(x.split('.')) #print list2 list3 = [] for x in list2: if(len(x)>1): list3.append(x[1]) return word_frequency(list3)
true
29d5d901fc4ea681b9c2caa9f2dddf954174da4d
Ardra/Python-Practice-Solutions
/chapter2/pbm38.py
399
4.15625
4
'''Problem 38: Write a function invertdict to interchange keys and values in a dictionary. For simplicity, assume that all values are unique. >>> invertdict({'x': 1, 'y': 2, 'z': 3}) {1: 'x', 2: 'y', 3: 'z'}''' def invertdict(dictionary): new_dict = {} for key, value in a.items(): #print key, value new_dict[value]=key #print new_dict return new_dict
true
874438d788e903d45edc24cc029f3265091130b1
IDCE-MSGIS/sample-lab
/mycode_2.py
572
4.25
4
""" Name: Banana McClane Date created: 24-Jan-2020 Version of Python: 3.4 This script is for randomly selecting restaurants! It takes a list as an input and randomly selects one item from the list, which is output in human readable form on-screen. """ import random # importing 'random' allows us to pick a random element from a list restaurant_list = ['Dominos Pizza', 'Mysore', 'Restaurant Thailande', 'Lemeac', 'Chez Leveque', 'Sushi', 'Italian', 'Poutineville'] restaurant_item = random.choice(restaurant_list) print ("Randomly selected item from list is " + restaurant_item)
true
f8f811d817cea9bc27e663e2299a43e189e75a51
camilobmoreira/Fatec
/1_Sem/Algoritmos/Lista_04_Capitulo_04_-_Entrega_ 23_03/406_calc_preco_viagem.py
494
4.15625
4
#4.6) Escreva um programa que pergunte a distância que um passageiro deseja percorrer em km. Calcule o preço da passagem, cobrando R$0,50 por km para viagens de até 200km e R$0,45 para viagens mais longas. dist = -5 while(dist < 0): dist = float(input("Informe a distância da viagem (km): ")) if(dist < 0): print("Informe um valor maior que zero.") if(dist <= 200): print("A passagem ficou em R$%.2f" %(dist * .5)) elif(dist > 200): print("A passagem ficou em R$%.2f" %(dist * .45))
false
605f7cc9bfe67751cb89fa883285f051aa33626f
PolinaVasilevichh/Udemy
/сomparison_operators1.py
495
4.375
4
"""Создайте 2 переменных, содержащие числовые значения. Сравните их при помощи всех операторов сравнения и выведите результат на экран """ first_value = 5 second_value = 8 print(first_value > second_value) print(first_value < second_value) print(first_value >= second_value) print(first_value <= second_value) print(first_value == second_value) print(first_value != second_value)
false
b59250f494354805444856c585f6ce7019405f21
cristhoseby/RegularExpressions
/phone_number.py
1,689
4.34375
4
#phone number validtor import re pattern = """\(0 #open bracket followed by a zero #then either: ( 1 #1 #followed by either: ( \d{3} #3 digits \) #close bracket \s #single space \d{6} #6 digits | #or ( \d1 #a single digit followed by a 1 | #or 1\d #a 1 followed by a single digit ) \) #a close bracket \s #a single space \d{3} #3 digits \s #a single space \d{4} #4 digits ) | #or 2\d\) #2 followed by a digit and a close bracket \s #a single space \d{4} #4 digits \s #a single space \d{4} #4 digits )$""" finished = False while not finished: phone_number = input("Please enter your phone number: ") if len(phone_number) == 0: finished = True else: if re.match(pattern,phone_number,re.VERBOSE): print("Valid phone number") else: print("Invalid phone number")
false
c5a84486c9e216b5507fb076f1c9c64257804232
DaveG-P/Python
/BookCodes/DICTIONARIES.py
2,745
4.59375
5
# Chapter 6 # A simple dictionary person = {'name': 'david', 'eyes': 'brown', 'age': 28} print(person['name']) print(person['eyes']) # Accessing values in a dictionary print(person['name']) # If there is a number in value use str() print(person['age']) # Adding new key-valu pairs person['dominate side'] = 'left' person['city'] = 'bogota' # Starting with an empty list countries = {} countries['country'] = 'france' countries['capital'] = 'paris' # Modifying values in dictionary countries['capital'] = 'nice' print("The new capital of France is " + countries['capital']) # another example France = { 'capital': 'paris', 'idioma': 'frances', 'presidente': 'emmanuel macron', 'moneda': 'euro', } # Removing key value pairs del France['moneda'] # A dictionary of similar objects languages = { 'jen': 'python', 'david': 'python', 'andre': 'C ++', 'felipe': 'javascript', } print("David's favorite language is " + languages['david'].title() + ".") # Looping through a dictionary # Looping through all key values for k, v in France.items(): print("\nKey: " + k) print("\nValue: " + v) # Looping though all the keys for key in France.keys(): print(key.title()) friends = ['jen', 'andre'] for name in languages.keys(): print(name.title()) if name in firends: print("HI " + name.title() # Looping though keys in order for key in sorted(France.keys()): print(name.title() + ".") # Looping through all values print("Here are the following facts about France") for value in France.values(): print(value.title()) # Using set pulls out uniquge values for language in set(languages.values()): print(language.title()) # Nesting # List of dictioaries France = {'capital': 'paris', 'idioma': 'frances'} Spain = {'capital': 'madrid', 'idioma': 'catellano'} UK = {'capital': 'londres', 'idioma':'ingles'} countries = [France, Spain, UK] for country in countries: print(country) # A list in a dictionary UK = {'capital': 'londres', 'idioma':['ingles', 'gales', 'escoses']} France = {'capital': 'paris', 'idioma': ['frances', 'breton', 'gascon']} Spain = {'capital': 'madrid', 'idioma': ['catellano', 'catalan', 'aragones']} # dictionary inside a dictionary countries = { UK = { 'capital': 'londres', 'idioms':['ingles','gales', 'escoses'], 'monarcha': 'isabel II', }, France = { 'capital': 'paris', 'idioma': ['frances', 'breton', 'gascon'], 'monarcha': 'depuso' }, Spain = { 'capital': 'madrid', 'idioma': ['catellano', 'catalan', 'aragones'], 'monarcha': 'felipe vi' }, } for country, facts in countries.items(): print("\nCountry: " + country.title)
true
9773d6abe3781c5c2bc7c083a267a3b84bc30983
proTao/leetcode
/21. Queue/622.py
1,931
4.1875
4
class MyCircularQueue: def __init__(self, k: int): """ Initialize your data structure here. Set the size of the queue to be k. """ self.data = [None] * k self.head = 0 self.tail = 0 self.capacity = k self.size = 0 def enQueue(self, value: int) -> bool: """ Insert an element into the circular queue. Return true if the operation is successful. """ if self.size == self.capacity: return False self.data[self.tail] = value self.tail = (self.tail + 1) % self.capacity self.size += 1 return True def deQueue(self) -> bool: """ Delete an element from the circular queue. Return true if the operation is successful. """ if self.size == 0: return False self.data[self.head] self.head = (self.head + 1) % self.capacity self.size -= 1 return True def Front(self) -> int: """ Get the front item from the queue. """ return self.data[self.head] if self.size else -1 def Rear(self) -> int: """ Get the last item from the queue. """ if self.size: return self.data[(self.tail + self.capacity - 1)%self.capacity] else: return -1 def isEmpty(self) -> bool: """ Checks whether the circular queue is empty or not. """ return self.size == 0 def isFull(self) -> bool: """ Checks whether the circular queue is full or not. """ return self.size == self.capacity if __name__ == "__main__": obj = MyCircularQueue(2) print(obj.enQueue(1)) print(obj.enQueue(2)) print(obj.enQueue(3)) print(obj.deQueue()) print(obj.Front()) print(obj.Rear()) print(obj.isEmpty()) print(obj.isFull())
true
be7f5249e86caa685f932b2cbd962d11fb9596a5
purusottam234/Python-Class
/Day 17/exercise.py
722
4.125
4
# Create a list called numbers containing 1 through 15, then perform # the following tasks: # a. Use the built in function filter with lambda to select only numbers even elements function. # Create a new list containing the result # b.Use the built in function map with a lambda to square the values of numbers' elements. Create # a new list containing the result function # c. Filter numbers even elements , then map them to their squares .Create # a new list containing the result numbers = list(range(1, 16)) print(numbers) a = list(filter(lambda x: x % 2 == 0, numbers)) print(a) b = list(map(lambda x: x ** 2, numbers)) print(b) c = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers))) print(c)
true
03b3e29c726f1422f5fa7f6ec200af74bad7b678
purusottam234/Python-Class
/Day 17/generatorexperessions.py
530
4.1875
4
from typing import Iterable # Generator Expression is similar to list comprehension but creates an Iterable # generator object that produce on demand,also known as lazy evaluation # importance : reduce memory consumption and improve performance # use parenthesis inplace of square bracket # This method doesnot create a list numbers = [10, 2, 3, 4, 5, 6, 7, 9, 10] for value in (x**2 for x in numbers if x % 2 != 0): print(value, end=' ') squares_of_odds = (x ** 2 for x in numbers if x % 2 != 0) print(squares_of_odds)
true
c212f377fd1f1bf1b8644a068bbf0a4d48a86fb0
purusottam234/Python-Class
/Day 5/ifelif.py
524
4.28125
4
# pseudo code # if student'grade is greater than or equal to 90 # display "A" # else if student'grade is greater than or equal to 80 # display "B" # else if student'grade is greater than or equal to 70 # display "C" # else if student'grade is greater than or equal to 60 # display "D" # else # display "E" # Python implementation grade = int(input("Enter your marks:")) if grade >= 90: print("A") elif grade >= 80: print("B") elif grade >= 70: print("C") elif grade >= 60: print("D") else: print("E")
true
415a3f4dd9be70d5f66accb8b25db24791996c0b
purusottam234/Python-Class
/Day 14/conc.py
224
4.125
4
# + operator is used to Concatenate lists list1 = [10, 20, 30] list2 = [40, 50] concatenated_list = list2 + list1 print(concatenated_list) for i in range(len(concatenated_list)): print(f'{i}:{concatenated_list[i]}')
false
dd012da4f847a1ac2d8ee942adcad572104fa345
pianowow/projecteuler
/173/173.py
967
4.125
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: CHRISTOPHER_IRWIN # # Created: 05/09/2012 ##We shall define a square lamina to be a square outline with a square "hole" so ##that the shape possesses vertical and horizontal symmetry. For example, using ##exactly thirty-two square tiles we can form two different square laminae. ## ##With one-hundred tiles, and not necessarily using all of the tiles at one time, ##it is possible to form forty-one different square laminae. ## ##Using up to one million tiles how many different square laminae can be formed? from time import clock max = 1000000 count = 0 clock() for holeSide in range(1,int(max/4)): #1block all the way around t = 1 numBlocks = (holeSide+t)*4 while numBlocks <= max: count += 1 t+=2 numBlocks += (holeSide+t)*4 print (count, clock(), 'seconds')
true
9ecc61f4d52f236379f2c9ada813efd364e651c0
liradal/Python-520
/aula2/lacos.py
1,641
4.125
4
#!/usr/bin/python3 ###### ## laços de Repetição ###### ###### ## Laço Whiloe ###### # Este laço executa enquanto uma condição for verdadeira # i = 0 # while(i < 10): # enquanto i for menor que 10 # print(i) # mostra valor de i # i += 1 # i = i + 1 # repete # Como fazer controle de um loop while # while(True): # i += 1 # if i == 3: # break # if i == 3: # continue # print('Teoricamente, um loop infinito') # # Continue retoma do começo a execução de um loop # i = 100 # while i > 0: # enquanto i < 0 # i -= 1 # i = i - 1 # if i % 2 == 1: # continue # print(i) ####### ## Laço For ####### # Percorre itens em determinado alcance de valores # for (i=0;i<10;i++){ # // rotina de codigo # } # lista = [] # for i in range(1000): # Começa do 1 ate o 100 de 2 em 2 # lista.append(i) # print(lista) # # percorrer lista # for i in lista: # if i % 2 ==0: # print(f'\033[31m{i}\033[0m','par') # if i % 2 == 1: # print(f'\033[32m{i}\033[0m','impar') # # percorrer um dicionario # dicionario = { # 'nome':'Daniel': # 'Sobrenome':'Silva' # } # # for i in dicionario # # print(dicionario[i]) # for chave,valor in dicionario.itens() # print(chave) # print(valor) não funcionou # Enumerando itens de uma lista # lista = ['item1','item2','item3','item4','item5','item6','item7'] # print(list(enumerate(lista))) # for indice,valor in enumerate(lista): # print(indice) # # list comprehension (compreensão de listas) lista = [x*2 for x in range(1,100)] # aqui qualquer numero antes da virgula é o inicio print(lista)
false
66b4199a8bf357c92e78a65c637d07d79627b657
liradal/Python-520
/aula2/manipulacao_arq.py
1,021
4.375
4
#!/usr/bin/python3 ######### ## Manipulando arquivos com python ######### # ### Abrir um arquivo para modificação # #### Método não recomendado #### # ponteiro = open('nomedoarquivo.txt','a') # abre um ponteiro para # # escrita de arquivos, modo utilizado é o read plus (r+) que serve para # # leitura e escrita.Possuimos varios modos de acesso, por exemplo: # # w = sobrescrita # # r = somente leitura # # + = abre um arquivo para atualização acrescenta e modifica # # a = complemento # # x = criação # # esse método não é recomendado porque sempre necessita # # ser encerrado com close, isso foi substituido com adição # # do comando with será mostrado adiante # ponteiro.write('Olá Mundo\n') # ponteiro.close() #### Método Usual ##### with open('nome do arquivo2.txt','w') as arquivo: arquivo.write('Olá mundo\n') arquivo.writelines(['banana','maça']) #arquivo em modo de leitura with open('nome do arquivo2.txt','r') as arquivo: letras = arquivo.read() print(letras)
false
d28564c2c36afa5fe4e96ce763d90bd07b6f2bcd
alok162/Geek_Mission-Python
/count-pair-sum-in-array.py
901
4.125
4
#A algorithm to count pairs with given sum from collections import defaultdict #function to calculate number of paris in an array def countPairSum(d, arr, sum): count = 0 #storing every array element in dictionary and #parallely checking every element of array is previously #seen in dictionary or not for i in arr: if sum-i in d: count+=d[sum-i] d[i]+=1 else: d[i]+=1 return count #main function or driven program if __name__=='__main__': #taking input number of test cases t=int(input()) for test in range(t): #taking input n number of element in an array #and sum is to find pair through array element n, sum = map(int,input().split()) arr = list(map(int,input().split())) #defining dictionary d = defaultdict(int) print(countPairSum(d, arr, sum))
true
0700f44ab1b11b60d28cd635aeaf20df5b90959d
jaolivero/MIT-Introduction-to-Python
/Ps1/ProblemSet1.py
779
4.125
4
r = 0.04 portion_down_payment = 0.25 current_savings = 0.0 annual_salary = float(input( "What is your annual salary: ")) portion_saved = float(input("what percentage of your salary would you like to save? write as a decimal: ")) total_cost = float(input("what is the cost of your deam home: ")) monthly_savings = (annual_salary / 12) * portion_saved down_payment = total_cost * portion_down_payment months = 0 while current_savings < down_payment: current_savings += monthly_savings + (current_savings * r / 12) months += 1 print ("It would take you " + str(months) + " months to save for the down payment of your dreams home") print(months)
true
04acb5cf7f7f70354415001e67ba64b6062e97aa
isiddey/GoogleStockPrediction
/main.py
2,377
4.25
4
#Basic Linear Regression Tutorial for Machine Learning Beginner #Created By Siddhant Mishra #We will try to create a model to predict stock price of #Google in next 3 days import numpy as np import pandas as pd import quandl as qd import math from sklearn import preprocessing, cross_validation from sklearn.linear_model import LinearRegression # Getting the Stock data from Quandl print("Getting stock from Quandl .........") googleStock = qd.get('WIKI/GOOGL') # Printing un altered dataset pd.set_option('display.max_columns',None) print("\nGoogle Stock from Quandl: \n\n {}".format(googleStock.head())) # Indexing to filter relevant data features = ['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume'] dataset = googleStock[features] print("--------------------------------------------------------------------\n"*2) print("Filtered Dataset: \n {}".format(dataset.head())) # Modifying/Defining features for modelset (data cleaning + manipulation) # We remove outliers here and also NAN and other bad data modelset = dataset[['Adj. Close', 'Adj. Volume']] modelset.loc[:,'Stock Variance'] = (dataset['Adj. High']-dataset['Adj. Close']) / dataset['Adj. Close']*100 modelset.loc[:,'Percentage Change'] = (dataset['Adj. Close']-dataset['Adj. Open']) / dataset['Adj. Open']*100 modelset = modelset.fillna(-999999) #modelset.fillna(-999999, inplace=True) print("--------------------------------------------------------------------\n"*2) print("Model Set W/O Label :\n {}".format(modelset.head())) # Define Label predictionCol = 'Adj. Close' print(len(modelset)) forecastShift = int(math.ceil(0.005*len(modelset))) modelset['Label'] = modelset[predictionCol].shift(-forecastShift) modelset.dropna(inplace=True) #Define X and Y for Linear Equation # X is going to be our features and Y is going to be Label # so we find Y = Omega(X) X = np.array(modelset.drop(['Label'],1)) Y = np.array(modelset['Label']) # Feature Scale and do it over entire dataset # We do this before dividing data to have uniform normalization equation X = preprocessing.scale(X) Y = np.array(modelset['Label']) # Create Training and Testing Set XTrain, XTest, YTrain, YTest = cross_validation.train_test_split(X, Y, test_size=0.15) # Create and Train model clf = LinearRegression() clf.fit(XTrain, YTrain) accuracy = clf.score(XTest, YTest) print("\n\nModel Accuracy = {}".format(accuracy))
true
6545045e6e520f70af769078d008a3e72492c4fe
saifazmi/learn
/languages/python/sentdex/basics/48-53_matplotlib/51_legendsAndGrids.py
728
4.15625
4
# Matplotlib labels and grid lines from matplotlib import pyplot as plt x = [5,6,7,8] y = [7,3,8,3] x2 = [5,6,7,8] y2 = [6,7,2,6] plt.plot(x,y, 'g', linewidth=5, label = "Line One") # assigning labels plt.plot(x2,y2, 'c', linewidth=10, label = "Line Two") plt.title("Epic Chart") plt.ylabel("Y axis") plt.xlabel("X axis") plt.legend() # display legends, call AFTER plotting what needs to be in legend plt.grid(True, color='k') # display grid, black in color ''' ' things are displayed in the order they are called, for example line 2 draws ' over line 1 as we are ploting them in that order. ' But a grid line will always be drawn behind everything else, no matter when ' and where the function is called. ''' plt.show()
true
b6a0bc120206cbb24f780c8b35065925c9ae038a
saifazmi/learn
/languages/python/sentdex/intermediate/6_timeitModule.py
1,765
4.1875
4
# Timeit module ''' ' Measures the amount of time it takes for a snippet of code to run ' Why do we use timeit over something like start = time.time() ' total = time.time() - start ' ' The above is not very precise as a background process can disrupt the snippet ' of code to make it look like it ran for longer than it actually did. ''' import timeit # print(timeit.timeit("1+3", number=500000000)) ##input_list = range(100) ## ##def div_by_five(num): ## if num % 5 == 0: ## return True ## else: ## return False ## ##xyz = (i for i in input_list if div_by_five(i)) ## ##xyz = [i for i in input_list if div_by_five(i)] ## Timing creation of a generator expression print("Gen Exp:", timeit.timeit(""" input_list = range(100) def div_by_five(num): if num % 5 == 0: return True else: return False xyz = (i for i in input_list if div_by_five(i)) """, number=5000)) ## Timing creation of a list comprehension print("List Comp:", timeit.timeit(""" input_list = range(100) def div_by_five(num): if num % 5 == 0: return True else: return False xyz = [i for i in input_list if div_by_five(i)] """, number=5000)) ## Timing iterating over a genexp print("Iter GenExp:", timeit.timeit(""" input_list = range(100) def div_by_five(num): if num % 5 == 0: return True else: return False xyz = (i for i in input_list if div_by_five(i)) for i in xyz: x = i """, number=500000)) ## Timing iterating over a list comp print("Iter ListComp:", timeit.timeit(""" input_list = range(100) def div_by_five(num): if num % 5 == 0: return True else: return False xyz = [i for i in input_list if div_by_five(i)] for i in xyz: x = i """, number=500000))
true
dcc08fb3c7b4ef7eeee50d79bd1751b537083339
saifazmi/learn
/languages/python/sentdex/basics/8_ifStatement.py
302
4.46875
4
# IF statement and assignment operators x = 5 y = 8 z = 5 a = 3 # Simple if x < y: print("x is less than y") # This is getting noisy and clutered if z < y > x > a: print("y is greater than z and greather than x which is greater than a") if z <= x: print("z is less than or equal to x")
true
f9d01749e966f4402c3591173a145b65380d2102
saifazmi/learn
/languages/python/sentdex/basics/62_eval.py
900
4.6875
5
# Using Eval() ''' ' eval is short for evaluate and is a built-in function ' It evaluates any expression passed through it in form of a string and will ' return the value. ' Keep in mind, just like the pickle module we talked about, eval has ' no security against malicious attacks. Don't use eval if you cannot ' trust the source. For example, some people have considered using eval ' to evaluate strings in the browser from users on their website, as a ' way to create a sort of "online editor." While you can do this, you have ' to be incredibly careful! ''' # a list as a string list_str = "[5,6,2,1,2]" print("BEFORE eval()") print("list_str", list_str) print("list_str[2]:", list_str[2]) list_str = eval(list_str) print("\nAFTER eval()") print("list_str", list_str) print("list_str[2]:", list_str[2]) x = input("code:") print(x) check_this_out = eval(input("code>")) print(check_this_out)
true
27634a1801bd0a5cbe1ca00e31052065a8e4ce9b
saifazmi/learn
/languages/python/sentdex/basics/64-68_sqlite/66_readDB.py
852
4.40625
4
# SQLite reading from DB import sqlite3 conn = sqlite3.connect("tutorial.db") c = conn.cursor() def read_from_db(): c.execute("SELECT * FROM stuffToPlot") # this is just a selection data = c.fetchall() # gets the data print(data) # Generally we iterate through the data for row in data: print(row) # each row is basically a tuple c.execute("SELECT * FROM stuffToPlot WHERE value = 3") data = c.fetchall() print(data) for row in data: print(row) c.execute("SELECT * FROM stuffToPlot WHERE unix > 1520423573") data = c.fetchall() print(data) for row in data: print(row) c.execute("SELECT value, datestamp FROM stuffToPlot WHERE unix > 1520423573") data = c.fetchall() print(data) for row in data: print(row) read_from_db() c.close() conn.close()
true
95443c1973cf14c5467b2fb8c4e24fda942bdfa9
saifazmi/learn
/languages/python/sentdex/intermediate/7_enumerate.py
830
4.40625
4
# Enumerate ''' ' Enumerate takes an iterable as parameter and returns a tuple containing ' the count of item and the item itself ' by default the count starts from index 0 but we can define start=num as param ' to change the starting point of count ''' example = ["left", "right", "up", "down"] # NOT the right way of doing this for i in range(len(example)): print(i, example[i]) print(5*'#') # Right way of writing the above code for i, j in enumerate(example): print(i, j) print(5*'#') # Creating a dictionary using enumerate, where key is the index value new_dict = dict(enumerate(example)) print(new_dict) [print(i, j) for i, j in enumerate(new_dict)] print(5*'#') # Creating a list using enumerate new_list = list(enumerate(example)) print(new_list) [print(i, j) for i, j in enumerate(new_list, start=1)]
true
8bbb0737979d0709d1edca705a4966f369a110de
saifazmi/learn
/languages/python/sentdex/intermediate/2_strConcatAndFormat.py
1,161
4.21875
4
# String concatenation and formatting ## Concatenation names = ["Jeff", "Gary", "Jill", "Samantha"] for name in names: print("Hello there,", name) # auto space print("Hello there, " + name) # much more readable, but makes another copy print(' '.join(["Hello there,", name])) # better for performance, no copies print(', '.join(names)) # preferable when joining more than 2 or more strings import os location_of_files = "/home/saif/learn/notes/python/sentdex_tuts/intermediate" file_name = "1_intro.txt" print(location_of_files + '/' + file_name) # not the correct way but works # proper method of joining for file paths/location with open(os.path.join(location_of_files, file_name)) as f: print(f.read()) ## Formatting who = "Gary" how_many = 12 # Gary bought 12 apple today! # this is not the most optimal way of doing this. # in python2 we could have used something like %s etc. print(who, "bought", how_many, "apples today!") # In python 3 we use {} combined with format() print("{} bought {} apples today!".format(who, how_many)) # you can also give order sqeuence print("{1} bought {0} apples today!".format(who, how_many))
true
04652bd04e648972fd819c39d288b8f52577eb14
saifazmi/learn
/languages/python/sentdex/basics/43_tkMenuBar.py
1,464
4.25
4
# Tkinter Menu Bar ''' ' Menus are defined with a bottom-up approach ' the menu items are appended to the menu, appended to menu bar, ' appended to main window, appended to root frame ''' from tkinter import * class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.master.title("GUI") self.pack(fill=BOTH, expand=1) #quitButton = Button(self, text="Quit", command=self.client_exit) #quitButton.place(x=0, y=0) # define a menu bar instance menu = Menu(self.master) # this is the menu of the main window self.master.config(menu=menu) # Create a menu item for the menu bar file = Menu(menu) # Add a command "Exit" to the menu item file.add_command(label="Save") # example file.add_command(label="Exit", command=self.client_exit) # Add the menu item "File" to the menu bar as a cascading menu menu.add_cascade(label="File", menu=file) # Add another menu item to the menu bar edit = Menu(menu) edit.add_command(label="Undo") # not adding a command for now menu.add_cascade(label="Edit", menu=edit) def client_exit(self): exit() root = Tk() root.geometry("400x300") app = Window(root) root.mainloop()
true
2f6bb6a1d83586fe2504c1ceb787392891bd011d
lucky1506/PyProject
/Item8_is_all_digit_Lucky.py
311
4.15625
4
# Item 8 def is_all_digit(user_input): """ This function validates user entry. It checks entry is only digits from 0 to 9, and no other characters. """ numbers = "0123456789" for character in user_input: if character not in numbers: return False return True
true
086101d275de833242f8fcfd2acddbfd6af62919
gelfandbein/lessons
/fibonacci.py
1,176
4.625
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 4 18:50:32 2020 @author: boris """ """Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate. (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) """ import pprint num = int(input("Введите до какого числа считать последовательность Фибоначчи: ")) def fibonacci(num): fib1, fib2 = 0, 1 for _ in range(num): fib1, fib2 = fib2, fib1 + fib2 yield fib1 for fib in fibonacci(num): print(fib, end=' ') print() pp = pprint.PrettyPrinter() pp.pprint(sum(fibonacci(num))) print("next...\n") def fib(f): if f == 0: return 0 if f == 1: return 1 return fib(f - 1) + fib(f - 2) a = int(input("enter num: ")) print(fib(a))
true
b0d34741b9de03eafe535eac8f30c8f977fa6518
gordonramsayjr/Procedural-Programming
/fizzbuzz.py
239
4.1875
4
import math for x in range(100): if x % 5 == 0 and x % 3 == 0: print("Bingo!") elif x % 3 == 0: print(x,"Is divisible by 3!") elif x % 5 == 0: print(x,"Is divisible by 5!") print(x)
false
eabbc8071925c42d579fe00f9736c7319f5b2a65
somvud9843/leetcode
/Spiral Matrix.py
1,422
4.1875
4
''' Spiral Matrix I Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. Spiral Matrix II Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] ''' import random class Solution: def spairalMatrix(self, M): ''' type ans: list type M: list ''' ans = [] m = len(M) n = len(M[0]) lastRow = m lastCol = n circul = min(m, n)/2 for i in range(0, int(circul)+1 ,1): for j in range(i, lastCol ,1): ans.append(M[i][j]) for j in range(i+1 , lastRow, 1): ans.append(M[j][lastCol-1]) lastCol -=1 for j in range(lastCol-1, i-1, -1): ans.append(M[lastRow-1][j]) lastRow -= 1 for j in range(lastRow-1, i, -1): ans.append(M[j][i]) print(ans) c = Solution() m = random.randint(1, 10) n = random.randint(1, 10) count = 1 M = [] l = [] for i in range(m): for j in range(n): l.append(count) count += 1 m.append(l) c.spairalMatrix(M)
false
7d7d6e70123576f89a5c8d318fc7339ec7c1a771
shreyan-naskar/Python-DSA-Course
/Strings/Max frequency/prog.py
532
4.3125
4
''' Given a string s of latin characters, your task is to output the character which has maximum frequency. Approach:- Maintain frequency of elements in a separate array and iterate over the array and find the maximum frequency character. ''' s = input("Enter the string : ") D = {} Freq_char = '' Freq = 0 for i in s : if i not in D.keys() : D[i] = 1 else : D[i] += 1 for i in D.keys() : if D[i] > Freq : Freq = D[i] Freq_char = i print("Most frequent character : ", Freq_char) print("Frequency : ", Freq)
true
306f07a2159c83f1213a2d5d58b9b83a8a2778e5
shreyan-naskar/Python-DSA-Course
/Patterns/floyd triangle/prog.py
229
4.25
4
#Generating the Floyd Triangle n = int(input("Enter the number of rows : ")) v = 1 print('The Floyd Triangle would look like :\n') for i in range(1,n+1) : for j in range(1,i+1) : print(v , end = ' ') v = v + 1 print('\n')
false
591e06efb766c4fd99986c756192b68d91ea2fd3
shreyan-naskar/Python-DSA-Course
/Functions in Python/find primes in range/primes.py
429
4.15625
4
#Finding all primes in a given range. def isPrime( n ) : count = 0 for i in range(2,n) : if n%i == 0 : count = 0 break else : count = 1 if count == 1 : return True else : return False n = int(input('Enter the upper limit of Range : ')) List_of_Primes = [] for i in range(1,n+1) : if isPrime(i) : List_of_Primes.append(i) print('\nList of prime numbers in the range 1 to', n, 'is : ', List_of_Primes)
true
2dbeef63ca251b9d9ab446b8776ea376ac3b0451
akshajbhandari28/guess-the-number-game
/main.py
1,584
4.1875
4
import random print("welcome to guess the number game! ") name = input("pls lets us know ur name: ") print("hello, ", name, "there are some things you need tp know before we begin..") print("1) you have to guess a number so the number u think type only that number and nothing else") print("2) you will get three chances to guess the number") print("3) you have to guess the number between 1 and 10") print("3) if you guess the number you win!!!") play = input("if you agree to the rules and wanna play type 'yes' ") if play == "yes": print("great lets begin!!") else: print("ok, then bye till next time :)"); exit() rn = random.randint(0, 10) guess1 = int(input("pls guess a number: ")) if guess1 == rn: print("correct! great job!! :)") exit() if guess1 > rn: print("the number is smaller than this") if guess1 < rn: print("the number is bigger than this") guess2 = int(input("try again!!: ")) if guess2 == rn: print("correct! great job!! :)") exit() if guess2 > rn: print("the number is smaller than this") if guess2 < rn: print("the number is bigger than this") guess3 = int(input("try again!!: ")) if guess3 == rn: print("correct! great job!! :)") exit() if guess3 > rn: print("the number is smaller than this") if guess3 < rn: print("the number is greater than this") guess4 = int(input("try again!!: ")) if guess4 == rn: print("correct! great job!! :)") exit() if guess4 > rn: print("sorry but you lost, better luck next time :)") if guess4 < rn: print("sorry but you lost, better luck next time :)")
true
3829020674ee0e08dd307a6e89606752f27f810b
Meowsers25/py4e
/chapt7/tests.py
2,099
4.125
4
# handle allows you to get to the file; # it is not the file itself, and it it not the data in file # fhand = open('mbox.txt') # print(fhand) # stuff = 'hello\nWorld' # print(stuff) # stuff = 'X\nY' # print(stuff) # # \n is a character # print(len(stuff)) # 3 character string # a file is a sequence of lines with \n at the end of each line # use the for loop to iterate through the sequence # xfile = open('mbox.txt') # use quotations!!!!! # # cheese is the iteration variable, it goes through each line # for cheese in xfile: # print(cheese) # for each line inn xfile, print line # counting lines in a file # fhand = open('mbox.txt') # count = 0 # for line in fhand: # count = count + 1 # print('Line Count: ', count) # # reading the 'whole' file # fhand = open('mbox.txt') # inp = fhand.read() # reads whole file into a single string # print(len(inp)) # print(inp[:20]) # prints first 20 characters # searching through a file # fhand = open('mbox.txt') # count = 0 # for line in fhand: # if line.startswith('From:'): # line = line.rstrip() # .rstrip takes away the whitespace # count = count + 1 # print(line) # print(count) # skipping with continue # this does the same as above code # fhand = open('mbox.txt') # for line in fhand: # line = line.rstrip() # if not line.startswith('From:'): # continue # print(line) # using 'in' to select lines # fhand = open('mbox.txt') # for line in fhand: # line = line.rstrip() # if not '@uct.ac.za' in line: # continue # print(line) # prompt for filename # fname = input('Enter the file name: ') # fhand = open(fname) # count = 0 # for line in fhand: # if line.startswith('Subject:'): # count += 1 # print('There were', count, 'subject lines in', fname) # dealing with bad file names fname = input('Enter the file name: ') try: fhand = open(fname) except: print('File cannot be opened: ', fname) quit() count = 0 for line in fhand: if line.startswith('Subject:'): count += 1 print('There were', count, 'subject lines in', fname)
true
e1c7a8b10f8fdb183ec52927bf7b2fde52116971
Meowsers25/py4e
/chapt5/counting.py
1,245
4.15625
4
# counting # zork = 0 # print("Before: ", zork) # for thing in [9, 41, 12, 3, 74, 15]: # zork += 1 # print(zork, thing) # print("After: ", zork) # # # summing # zork = 0 # print("Before:", zork) # for thing in [9, 41, 12, 3, 74, 15]: # zork = zork + thing # print(zork, thing) # print("After:", zork) # # # Average # count = 0 # sum = 0 # print("Before:", count, sum) # for value in [9, 41, 12, 3, 74, 15]: # count += 1 # sum = sum + value # print(count, sum, value) # print("After:", count, sum, sum / count) # # # filtering # print('Before') # for value in [9, 41, 12, 3, 74, 15]: # if value > 20: # print('Larger', value) # print("After") # search using boolean # found = False # print('Before', found) # for value in [9, 41, 12, 3, 74, 15]: # if value == 3: # found = True # print(found, value) # print('After', found) # smallest smallest = None # none is None! print('Before') for value in [9, 41, 12, 3, 74, 15]: if smallest is None: # 'is' demands equality in type and value; stronger than == smallest = value elif value < smallest: smallest = value print(smallest, value) print('After', smallest) # use 'is' for None types or booleans also 'is not'
false
4071598da7f76b0c61a03325b989b3a58f2e91fd
wwwser11/train_task_massive
/task5.py
921
4.1875
4
# 5. В массиве найти максимальный отрицательный элемент. # Вывести на экран его значение и позицию в массиве. # Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный». # Это два абсолютно разных значения. import random print('vvedite diapazon massiiva') char1 = int(input('min massiva: ')) char2 = int(input('max massiva:')) user_choice = int(input('vvedite dliny massiva: ' )) a = [random.randint(char1, char2) for i in range(1, user_choice)] value = '' index = 0 for i, num in enumerate(a, 0): if (type(value) != int) and num < 0: value = num if num < 0 and num < value: value = num index = i print(a) print(f'значение {value},позиция {index}')
false
fe5e4243e64ebedaa1b31718b2be256e24cd52a3
bipulhstu/Data-Structures-and-Algorithms-Through-Python-in-Depth
/1. Single Linked List/8. Linked List Calculating Length.py
1,401
4.21875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): cur_node = self.head while cur_node: print(cur_node.data) cur_node = cur_node.next def append(self, data): #create memory new_node = Node(data) #insertion in an empty linked list if self.head is None: self.head = new_node return #insertion at the end of the linked list last_node = self.head while last_node.next is not None: last_node = last_node.next last_node.next = new_node def count_nodes_iterative(self): temp = self.head count = 1 while temp.next: count+=1 temp = temp.next return count def count_nodes_recursive(self, node): if node is None: return 0 return 1+ self.count_nodes_recursive(node.next) if __name__ == "__main__": llist = LinkedList() llist.append("A") llist.append("B") llist.append("C") llist.append("D") print(llist.count_nodes_iterative()) print(llist.count_nodes_recursive(llist.head)) llist.print_list()
true
05caa2fd68e08437ee71919e6bc044168d4b69fc
emsipop/PythonPractice
/pig_latin.py
680
4.28125
4
def pig_latin(): string = input("Please enter a string you would like translating: ").lower() #Changes case of all characters to lower words = string.split(" ") # Splitting the user's input into an array, each item corresponding to each word in the sentence translation = [] # An empty array which each translated word will be appended to for word in words: # The following will occur for each item in the array translation.append(word[1:] + word[0] + "ay") # Each word is translated and added to the new array return " ".join(translation) # The new array is then turned back into a string and is returned to give the full translated string
true
4a1333b1c3da67ad28f85a9094066b52c6ad51b6
gaurav9112in/FST-M1
/Python/Activities/Activity8.py
238
4.125
4
numList = list(input("Enter the sequence of comma seperated values : ").split(",")) print("Given list is ", numList) # Check if first and last element are equal if (numList[0] == numList[-1]): print("True") else: print("False")
true
020e801e0be13679a66e113af0945c191d54e2e9
aniruddha2000/dsa
/Recursion/reverseStringRecursion.py
210
4.15625
4
def reverse(string): if len(string) == 0: return string else: return reverse(string[1:]) + string[0] if __name__ == "__main__": result = reverse("aniruddha basak") print(result)
false
0071df21d8caf1ecaaf36ee25857ec85b9aae83d
davidjoliver86/advent-of-code-2019
/aoc2019/day3.py
2,344
4.1875
4
""" Day 3: Crossed Wires """ import pathlib import functools from typing import List, Tuple, Set def _trace_path(path: str) -> List[Tuple]: steps = path.split(",") path = [] x = 0 y = 0 for step in steps: direction, distance = step[0], int(step[1:]) if direction == "U": dy = 1 dx = 0 if direction == "D": dy = -1 dx = 0 if direction == "L": dx = -1 dy = 0 if direction == "R": dx = 1 dy = 0 for _ in range(distance): x += dx y += dy path.append((x, y)) return path @functools.lru_cache def _get_intersections(path_1: str, path_2: str) -> Set[Tuple]: points_1 = _trace_path(path_1) points_2 = _trace_path(path_2) return set(points_1) & set(points_2) def smallest_manhattan_distance(path_1: str, path_2: str) -> int: """ Find all intersections between path_1 and path_2. Then return the shortest "Manhattan distance" between the intersections. """ return min([(abs(x) + abs(y)) for x, y in _get_intersections(path_1, path_2)]) def shortest_intersection(path_1: str, path_2: str) -> int: """ Given the intersections we found earlier, trace each path's distance to that intersection. Then from all the intersection distances, return the shortest. """ points_1 = _trace_path(path_1) points_2 = _trace_path(path_2) intersections = _get_intersections(path_1, path_2) intersection_distances = [] for intersection in intersections: intersection_distances.append( points_1.index(intersection) + points_2.index(intersection) + 2 ) if intersection_distances: return min(intersection_distances) return None @functools.lru_cache def _load_fixtures() -> List[str]: return pathlib.Path("fixtures/day3_input1.txt").read_text().split() def first_star(): """ Find the shortest Manhattan distance. """ path_1, path_2 = _load_fixtures() return smallest_manhattan_distance(path_1, path_2) def second_star(): """ Find the shortest intersection. """ path_1, path_2 = _load_fixtures() return shortest_intersection(path_1, path_2) if __name__ == "__main__": first_star() second_star()
false
0e8240844666542eeb745b0e53c5471e9a7d55a9
sergiuvidican86/MyRepo
/exerc4 - conditions 2.py
327
4.1875
4
name = "John" age = 24 if name == "John" and age == 24: print("Your name is John, and you are also 23 years old.") if name == "test" pass if name == "John"or name == "Rick": print("Your name is either John or Rick.") if name in ["John", "Rick"]: print("Your name is either John or Rick.")
true
63c29133e42fb808aa8e42954534eef33508e22b
oscarwu100/Basic-Python
/HW4/test_avg_grade_wu1563.py
1,145
4.125
4
################################################################################ # Author: BO-YANG WU # Date: 02/20/2020 # This program predicts the approximate size of a population of organisms. ################################################################################ def get_valid_score():#re print the question n= int(input('Enter a score: ')) while n< 0 or n> 100: print('Invalid Input. Please try again.', end='') n= int(input('Enter a score: ')) return n def calc_average(l):#cal avg return sum(l)/ len(l) def determine_grade(g):# A B C D if g>= 90: return 'A' elif g>= 80: return 'B' elif g>= 70: return 'C' elif g>= 60: return 'D' else: return 'F' number=[0]* 5 for i in range(0,5): number[i]=get_valid_score() print('The letter grade for', format(number[i], '.1f'), 'is', determine_grade(number[i]), end='') print('.', end='') print('') print('The average test score is', format(calc_average(number), '.2f')) # print out the average result
true
d9134fcdc5012a0529bd7a77131fa7c80c4a9085
oscarwu100/Basic-Python
/HW2/roulette_wheel_wu1563.py
952
4.125
4
################################################################################ # Author: BO-YANG WU # Date: 02/05/2020 # This program calculate the pocket number color ################################################################################ num= int(input('Please enter a pocket number:')) if num< 0: print('Invalid Input!') elif num== 0: print('Pocket', num,'is green.') elif num< 10: if num% 2== 0: print('Pocket', num,'is black.') else: print('Pocket', num,'is red.') elif num< 19: if num% 2== 0: print('Pocket', num,'is red.') else: print('Pocket', num,'is black.') elif num< 29: if num% 2== 0: print('Pocket', num,'is black.') else: print('Pocket', num,'is red.') elif num< 37: if num% 2== 0: print('Pocket', num,'is red.') else: print('Pocket', num,'is black.') else: print('Invalid Input!')
false
6dd26ecb710eec1d072c7971044b29362b244b10
AMRobert/Simple-Calculator
/Simple_Calculator.py
1,846
4.15625
4
#SIMPLE CALCULATOR #Function for addition def addition(num1,num2): return num1 + num2 #Function for subtraction def subtraction(num1,num2): return num1 - num2 #Function for multiplication def multiplication(num1,num2): return num1 * num2 #Function for division def division(num1,num2): return num1 / num2 #Function for Calculation def calc(): print("1.Addition") print("2.Subtraction") print("3.Multiplication") print("4.Division") choice = int(input("Enter your choice: ")) if choice == 1: num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) print("Addition of",int(num1),"and",int(num2),"=",addition(num1,num2)) elif choice == 2: num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) print("Subtraction of",num1,"and",num2,"=",subtraction(num1,num2)) elif choice == 3: num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) print("Multiplication of",num1,"and",num2,"=",multiplication(num1,num2)) elif choice == 4: num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) print("Division of",num1,"and",num2,"=",division(num1,num2)) else: print("Invalid Input") print("Please choose the correct options") calc() print("SIMPLE CALCULATOR") print("Choose which operation you want to do!..") calc() for i in range(100): print("<------------------------>") print("Do you want to continue!..") print("1.yes") print("2.No") second_choice = int(input("Enter your choice: ")) if second_choice==1: calc() else: print("Thank You") exit()
true
e8af57b1a0b5d1d6ec8e8c7fa2899c2ddc8f2135
lnogueir/interview-prep
/problems/stringRotation.py
1,174
4.40625
4
''' Prompt: Given two strings, s1 and s2, write code to check if s2 is a rotation of s1. (e.g., "waterbottle" is a rotation of "erbottlewat"). Follow up: What if you could use one call of a helper method isSubstring? ''' # Time: O(n), Space: O(n) def isStringRotation(s1, s2): if len(s1) != len(s2): return False strLength = len(s1) or len(s2) s1Prefix = [] s1Suffix = [c for c in s1] s2Prefix = [c for c in s2] s2Suffix = [] for idx in range(strLength): if s1Suffix == s2Prefix and s1Prefix == s2Suffix: return True s1Prefix.append(s1Suffix.pop(0)) s2Suffix.insert(0, s2Prefix.pop()) return False ''' Follow up: Notice that if isStringRotation(s1, s2) == True Let `p` be the prefix of the string and `s` the suffix. Then s1 can be broken down into s1=`ps` and s2=`sp` Therefore, notice that s1s1 = `psps`, so s2 must be a substring. So: return isSubstring(s1+s1, s2) ''' print(isStringRotation("waterbottle", "erbottlewat")) print(isStringRotation("waterbottle", "erbottlewqt")) print(isStringRotation("waterbottle", "eniottlewdt")) print(isStringRotation("lucas", "sluca")) print(isStringRotation("lucas", "wluca"))
true
e931d6c45ba4181ee92a5df69d3de859f3e2926d
ShreyaKaran14/Python
/program7.py
632
4.15625
4
def birthday(x): if x == 'apurva': print(x,'Birthday is on',data['apurva']) if x== 'ankita': print(x,"Birthday is on",data['ankita']) if x=='madhu': print(x, "Birthday is on",data['madhu']) if x == 'kavita': print(x, "Birthday is on",data['kavita']) name = ['apurva','ankita','madhu','kavita'] data= {'apurva': '2/11/1996', 'ankita':'1/11/1996', 'madhu':'09/12/1998', 'kavita':'23/04/1998'} print("Welcome to Birthday Dictionary!!") print("We know the Birthday's of") for i in range(len(name)): print(name[i]) x = input("Who's birthday would you like to know :") birthday(x)
false
713020b5e737e835ddb818a5faaacd037a2e4d16
RaymondLloyd/Election_Analysis
/Python_practice.py
976
4.15625
4
counties = ["Arapahoe", "Denver","Jefferson"] if counties[1] == 'Denver': print(counties[1]) if "ElPaso" in counties: print("El Paso is in the list of counties.") else: print("El Paso is not in the list of counties.") if "Arapahoe" in counties and "El Paso" in counties: print("Arapahoe and El Paso are in the list of counties.") else: print("Arapahoe or El Paso is NOT in the list of counties.") counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} for county in counties_dict: print(county) for county in counties_dict: print(counties_dict.get(county)) voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] for county_dict in voting_data: print(county_dict) for county_dict in voting_data: for value in county_dict.values(): print(value)
false
334d1b51189b1492bb754f0db69a2357cc8e0f15
abideen305/devCamp-task
/Bonus_Task_2.py
1,845
4.46875
4
#!/usr/bin/env python # coding: utf-8 # In[4]: # program to replace a consonant with its next concosnant #Starting by definig what is vowel and what is not. Vowel are just: a,e,i,o,u #defining a function with the name vowel and its argument v def vowel(v): #if statement to taste if the word containing any of the letters of vowel if (v != 'a' and v != 'e' and v != 'i' and v != 'o' and v != 'u'): #the program should return false is it doesn't return False #returning true if the word containings vowel letter(s) return True #Now to have a function to replace a consonant #Here, I am defining my function with the name replaceConsonants and argument c def replaceConsonants(c): #looping through range of the length of c for i in range(len(c)): if (vowel(c[i])==False): #replacing z with b and not a if (c[i] == 'z'): c[i] = 'b' #an else statement to defining another condition if the argument is not z else: #here I am replacing the consonant with the next one with the method ord c[i] = chr(ord(c[i]) + 1) # checking and relacing the word if the next word above is a vowel. No two consecutive word is a vowel in alphabet if (vowel(c[i])==True): c[i] = chr(ord(c[i]) + 1) return ''.join(c) # taking input from the user for word to replace its consonants # and converting it to lowercase using .lower method c = input("Enter a sentence to replace its consonants: ") #storing my function in a variable called string and converting it to list string = replaceConsonants(list(c)) #replacing ! with nothing because by default the program will replace any space with exclamation string = string.replace("!", " ") #printing final result print(string)
true
f7330413f555d1dfa3164c3a3229e18cac863415
mmarcosmath/learning_python
/PythonOO/inputs.py
311
4.25
4
nome = input("Digite seu nome: ") print(nome) print(nome.upper()) print(nome.capitalize()) print("O nome digitado foi "+nome) print("O nome digitado foi {}".format(nome)) print("{} foi o nome digitado".format(nome)) sobre = input("Digite seu sobrenome: ") print("{} {} é o nome completo".format(nome,sobre))
false
97433547ac2da4227d9c64499727b46c5b05c3f7
Mayank2134/100daysofDSA
/Stacks/stacksUsingCollection.py
490
4.21875
4
#implementing stack using #collections.deque from collections import deque stack = deque() # append() function to push # element in the stack stack.append('a') stack.append('b') stack.append('c') stack.append('d') stack.append('e') print('Initial stack:') print(stack) # pop() function to pop element from stack in # LIFO order print('\nElements popped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are popped:') print(stack)
true
3f81995adbbbc6c32e77ca7aaa05c91f5dd25d99
Lexielist/immersive---test
/Prime.py
204
4.15625
4
A = input("Please input a number: ") print ("1 is not a prime number") for number in range (2,A): if num%A == 0: print (num," is a prime number) else: print (num,"is not a prime number)
true
a585ac1434cfc382a3d1f1f30850b36b4a0c3e35
Millennial-Polymath/alx-higher_level_programming
/0x06-python-classes/5-square.py
1,435
4.375
4
#!/usr/bin/python3 """ Module 5 contains: class square """ class Square: """ Square: defines a square Attributes: size: size of the square. Method: __init__: initialialises size attribute in each of class instances """ def __init__(self, size=0): self.__size = size @property def size(self): """ getter function for private attribute size Return: size """ return self.__size @size.setter def size(self, value): """ Setter function for private attribute size Args: value: the value to be assigned to size Return: Nothing """ if isinstance(value, int): self.__size = value if value < 0: raise ValueError("size must be >= 0") else: raise TypeError("size must be an integer") def area(self): """ public instance method calculates the area of a square args: None Return: current square area """ return self.__size * self.__size def my_print(self): """ Public instance method to print to stdout the square with "#" Args: None Return: None """ if self.__size == 0: print() for i in range(self.__size): print("#" * self.__size, end='') print()
true
f9411b270aea54e2d36cfabed30a18f3278a8b1e
eszkatya/test
/boolean.py
387
4.28125
4
#Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false. def bool_to_word(boolean): if boolean == True: return 'Yes' else: return 'No' """ezt is lehetett vna egy sorba, ami még érdekes: def bool_to_word(bool): return ['No', 'Yes'][bool] bár nem teljesen értem, hogy ez h működik
false
c7e9613d1af0ec7359dc8a175bbd99059b05c66b
iomkarsurve/basicpython
/conditional statements/calculator.py
309
4.25
4
num1 = int(input("Enter the first number")) num2 = int(input("Enter the second number")) op = input("Enter operator") if(op=="+"): print(num1+num2) elif(op=="-"): print(num1-num2) elif(op=="*"): print(num1*num2) elif(op=="/"): print(num1/num2) else: print("invalid operator")
false
944d8d7851bb5f27d6fc1e6d5b4043cacbb4e16a
beyzend/learn-sympy
/chapter3.py
329
4.34375
4
days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"] startDay = 0 whichDay = 0 startDay = int(input("What day is the start of your trip?\n")) totalDays = int(input("How many days is you trip?\n")) whichDay = startDay + totalDays print("The day is: {}".format(days[whichDay % len(days)]))
true
714981cda6519db2aefa69f575c1d87c454d1c77
ivan295/Curso-Python-Rafael
/tarea unidad 3/tarea3_ejercicio6.py
917
4.40625
4
""" Utilizando la función range() y la conversión a listas genera las siguientes listas dinámicamente: Todos los números del 0 al 10 [0, 1, 2, ..., 10] Todos los números del -10 al 0 [-10, -9, -8, ..., 0] Todos los números pares del 0 al 20 [0, 2, 4, ..., 20] Todos los números impares entre -20 y 0 [-19, -17, -15, ..., -1] Todos los números múltiples de 5 del 0 al 50 [0, 5, 10, ..., 50] Concepto útil Se pueden generar saltos en el range() estableciendo su tercer parámetro range(inicio, fin, salto), experimenta. """ print("lista del 0 al 10 : {}".format(list(range(0, 11)))) print("lista del -10 al 0 : {}".format(list(range(-10, 1)))) print("lista de pares de 0 al 20 : {}".format(list(range(0, 21, 2)))) print("lista de impares entre -20 y 0 : {}".format(list(range(-19, 1, 3)))) print("lista de los multiplos de 5 del 0 al 50 : {}".format(list(range(5, 51, 5))))
false
8bd9bbdabd8a962c794c3fa01b2de6437a0268ce
nenusoulgithub/LearnPython
/求知学堂/day8_09-类属性和实例属性.py
892
4.1875
4
# 类属性和实例属性 class Student: school = "东北师范大学" # 类属性 def __init__(self, name): self.name = name # 实例属性 def __str__(self): return "学生%s就读于%s" % (self.name, Student.school) xiaoming = Student("小明") print(xiaoming) print("类属性的地址是%d,内容是%s。" % (id(xiaoming.school), xiaoming.school)) xiaoming.school = "吉林大学" print("类属性的地址是%d,内容是%s。" % (id(xiaoming.school), xiaoming.school)) print(xiaoming) xiaomao = Student("小毛") print(xiaomao) xiaomao.school = "吉林农业大学" print(xiaomao) print(xiaomao.school) Student.school = "吉林大学" print(xiaoming) print("类属性的地址是%d,内容是%s。" % (id(xiaoming.school), xiaoming.school)) print(xiaomao) print("类属性的地址是%d,内容是%s。" % (id(xiaomao.school), xiaomao.school))
false
a8bc4dee358f97fe97efbb01cb8c1aa3fdba6078
nenusoulgithub/LearnPython
/求知学堂/day3_02-字符串操作.py
2,509
4.5625
5
# Python的序列 字符串 列表 元组 # 优点:通过下标访问元素 # 共同点:支持切片 python = "Python" print("字符串的第一个字符%s" % python[0]) print("字符串的第二个字符%s" % python[1]) for c in python: print(c, end=" ") print("\n--------------------------------------") # 大小写转换 python = "python" print("将单词的首字母变为大写%s" % python.capitalize()) print("将单词所有字母变为大写%s" % python.upper()) print("将单词所有字母变为小写%s" % python.lower()) s = "I like Python." print("把每个单词的首字符变大写%s" % s.title()) print("大小写逆转%s" % s.swapcase()) print("判断字符串是否大写%s" % python.upper().isupper()) print("判断字符串是否小写%s" % python.lower().islower()) print("--------------------------------------") # 去掉空格 python = " P y t h o n " print("去掉字符串中的空格%s。" % python.strip()) print("去掉字符串中的左边空格%s。" % python.lstrip()) print("去掉字符串中的右边空格%s。" % python.rstrip()) print("--------------------------------------") # 复制字符串:内存地址的复制,是同一个内存地址的引用 _python = python print("python的内存地址%d" % id(python)) print("python的内存地址%d" % id(_python)) print("--------------------------------------") # 字符串查找 s = "I like Python." print("使用find查找字符串o的位置%d" % python.find("o")) print("使用find查找字符串o的位置%d" % python.index("o")) print("字符串是否以I开头%s" % s.startswith("I")) print("字符串是否以.结尾%s" % s.endswith(".")) print("--------------------------------------") # 其他操作 print("判断是否字母和数字%s" % python.isalnum()) print("判断是否字母和数字%s" % s.isalnum()) print("判断是否字母%s" % python.isalnum()) print("判断是否数字%s" % "123".isdigit()) print("字符串连接%s" % "_".join(s)) print("替换字符串中的字母%s" % s.replace("I", "You", 1)) print("切分字符串%s" % s.split(" ")) print("字符串计数%d" % "aaabbcccc".count("c")) print("--------------------------------------") # 字符串切片(开始:结尾:步进) print("Hello World!"[2:10]) print("Hello World!"[:10]) print("Hello World!"[2:]) print("Hello World!"[:-5]) print("Hello World!"[2:10:2]) print("Hello World!"[2:10:1]) print("Hello World!"[9:1:-1]) print("Hello World!"[-3:1:-1]) print("Hello World!"[-3:-11:-1]) print("Hello World!"[9:-11:-1])
false
b50df42287c5962d04b762d0c32feb4a81b72ac6
nenusoulgithub/LearnPython
/求知学堂/day1_07-逻辑运算符.py
436
4.125
4
# 条件运算符 and or not a, b, c, d = 5, 8, 2, 9 print("---------------and---------------") print(a < b and c < d) print(b > c and d < a) print("---------------or---------------") print(a < b or c < d) print(b > c or d < a) print(b < c or d < a) print("---------------not---------------") print(not a < b) # 逻辑运算符优先级 # () > not > and > or print(2 > 1 and 1 < 4 or 2 < 4 and 9 > 3 or 1 < 4 and 3 < 2)
false
2f05c959814934372cf786623921c26f788d0d30
ed1rac/AulasEstruturasDados
/2019/## Python/Ordenacao e Busca/insertion_sort-v1.py
805
4.1875
4
""" A estrategia do insertion sort é: 1 - iterar usando i de vetor[1] até tamanho do vetor (laço externo) - vetor[i] é o atual 2 - fazer um laço (usando j) de i-1 até 0 e: (laço interno) 3 - se o valor de atual < vetor[j], afasta vetor[j] para direita 4 - quando vetor[j] encontrar um valor menor ou 0, então insere o atual em vetor[j+1] """ def insertion_sort(vetor): for i in range(1,len(vetor)): atual = vetor[i] j = i-1 while j>=0 and atual < vetor[j]: vetor[j+1] = vetor[j] j = j - 1 #print(vetor) vetor[j+1] = atual vetor = [10,9,8,7,6,5,4,3,2,1] print(vetor) insertion_sort(vetor) print(vetor) bandas = ['Led Zeppelin', 'Beatles', 'Guns and Roses', 'Pink Floyd', 'ABBA'] print(bandas) insertion_sort(bandas) print(bandas)
false
eb61ba46bf967a9e79600eb9905dfe652a4d0ca6
ed1rac/AulasEstruturasDados
/2019/## Python/Basico-MacBook-Ed/SlicesString.py
581
4.1875
4
s = 'Edkallenn' print("Fatias de strings:\n=============") print(s[2:]) #a partir da segunda posição, começando de zero, para frente - 'kallenn' print(s[1:]) #a partir da primeira posição, começando de zero, para frente - 'dkallenn' print(s[-1:]) #slice com a Última posição - 'n' print(s[-2:]) #slice com as duas últimas posições - 'nn' print(s[::-1]) #Imprime invertido print(s[2:6+1]) #COmeça em 2 ('k') e vai até o 6 (e) print(s[:2]) #Separa um slice com os dois primeiros caracteres print(s[:-2]) # Separa um slice com todos os caracteres menos os dois últimos
false
53d1afc8ba2931f4f6a4c4df9baaa017b3ebf3b9
ed1rac/AulasEstruturasDados
/UNP/ref/Python/TADs e Classes/Fila.py
1,120
4.1875
4
class Fila(object): 'uma classe de fila clássica' def __init__(self): 'instancia uma lista vazia' self.items = [] def esta_vazia(self): 'retorna True se a lista está vazia, False caso contrário' return (len(self.items)==0) #se o tamanho for zero def enfileira(self, item): #enqueue 'insere item no final da fila' return self.items.append(item) def desenfileira(self): #dequeue 'remove e retorna o item na frente da fila' if not (self.esta_vazia()): return self.items.pop(0) print('Impossível desenfileirar. Fila está vazia') def imprime(self): 'imprime a fila' print(self.items) def size(self): 'retorna o número de itens na fila' return len(self.items) fila = Fila() if fila.esta_vazia: print('Fila está vazia!') x = fila.desenfileira() fila.enfileira('Edkallenn') fila.enfileira('Vanessa') fila.enfileira(1) fila.enfileira(2) fila.enfileira(3) fila.enfileira('João') fila.imprime() print(fila.desenfileira()) print(fila.desenfileira()) print(fila.desenfileira()) fila.imprime() print(f'Tamanho da fila: {fila.size()}')
false
d975784b292282e44aab27e86b07d0a0a175230d
ed1rac/AulasEstruturasDados
/2019/## Python/TADs e Classes/TAD_ponto.py
936
4.28125
4
class Ponto(object): def __init__(self, x, y): #método construtor (cria ponto) self.x = x self.y = y def exibe_ponto(self): print('Coordenadas -> x: ', self.x, ', y: ', self.y) def set_x(self, x): self.x = x def set_y(self, y): self.y = y def get_x(self): return self.x def get_y(self): return self.y def distancia_entre(self, q): dx = q.x - self.x dy = q.y - self.y return (dx*dx+dy*dy)**0.5 def distancia_ate_origem(self): return ((self.x ** 2) + (self.y ** 2)) ** 0.5 p = Ponto(2.0,1.0) q = Ponto(3.4, 2.1) p.exibe_ponto() q.exibe_ponto() print('A distância entre o ponto p e q é: ', p.distancia_entre(q)) print(f'As coordenadas de p: {p.get_x()}, {p.get_y()}') print(f'As coordenadas de p: {q.get_x()}, {q.get_y()}') print('Distância de {} até a origem: {}'.format('p',p.distancia_ate_origem()))
false
e1730b223bc66de92afdb0f2f857a1b617a43df9
vivekdubeyvkd/python-utilities
/writeToFile.py
462
4.40625
4
# create a new empty file named abc.txt f = open("abc.txt", "x") # Open the file "abc.txt" and append the content to file, "a" will also create "abc.txt" file if this file does not exist f = open("abc.txt", "a") f.write("Now the file has one more line!") # Open the file "abc.txt" and overwrite the content of entire file, "w" will also create "abc.txt" file if this file does not exist f = open("abc.txt", "w") f.write("Woops! I have deleted the content!")
true
9a4374b3e3d6ef7651fdfbcd279af9c0d7cb2556
ducang/python
/session5/validate_input.py
749
4.1875
4
'''check ten ko co so''' # while True : # name = input("enter your name:") # if name.isalpha() : # break # else: # print("error, please enter a valid name.") '''check pass co chua so''' # while True: # pas= input("enter password:") # if pas.isalpha(): # print("password must have numbers, please re-enter") # else: # break '''check pass co >8''' # while True: # password= input("enter password:") # if password.isalpha(): # print("password must have numbers and more than 8 letters, please re-enter.") # elif len(password) < 8: # print ('password must have numbers and more than 8 letters, please re-enter.') # else: # break
false
191ce4a91dde400ff43493eea3a1b1a4f9ea08c9
HaminKo/MIS3640
/OOP/OOP3/Time1.py
1,646
4.375
4
class Time: """ Represents the time of day. attributes: hour, minute, second """ def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second def print_time(self): print('{:02d}:{:02d}:{:02d}'.format(self.hour, self.minute, self.second)) def time_to_int(self): minutes = self.hour * 60 + self.minute seconds = minutes * 60 +self.second return seconds def increment(self, seconds): result = Time() result.hour, result.minute, result.second = self.hour, self.minute, self.second result.second += seconds if result.second >= 60: result.second -= 60 result.minute += 1 if result.minute >= 60: result.minute -= 60 result.hour += 1 return result def is_after(self, other): return self.time_to_int() > other.time_to_int() def int_to_time(seconds): """Makes a new Time object. seconds: int seconds since midnight. """ minutes, second = divmod(seconds, 60) hour, minute = divmod(minutes, 60) return Time(hour, minute, second) # start = Time(9, 45, 0) start = Time() start.hour = 15 start.minute = 18 start.second = 50 start.print_time() print(start.time_to_int()) end = start.increment(2000) end.print_time() print(end.is_after(start)) # traffic = Time(0, 30, 0) # expected_time = Time(10, 15, 0) # traffic.print_time() # expected_time.print_time() # print(start.is_as_expected(traffic, expected_time)) # default_time = Time() # default_time.print_time()
true
04c359f3e674466994f258820239885690299c21
HaminKo/MIS3640
/session10/binary_search.py
1,143
4.1875
4
import math def binary_search(my_list, x): ''' this function adopts bisection/binary search to find the index of a given number in an ordered list my_list: an ordered list of numbers from smallest to largest x: a number returns the index of x if x is in my_list, None if not. ''' pass index = round(len(my_list)/2) move = round(len(my_list)/4) index_searched = [] while True: print("Printing index: {}".format(index)) if my_list[index] < x: index = index + move elif my_list[index] > x: index = index - move if my_list[index] == x: return index if index in index_searched or index <= 0 or index >= len(my_list) - 1: return "None" index_searched.append(index) move = math.ceil(move/2) test_list = [1, 3, 5, 235425423, 23, 6, 0, -23, 6434] test_list.sort() # [-23, 0, 1, 3, 5, 6, 23, 6434, 235425423] print(binary_search(test_list, -23)) print(binary_search(test_list, 0)) print(binary_search(test_list, 235425423)) print(binary_search(test_list, 30)) # expected output # 0 # 1 # 8 # None
true
47b9e54b2b400bf8981920e4924a38c8091392ac
AhmedKhalil777/courses
/data_structures_and_algorithms/Thebes-1st-2018-2019/Lectures/Lecture-06/run.py
1,163
4.3125
4
# بسم الله الرحمن الرحيم from Set import Set mahmoud = Set() mahmoud.add("CSCI-112") mahmoud.add("MATH-121") mahmoud.add("HIST-340") mahmoud.add("ECON-101") Eslam = Set() Eslam.add("POL-101") Eslam.add("ANTH-230") Eslam.add("CSCI-112") Eslam.add("ECON-101") # Determine if two students are taking: common_courses = Set() # print(type(mahmoud)) # print(type(Eslam)) # print(mahmoud.equals(Eslam)) # print(mahmoud == Eslam) # print(mahmoud.is_subset_of(Eslam)) # print(mahmoud.intersect(Eslam)) for course in mahmoud.intersect(Eslam): print(course) # ## 1 - all of the same courses # if mahmoud == Eslam: # print("Both students are taking same courses") # ## 2 - any of the same courses # elif mahmoud.intersection(Eslam) != None: # common_courses = mahmoud.intersection(Eslam) # print("There are common courses between them") # # for course in common_courses: # # print(course) # ## How can we determine which courses "Eslam" is taking that "mahmoud" is not taking # eslam_unique_courses = Eslam - mahmoud # print("Eslam Unique Courses are:") # for course in eslam_unique_courses: # print(course)
false
0757693b76c6ccf62eb380198ab10365d6a2c016
Titowisk/estudo_python
/meus_programas/04-desafio1.py
457
4.15625
4
# coding: utf-8 #desafio 1 #nome = input("Digite seu nome: ") #print("Bem-vindo", nome) #desafio 2 #dia = input("Digite o dia do seu nascimento: ") #mes = input("Digite o mês do seu nascimento: ") #ano = input("Digite o ano de seu nascimento: ") # #print("Você nasceu em", dia,"/",mes,"/",ano) #desafio 3 a = float(input("Digite aqui o primeiro número da soma: ")) b = float(input("Digite o segundo número da soma: ")) print(a+b) print("AW YEAH!")
false
fb16eda74a1e4ab4b412c9b206273839e3c8049c
jdogg6ms/project_euler
/p009/p9.py
885
4.1875
4
#!/usr/bin/env python # Project Euler Problem #9 """ A Pythagorean triplet is a set of three natural numbers. For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ from math import sqrt def test_triplet(a,b,c): return (a**2 + b**2 == c**2) def calc_triplet(a,b): return sqrt(a**2 + b**2) if __name__ == "__main__": c = 1 b = 1 done = False for a in xrange(1, 1000): for b in xrange(1, 1000): c = calc_triplet(a,b) if a+b+c == 1000: print a,b,c done = True break elif a+b+c >1000: break if done == True: break print "The triplet whose sum = 1000 is %s, %s, %s, whose product is: %s" %(a,b,c,(a*b*c))
true
0f8bc6d325c0e7af4cae255b3815e10be59148cb
utk09/open-appacademy-io
/1_IntroToProgramming/6_Advanced_Problems/10_prime_factors.py
1,096
4.1875
4
""" Write a method prime_factors that takes in a number and returns an array containing all of the prime factors of the given number. """ def prime_factors(number): final_list = [] prime_list_2 = pick_primes(number) for each_value in prime_list_2: if number % each_value == 0: final_list.append(each_value) return final_list def pick_primes(numbers): prime_list = [] for each_num in range(numbers): x = prime_or_not(each_num) if x != None: prime_list.append(x) return prime_list def prime_or_not(new_num): prime_list = [] last_num = new_num + 1 if new_num == 2: return new_num elif new_num > 2: for each_num in range(2, last_num): if new_num % each_num == 0: prime_list.append(each_num) if len(prime_list) == 1: for each_element in prime_list: return each_element else: return None else: return None print(prime_factors(24)) # => [2, 3] print(prime_factors(60)) # => [2, 3, 5]
true
6ea5413956361c5ce26f70079caefca87f352112
utk09/open-appacademy-io
/1_IntroToProgramming/6_Advanced_Problems/14_sequence.py
1,120
4.46875
4
""" A number's summation is the sum of all positive numbers less than or equal to the number. For example: the summation of 3 is 6 because 1 + 2 + 3 = 6, the summation of 6 is 21 because 1 + 2 + 3 + 4 + 5 + 6 = 21. Write a method summation_sequence that takes in a two numbers: start and length. The method should return an array containing length total elements. The first number of the sequence should be the start number. At any point, to generate the next element of the sequence we take the summation of the previous element. You can assume that length is not zero. """ def summation_sequence(start, length): final_list = [start] val = start i = 0 while i < length - 1: x = total_sum(val) final_list.append(x) val = x i += 1 return final_list def total_sum(num): for i in range(1, num): num = num + i return num print(summation_sequence(3, 4)) # => [3, 6, 21, 231] # => 3, 1+2+3=6, 1+2+3+4+5+6=21, 1+2+3+4+5+6+7+8+9+10+....+19+20+21 = 231 print(summation_sequence(5, 3)) # => [5, 15, 120] # => 5, 1+2+3+4+5=15, 1+2+3+4+5+....13+14+15=120
true
88f52244e93514f9bab7cbfb527c1505f298925b
utk09/open-appacademy-io
/1_IntroToProgramming/2_Arrays/2_yell.py
481
4.28125
4
# Write a method yell(words) that takes in an array of words and returns a new array where every word from the original array has an exclamation point after it. def yell(words): add_exclam = [] for i in range(len(words)): old_word = words[i] new_word = old_word + "!" add_exclam.append(new_word) return add_exclam print(yell(["hello", "world"])) # => ["hello!", "world!"] print(yell(["code", "is", "cool"])) # => ["code!", "is!", "cool!"]
true
f737fe1edc1d4837154537fd3e8a55da0ada12c7
utk09/open-appacademy-io
/1_IntroToProgramming/6_Advanced_Problems/1_map_by_name.py
895
4.125
4
""" Write a method map_by_name that takes in an array of dictionary and returns a new array containing the names of each dictionary key. """ def map_by_name(arr): map_list = [] for each_dict in range(len(arr)): map_dict = arr[each_dict] for key, value in map_dict.items(): if key == "name": map_list.append(map_dict["name"]) return map_list pets = [ {"type": "dog", "name": "Rolo"}, {"type": "cat", "name": "Sunny"}, {"type": "rat", "name": "Saki"}, {"type": "dog", "name": "Finn"}, {"type": "cat", "name": "Buffy"} ] print(map_by_name(pets)) # => ["Rolo", "Sunny", "Saki", "Finn", "Buffy"] countries = [ {"name": "Japan", "continent": "Asia"}, {"name": "Hungary", "continent": "Europe"}, {"name": "Kenya", "continent": "Africa"}, ] print(map_by_name(countries)) # => ["Japan", "Hungary", "Kenya"]
false
ac6ddb7a5ff88871ed728cc8c90c54852658ce30
utk09/open-appacademy-io
/1_IntroToProgramming/2_Arrays/12_sum_elements.py
586
4.15625
4
""" Write a method sum_elements(arr1, arr2) that takes in two arrays. The method should return a new array containing the results of adding together corresponding elements of the original arrays. You can assume the arrays have the same length. """ def sum_elements(arr1, arr2): new_array = [] i = 0 while i < len(arr1): new_array.append(arr1[i]+arr2[i]) i += 1 return new_array print(sum_elements([7, 4, 4], [3, 2, 11])) # => [10, 6, 15] # => ["catdog", "pizzapie", "bootcamp"] print(sum_elements(["cat", "pizza", "boot"], ["dog", "pie", "camp"]))
true
086ed855f74612d9ef8e28b2978ae7ffe5bf62f4
Mzomuhle-git/CapstoneProjects
/FinanceCalculators/finance_calculators.py
2,602
4.25
4
# This program is financial calculator for calculating an investment and home loan repayment amount # r - is the interest rate # P - is the amount that the user deposits / current value of the house # t - is the number of years that the money is being invested for. # A - is the total amount once the interest has been applied. # n - is the number of months over which the bond will be repaid. # i - is the monthly interest rate, calculated by dividing the annual interest rate by 12. # To include extended mathematical functions import math print("Choose either 'investment' or 'bond' from the menu below to proceed: ") print("investment \t - to calculate the amount of interest you'll earn on interest ") print("bond \t \t - to calculate the amount you'll have to pay on a home loan") calculator_type = input(": ") # choosing investment or bond if calculator_type == "investment" or calculator_type == "Investment" or calculator_type == "INVESTMENT": P = float(input("Enter the amount of money to deposit: ")) t = int(input("Enter the number of years: ")) interest_rate = float(input("Enter the percentage interest rate: ")) interest = input("Enter the type of interest [compound or simple] interest: ") r = interest_rate / 100 if interest == "simple" or interest == "SIMPLE" or interest == "Simple": # Formula for calculating simple interest A = P * (1 + r * t) A = round(A, 2) print("The total amount of money the user will earn is: R", A) elif interest == "compound" or interest == "COMPOUND" or interest == "Compound": # Formula for calculating compound A = P * math.pow((1 + r), t) A = round(A, 2) print("The total amount of money the user will earn is: \t R", A) # prints the error massage else: print("Error!!! Please choose the correct word [simple or compound] and try again") elif calculator_type == "bond" or calculator_type == "BOND" or calculator_type == "Bond": P = float(input("Enter the current value of the house: ")) interest_rate = float(input("Enter the annual interest rate: ")) n = int(input("Enter the number of months to repay: ")) r = interest_rate / 100 i = r / 12 # Formula for calculating bond repayment amount repayment = (i * P) / (1 - (1 + i) ** (-n)) repayment = round(repayment, 2) print("After each month the user will need to pay: \t R", repayment) # prints the error massage if the user doesn't enter investment or bond else: print("Error!!! Please enter the correct word [investment or bond] and try again")
true
4cbc8fddcb32ba425cbcbb2ff96f580384c8ddbb
rushabhshah341/Algos
/leetcode38.py
1,397
4.21875
4
'''The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Example 2: Input: 4 Output: "1211" ''' '''Python 2''' import copy class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str 1. 1 2. 11 3. 21 4. 1211 5. 111221 """ str1 = "1" if n == 1: return str1 str2 = "" for x in range(n-1): count = 1 str2 = "" prev = "" for i,c in enumerate(str1): if i == 0: prev = c count = 1 else: if prev == c: count += 1 else: str2 += str(count)+prev prev = c count = 1 str2 += str(count)+prev str1 = copy.deepcopy(str2) return str1
true
ca9c82e87d639e70de2ce6b214706617fb8f6a71
JeterG/Post-Programming-Practice
/CodingBat/Python/String_2/end_other.py
458
4.125
4
#Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string def end_other(a, b): lA=len(a) lB=len(b) if lA>lB: return a.lower()[-lB:]==b.lower() elif lB>lA: return b.lower()[-lA:]==a.lower() return a.lower()==b.lower()
true
f8b9bd890548a5d2b5fd2b60e23f68053b282097
duongtran734/Python_OOP_Practice_Projects
/ReverseString.py
625
4.5625
5
# Class that has method that can reverse a string class ReverseString: # take in a string def __init__(self, str=""): self._str = str # return a reverse string def reverse(self): reverse_str = "" for i in range(len(self._str) - 1, -1, -1): reverse_str += self._str[i] return reverse_str if __name__ == "__main__": #Get string from user str = input("Enter the string you want to reverse: ") #Initialize the object reversed_string = ReverseString(str) #call the method to reverse the string from the class print(reversed_string.reverse())
true
bd12113e4ca9a48b588c74d151d21373cdc9cfa1
pwittchen/learn-python-the-hard-way
/exercises/exercise45.py
875
4.25
4
# Exercise 45: You Make A Game ''' It's a very simple example of a "text-based game", where you can go to one room or another. It uses classes, inheritance and composition. Of course, it can be improved or extended in the future. ''' class Game(object): def __init__(self): self.kitchen = Kitchen() self.living_room = LivingRoom() def start(self): print "starting game..." action = raw_input("choose room: ") if action == "kitchen": self.kitchen.enter() elif action == "living_room": self.living_room.enter() else: print "I don't know that place" class Room(object): def enter(self): pass def leave(self): print "leaving room" class Kitchen(Room): def enter(self): print "entering Kitchen..." class LivingRoom(Room): def enter(self): print "entering Living Room..." game = Game() game.start()
true
7b979b62e0828aae93811ff6b9c39fd5bca83ec5
sushmithasuresh/Python-basic-codes
/p9.py
228
4.28125
4
n1=input("enter num1") n2=input("enter num2") n3=input("enter num3") if(n1>=n2 and n1>=n3): print str(n1)+" is greater" elif(n2>=n1 and n2>=n3): print str(n2)+" is greater" else: print str(n3)+" is greater"
false
4186b70a8f55396abe0bbd533fe61b7e8819f14e
mprior19xx/prior_mike_rps_game
/functions.py
919
4.34375
4
# EXPLORING FUNCTIONS AND WHAT THE DO / HOW THEY WORK # # EVERY DEFINITION NEEDS 2 BLANK LINES BEFORE AND AFTER # def greeting(): # say hello print("hello from your first function!") # this is how you call / invoke a function greeting() def greetings(msg="hello player", num1=0): # creating another function with variable arguments print("Our function says", msg, "and also the number", num1) myVariableNum = 0 # calling default argument for msg greetings() # these show up in place of msg and num # these arguments do nothing outside of the function greetings("This is an argument", 1) greetings("Why are we arguing?", 2) # function with math def math(num2=2, num3=5): # global enlarges scope to use variable global myVariableNum myVariableNum = num2 + num3 return num2 + num3 sum = math() print("the sum of the numbers is:", sum) print("the varial number is also:", sum)
true
53fcbf43171cfb5a3c38e05ee1c1d77d6b89a171
jhmalpern/AdventOfCode
/Puzzles/Day5/Day5Solution.py
2,238
4.1875
4
# Imports import time from re import search # From https://www.geeksforgeeks.org/python-count-display-vowels-string/ # Counts and returns number of vowels in a string ##### Part 1 functions ##### def Check_Vow(string, vowels): final = [each for each in string if each in vowels] return(len(final)) def Check_repeat(string): for each in range(1,len(string)): if(string[each] == string[each-1]): return(True) def Check_bad(string, test_list): res = [each for each in test_list if each in string] if len(res) >=1 : return(True) ##### Part 2 functions ##### def Check_doublet(string): doublet = [] for each in range(len(string)): try: doublet.append(string[each] + string[each + 1]) except: repeats = [doublet[dub] for dub in range(len(doublet)) if doublet[dub] in doublet[dub + 2:len(doublet)]] return(repeats) #return(doublet) def Check_sandwich(string): for each in range(len(string)): try: if string[each] == string[each + 2]: return(True) except: pass ##### Main ##### def main(): with open("PuzzleInput.txt","r") as f: puzzleInput = f.read().splitlines() ##### Part 1 ##### startTime1 = time.time() vowels = "aeiou" bad = ["ab", "cd", "pq", "xy"] niceString = 0 for i in range(len(puzzleInput)): if Check_Vow(puzzleInput[i],vowels) >= 3 and Check_repeat(puzzleInput[i]) and not Check_bad(puzzleInput[i],bad): # If it has more than 2 vowels niceString +=1 endTime1 = time.time() ##### Part 2 ##### startTime2 = time.time() niceString2 = 0 for i in range(len(puzzleInput)): if Check_sandwich(puzzleInput[i]) and len(Check_doublet(puzzleInput[i]))>0: niceString2 += 1 endTime2 = time.time() ##### Calls ##### print("There are %s nice strings in Part1:\t" % (niceString)) print("This solution took %s seconds" % (round(endTime1-startTime1,4))) print("There are %s nice strings in Part2:\t" % (niceString2)) print("This solution took %s seconds" % (round(endTime2-startTime2,4))) if __name__ == "__main__": main()
true
2bbc62def0409391e8d077114b6d001c95acd12b
xqhl/python
/04.function/03.function_return.py
802
4.1875
4
# 函数返回值 string = 'hello world' string = string.replace('o', '0') print(string) # 具备返回值的函数 def add(a=0, b=0): c = a + b return c def odd(c=1, d=1): e = c * d return e # result_add = add(2, 3) # result_odd = odd(c=result_add, d=6) # print(result_odd) result = odd(c=add(2, 3), d=6) print(result) # yield生成器 with open(file='../03.threeday/access_log', mode='r') as log: print(log.readline()) print(log.readline()) def ysd(): for i in range(100): yield i # @容器@ -> @1@ -> @1, 2@ def ysds(): listA = [] for i in range(100): listA.append(i) return listA result = ysd() print(result.__sizeof__()) # for i in result: # print(i) result = ysds() print(result.__sizeof__()) # for i in result: # print(i)
false
e7f9f4f92b756426ec8dfd9aa75eda62ef6f25f8
ngthnam/Python
/Python Basics/18_MultiDimensional_List.py
761
4.53125
5
x = [2,3,4,6,73,6,87,7] # one dimensional list print(x[4]) # single [] bracket to refer the index x = [2,3,[1,2,3,4],6,73,6,87,7] # two dimensional list print(x[2][1]) # using double [] to refer the index of list x = [[2,3,[8,7,6,5,4,3,2,1]],[1,2,3,4],6,73,6,87,7] # three dimensional list print(x[0][2][2]) # using triple [] to refer the index of the three dimensional list # you can also define a 3-D list in following manner, which is comparatively easy to visualize and understand x = [ [ 2, 3, [8,7,6,5,4,3,2,1] ], [ 1, 2, [5,6,7,8,9,12,34,5,3,2], 4 ], 6, 73, 6, 87, 7 ] print(x[1][2][-1])
true
73c8e86223f7de441517c9206ae526ef5365c664
JonathanFrederick/what-to-watch
/movie_rec.py
2,223
4.28125
4
"""This is a program to recommend movies based on user preference""" from movie_lib import * import sys def get_int(low, high, prompt): """Prompts the player for an integer within a range""" while True: try: integer = int(input(prompt)) if integer < low or integer > high: integer/0 break except: print("Please enter an integer between", low, "and", high) continue return integer def rate_movie(): while True: try: iden = int(input("Please enter the ID of the movie you'd like to rate >>")) except: print("Not a valid movie ID") if iden in all_movies: rate = get_int(0, 5, "Please enter your selected rating for "+all_movies[iden].title+"\nEnter a number 1 through 5 where 5 is more favorable or enter 0 to back out >>") if rate > 0: Rating(0, iden, rate) break else: print("Not a valid movie ID") def search_movies(): string = input("Please enter all or part of a movie title >> ").title() print("ID\tTITLE") for movie in all_movies.values(): if string in movie.title: print(str(movie.ident)+'\t'+movie.title) def main_menu(): while True: choice = get_int(1, 5, """Please select an option: 1 - View movies by highest average rating 2 - Search for a movie 3 - Rate a movie by ID 4 - Get recommendations (must have rated at least 4 movies) 5 - Exit >>>""") if choice == 1: print_movies_by_avg() elif choice == 2: search_movies() elif choice == 3: rate_movie() elif choice == 4: if len(all_users[0].ratings) > 3: num = get_int(1, 20, "Please enter a desired number of recommendations between 1 and 20") for movie in all_users[0].recommendations(num): print(movie.title) else: print("Rate more movies for this feature") else: sys.exit() def main(): load_data() all_users[0] = User(0) main_menu() if __name__ == '__main__': main()
true
eced2979f93a7fe022bab64f1520480b7882bf10
bishnu12345/python-basic
/simpleCalcualtor.py
1,770
4.3125
4
# def displayMenu(): # print('0.Quit') # print('1.Add two numbers') # print('2.Subtract two numbers') # print('3.Multiply two numbers') # print('4.Divide two numbers') def calculate(num1,num2,operator): result = 0 if operator=='+': result = num1 + num2 if operator == '-': result = num1 - num2 if operator == '*': result = num1 * num2 if operator == '/': result = num1 / num2 return result num1=int(input('Enter first number')) num2= int(input('Enter second number')) operator=input('Enter operator') result = calculate(num1,num2,operator) print(result) # displayMenu() # choice = int(input('Your Choice')) # while choice!=0: # if choice==1: # num1 = int(input("Enter first number")) # num2 = int(input("Enter second number")) # sum = num1 + num2 # print('The sum of {} and {} is {}'.format(num1,num2,sum)) # # elif choice==2: # num1 = int(input("Enter first number")) # num2 = int(input("Enter second number")) # subtract = num1 - num2 # print('The difference of {} and {} is {}'.format(num1, num2, subtract)) # # elif choice==3: # num1 = int(input("Enter first number")) # num2 = int(input("Enter second number")) # product = num1*num2 # print('The product of {} and {} is {}'.format(num1, num2, product)) # # elif choice==4: # num1 = int(input("Enter first number")) # num2 = int(input("Enter second number")) # division= num1/num2 # print('{} divided by {} is {}'.format(num1, num2, division)) # # displayMenu() # choice = int(input('Your Choice')) #print('Thank You')
true
789ca9376e8a07fc228c109b4dddaaf796b55173
skishorekanna/PracticePython
/longest_common_string.py
1,093
4.15625
4
""" Implement a function to determine the longest common string between two given strings str1 and str2 """ def check_common_longest(str1, str2): # Make the small string as str1 if not len(str1)< len(str2): str1, str2 = str2, str1 left_index=0 right_index=0 match_list = [] while ( left_index < len(str1)): matches="" if str1[left_index] in str2: temp_right = str2.find(str1[left_index]) temp_left = left_index while(str1[temp_left]==str2[temp_right]): matches+=str1[temp_left] temp_left+=1 temp_right+=1 if temp_left >= len(str1): break match_list.append(matches) left_index+=1 if not match_list: print("No match found") else: result = None for match in match_list: if not result: result = match continue if len(match) > len(result): result = match print("Match found is {}".format(result))
true
8b8471130787bf0c603dd98b79ac77848d72eda4
Andrew-Lindsay42/Week1Day1HW
/precourse_recap.py
277
4.15625
4
user_weather = input("Whats the weather going to do tomorrow? ") weather = user_weather.lower() if weather == "rain": print("You are right! It is Scotland after all.") elif weather == "snow": print("Could well happen.") else: print("It's actually going to rain.")
true
7a03a57714a7e1e7c4be0d714266f119ffbe2667
pankaj-raturi/python-practice
/chapter3.py
1,086
4.34375
4
#!/usr/bin/env python3 separatorLength = 40 lname = 'Raturi' name = 'Pankaj ' + lname # Get length of the string length = len(name) # String Function lower = name.lower() print (lower) # * is repetation operator for string print ( '-' * separatorLength) # Integer Object age = 30 # Convert Integers to string objects # Required to be concatenated with String Objects print(name + ' Age: ' + str(age)) print ( '-' * separatorLength) # --------------------------------------------------------- # Formating String formatted = 'I am {1}\nMy Age is {0} years'. format(age,name) print (formatted) print ( '-' * separatorLength) # ----------------------------------------------------------- # Format Specification (specifying the width of the objects for printing) print('{0:10} | {1:>10}'. format('Fruits', 'Quantity')) print('{0:10} | {1:>10.2f}'. format('Orange', 10)) print ( '-' * separatorLength) # ----------------------------------------------------------- # Accept standard input person = input('Please identify yourself: ') print('Hi {}. How are you?'.format(person))
true
8a3ad8eac1b92fcd869d220e1d41e19c65bf44d3
MegaOktavian/praxis-academy
/novice/01-05/latihan/unpickling-1.py
758
4.1875
4
import pickle class Animal: def __init__(self, number_of_paws, color): self.number_of_paws = number_of_paws self.color = color class Sheep(Animal): def __init__(self, color): Animal.__init__(self, 4, color) # Step 1: Let's create the sheep Mary mary = Sheep("white") # Step 2: Let's pickle Mary my_pickled_mary = pickle.dumps(mary) # Step 3: Now, let's unpickle our sheep Mary creating another instance, another sheep... Dolly! dolly = pickle.loads(my_pickled_mary) # Dolly and Mary are two different objects, in fact if we specify another color for dolly # there are no conseguencies for Mary dolly.color = "black" print (str.format("Dolly is {0} ", dolly.color)) print (str.format("Mary is {0} ", mary.color))
true
ab88ff7a1b5ebad88c6934741a0582603b9313ea
bmschick/DemoProject
/Unit_1.2/1.2.1/Temp_1.2.1.py
1,482
4.15625
4
'''1.2.1 Catch-A-Turtle''' '''Abstracting with Modules & Functions''' # 0.1 How does the college board create a “function”? # 0.2 What is “return” # 1 # Quiz: '''Events''' # # '''Click a Turtle''' # 2 through 14 (Make sure you comment the code!!): # 14 Did you have any bugs throughout this section of code? If so, what were they and how did you fix them? '''Move a Turtle''' # Quiz # How is Random in python different from what the college board uses? # 15 through 25 Copy and Paste the code form section 2-14 and contiune to develop it more here (don't forget to comment out the code above)! # 25 Did you have any bugs throughout this section of code? If so, what were they and how did you fix them? '''Display a Score''' # 26 # 27 # 28 through 41. Copy and Paste the code form section 15-25 and contiune to develop it more here (don't forget to comment out the code above)! # 41 Did you have any bugs throughout this section of code? If so, what were they and how did you fix them? '''Add a Countdown & It’s Your Turn''' # 42 through 50 & the It’s Your Turn Section!Copy and Paste the code form section 28-41 and contiune to develop it more here (don't forget to comment out the code above)! ''' Note: the more you try to do now, the cooler your app will work in 1.2.2, HOWEVER, make sure you know how/what your code does, otherwise 1.2.2 will become that much harder to complete. ''' '''Conclusion''' # 1 # 2
true
77244a8edec8f482e61cfe7cb2da857d989206cb
jesse10930/Similarities
/mario.py
830
4.3125
4
#allows us to use user input from cs50 import get_int #main function for the code def main(): #assigns the user input into the letter n while True: n = get_int("Enter an integer between 1 and 23: ") if n == 0: return elif n >= 1 and n <= 23: break #iterates from 0 up to user input to determine the number of rows for i in range(n): #iterates from 0 to n, determining number of columns. for j in range(n + 1): #prints either a space or a # depending on value of i and j, corresponding #to what row and column is active if n - (i + j) >= 2: print(' ', end='') else: print('#', end='') #moves to next row print() if __name__ == "__main__": main()
true