blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
54a10d41ef8a3bc55c624d1115bff0d731dff64f
androidSec/SecurityInterviews
/docs/custom_linked_list.py
837
4.15625
4
''' Create a linked list that supported add and remove. Numbers are added in ascending order, so if the list was 1,3,5 and 4 was added it would look like 1,3,4,5. ''' class custom_linked_list: def __init__(self): self.custom_list = [] def add(self, number): if len(self.custom_list) == 0: self.custom_list.append(number) return for i, n in enumerate(self.custom_list): if n >= number: self.custom_list.insert(i, number) return self.custom_list.append(number) def remove(self, number): if len(self.custom_list) == 0: raise for i, n in enumerate(self.custom_list): if n == number: del self.custom_list[i] return cll = custom_linked_list() cll.add(4) cll.add(9) cll.add(1) cll.add(7) cll.add(0) assert cll.custom_list == [0, 1, 4, 7, 9] cll.remove(4) assert cll.custom_list == [0, 1, 7, 9]
true
51fce45bb405ab2fc62e3f0cdfd92759b9e4f515
vijayb5hyd/class_notes
/turtle_race.py
2,138
4.28125
4
import turtle # Import every object(*) from module 'turtle' from turtle import * speed(100) penup() # The following code is for writing 0 to 13 numbers on the sheet # By default, the turtle arrow starts at the middle of the page. goto(x,y) will take it to (x,y). goto(-120,120) for step in range(14): write(step, align='center') forward(20) # the turtle arrow is moving 20 pixels with every step. But, it's not drawing since the pen is up. # The following code is to draw 0 to 13 lines goto(-120,120) for step in range(14): right(90) forward(10) pendown() # Starts drawing forward(200) # 200 pixels line penup() # stops left(180) forward(210) right(90) forward(20) # Import 'randint' object/member from the module 'random' from random import randint # Define turtle1 and start the race tigress=Turtle() # uppercase T in the function 'Turtle()', lowercase t will lead to NameError. tigress.color('orange') tigress.shape('turtle') tigress.penup() tigress.goto(-140,70) tigress.pendown() for turn in range(100): tigress.forward(randint(1,5)) # randint(x,y) generates random integers between x and y. Forward the turtle with the random number generated. # Define turtle2 and start the race viper=Turtle() viper.color('green') viper.shape('turtle') viper.penup() viper.goto(-140,35) viper.pendown() for turn in range(100): viper.forward(randint(1,5)) # Define turtle3 and start the race monkey=Turtle() monkey.color('yellow') monkey.shape('turtle') monkey.penup() monkey.goto(-140,0) monkey.pendown() for turn in range(100): monkey.forward(randint(1,5)) # Define turtle4 and start the race mantis=Turtle() mantis.color('blue') mantis.shape('turtle') mantis.penup() mantis.goto(-140,-35) mantis.pendown() for turn in range(100): mantis.forward(randint(1,5)) # Define turtle5 and start the race crane=Turtle() crane.color('gray') crane.shape('turtle') crane.penup() crane.goto(-140,-70) crane.pendown() for turn in range(100): crane.forward(randint(1,5)) turtle.exitonclick()
true
fdc37d4b6119ef863393cc36eec3fe8cbeafa09f
ramchinthamsetty/learning
/Python3/Advanced/decorators2.py
2,605
4.65625
5
""" 1. Demystifying Decorators for Simple Use. 2. Helps in Building Libraries and Frameworks. 3. Encapuslating details and providing simple interface. """ def simple_func1(x): ''' @return - Square of given values ''' return x*x # Passing the reference to a varibaale # dec_func is stored as a variable in Stack and it refers to address of simple_func dec_func = simple_func1 print(dec_func(10)) # Complete a simple test ''' Call function in function by passing function reference as variable ''' def simple_func2(func, x, y): ''' func - A Function reference called. x - an Integer y - an Integer. @return - Sum of outputs returned by func() referene called here ''' return func(x) + func(y) print(simple_func2(simple_func1, 10, 10)) # Test the output of function. def simple_func3(x): print("x - {}".format(x)) def inside_func(y): print("y - {}".format(y)) return x + y return inside_func # returns the reference of inside_func ''' Found the trick here :) 1. simple_func calls passing 4 and returns the refence of inside_func 2. func_var will call the internal reference and it finally exceutes and outputs the results ''' func_var = simple_func3(4) # simple_func() returns the interval reference of inside_func print(func_var(5)) # Calling inside_func with value ''' Decorator function executes before main starts execution ''' def trace(f): print("I was called here to return internal reference of g") def g(x): print(f.__name__, x) print("I am executing this time!") return f(x) return g ''' Syntactic Sugar of decorator as follows 1. Simple decorators here. 2. @trace is euqal to var_func = trace(square) - returns the refernce to square. var_func(value) - returns the square value ''' @trace def square(x): return x*x @trace def add(x): return x+x @trace def difference(x): return x-x ''' Lets try some here as it is tasting good :) 1. Passing multiple arguments to decorator functions. 2. So use *args to perform this. ''' def trace2(f): def g(*args): print(f.__name__, args) return f(*args) return g @trace2 def square2(x): return x*x @trace2 def sum_of_squares(x,y): return square2(x)+square2(y) def main(): print("Checking if decorators execution is done at import time or not") print(sum_of_squares(4,9)) print(square(4)) print(add(4)) print(difference(10)) if __name__ == '__main__': main()
true
bf5a57816608353f402c38cbb0f0294fbad96731
cintax/dap_2019
/areas_of_shapes.py
944
4.21875
4
#!/usr/bin/env python3 import math def circle(): radius = int(input("Give radius of the circle: ")) print(f"The area is {math.pi*(radius**2):6f}") def rectangle(): width = int(input("Give width of the rectangle: ")) height = int(input("Give height of the rectangle: ")) print(f"The area is {height*width:6f}") def triangle(): base = int(input("Give base of the triangle: ")) height = int(input("Give height of the triangle: ")) print(f"The area is {0.5*base*height:6f}") def main(): # enter you solution here while True: choice = input("Choose a shape (triangle, rectangle, circle): ") if choice == "triangle": triangle() elif choice == "circle": circle() elif choice == "rectangle": rectangle() elif choice == "": break else: print("Unknown shape!") if __name__ == "__main__": main()
true
b6d75f871bb2a85f93d87234fd97c73cd7350ecf
hiSh1n/learning_Python3
/Day_02.py
1,249
4.3125
4
#This is day 2 #some variable converters int(),str(), bool(), input(), type(), print(), float(), by default everything is string. #Exercise 03- #age finder birth_year = input("what's your Birth Year:") age = (2021 - int(birth_year)) print("your are " + str( age) + " years old !") print(" ") #Exercise 04- #pound to kilo weight convertor- your_weight = input("Enter the weight in pounds: ") a_kilo = (int(your_weight) / 2.20) print(str(your_weight) + ' Pound is equal to ' + str(a_kilo) + " kg") print(" ") #python indexing #python indexes strints like 'APPLE' # 01234 #there's also negitive indexing line 'A P P L E' # ...-2 -1 #index printing dummy = 'jojo' print(dummy[0]) #output = j, 0 print(dummy[0:3]) #output = joj, 0,1,2 print(" ") #formatted strings, use f'{placeholder for variable} no concatenation needed. first_name = 'jonny' last_name = 'jake' message = f'{first_name} {[last_name]} is our secret agent! ' #without f'string I have to write it as #message = first_name + ' [' + last_name + ' ]' + 'is our secret agent!' print(message) print(" ") #TO BE CONTINUE...
true
b6ec7850d06b74c6009467c3dc860bde78298164
DanielHabib/HowManyBalloons
/HowManyBalloonsAlg.py
514
4.125
4
"""How Many Balloons Alghorithm""" import math class BalloonCount(object): grams = 453.593 liters_in_balloon = 14 def __init__(self, weight): self.weight = weight def how_many_balloons(self): balloons = self.weight * self.grams / self.liters_in_balloon return ("It would take %s balloons to lift %s lbs!" % (math.ceil(balloons), self.weight)) if __name__ == '__main__': weight = BalloonCount(int(input("Enter your weight "))) print (weight.how_many_balloons())
false
a61941a1d02f0fe26da9dfb3586341bcaa5cb419
joshuaabhi1802/JPython
/class2.py
793
4.125
4
class mensuration: def __init__(self,radius): self.radius=radius self.pi= 22/7 def area_circle(self): area = self.pi*self.radius**2 return area def perimeter_circle(self): perimeter = 2*self.pi*self.radius return perimeter def volume_sphere(self): volume= 4/3*self.pi*self.radius**3 return volume if __name__ == "__main__": print("Enter the radius") a=int(input()) print("Please select the options given below-\n1.Area of circle\n2.Perimeter of circle\n3.Volume of sphere") b=int(input()) s= mensuration(a) if b==1: print('Area is:',s.area_circle()) if b==2: print('Perimeter is:',s.perimeter_circle()) if b==3: print('Volume is:',s.volume_sphere())
true
abd5cb0421cd452bdb1405cca6a680f7f7f2ead3
mthompson36/newstuff
/codeacademypractice.py
856
4.1875
4
my_dict = {"bike":1300, "car":23000, "boat":75000} """for number in range(5): print(number, end=',')""" d = {"name":"Eric", "age":26} for key in d: print(d.items()) #list for each key and value in dictionary for key in d: print(key, d[key]) #list each key and value in dictionary just once(not like above example) for letter in "Eric": print(letter) for key in my_dict: print(key, my_dict[key]) #List comprehensions evens_to_50 = [i for i in range(51) if i % 2 == 0] print(evens_to_50) even_squares = [x**2 for x in range(12) if x % 2 == 0] print(even_squares) cubes_by_four = [x**3 for x in range(11) if x % 4 ==0] #not sure why x%4 w/o parenthesis doesn't work see example below print(cubes_by_four) cubes_by_four1 = [x**3 for x in range(1,11) if ((x**3) % 4 ==0)] print(cubes_by_four1) l = [x**2 for x in range(1,11)] print(l[2:9:2])
true
d416f36e048c95fd1d331c0e9b5d4dd64c16c7ca
rafaelsaidbc/Exercicios_python
/ex093.py
1,246
4.125
4
'''Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.''' from time import sleep dicionario = {} dicionario['nome'] = str(input('Nome do jogador: ')) partidas = int(input('Quantas partidas ele jogou? ')) gols = [] total_gols = 0 for partida in range(1, partidas + 1): gol = int(input(f'Quantos gols ele fez na {partida}ª partida? ')) gols.append(gol) total_gols += gol dicionario['gols'] = gols dicionario['total_gols'] = total_gols print('*' * 40) print(dicionario) print('*' * 40) for chave, valor in dicionario.items(): print(f'O campo {chave} tem o valor {valor}.') print('*' * 40) contador = 1 for elemento in gols: print(f'Na {contador}ª partida, ele fez {elemento} gols.') contador += 1 sleep(1) # print(f'O nome do jogador é {dicionario["nome"]}.') # print(f'Ele marcou os gols nessa ordem {gols}') # print(f'Ele marcou ao todo {dicionario["total_gols"]} gols.') # print('*'*40) # print(f'O jogador {dicionario["nome"]} jogou {partidas} partidas.')
false
59a3f75b4cfc0851b9478a998b94262fdccdbece
rafaelsaidbc/Exercicios_python
/ex080.py
783
4.25
4
'''Crie um programa que o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista, já na posição correta de inserção (sem usar o sort()). No final , mostre a lista ordenada na tela.''' lista = [] for elemento in range(0, 5): numero = int(input('Adicione um número na lista: ')) if elemento == 0 or numero >= lista[-1]: lista.append(numero) print(f'O número {numero} foi adicionado ao final da lista...') else: posicao = 0 while posicao <= len(lista): if numero <= lista[posicao]: lista.insert(posicao, numero) print(f'O número {numero} foi inserido na posição {posicao}...') break posicao += 1 print(f'Você digitou essa lista\n{lista}')
false
37277bbd39ba1a73e04a4d28d8e41a0eb04da7ad
rafaelsaidbc/Exercicios_python
/ex042.py
947
4.34375
4
'''Verificar se 3 retas podem formar um triângulo e qual tipo de triângulo elas formarão - equilátero: todos os lados são iguais - isósceles: dois lados iguais - escaleno: nenhum lado igual''' lado1 = float(input('Dê a medida de uma reta: ')) lado2 = float(input('Dê a medida de outra reta: ')) lado3 = float(input('Dê a medida de uma terceira reta: ')) if lado1 < (lado2 + lado3) and lado2 < (lado1 + lado3) and lado3 < (lado2 + lado1): print('As retas de comprimento {}, {} e {} podem formar um triângulo.'.format(lado1, lado2, lado3)) if lado1 == lado2 and lado1 == lado3: print('O triângulo formado será EQUILÁTERO.') elif lado1 == lado2 or lado1 == lado3 or lado2 == lado3: print('O triângulo formado será ISÓSCELES') else: print('O triângulo formado sera ESCALENO.') else: print('As retas de comprimento {}, {} e {} não podem formar um triângulo.'.format(lado1, lado2, lado3))
false
b3b88fe8ea17fd2a5d32e6ca796633d9855c7aa4
Izaya-Shizuo/lpthw_solutions
/ex9.py
911
4.5
4
# Here's some new strange stuff, remember type it exactly # Assigning the days variable with a string containing the name of all the 7 days in their short form days = "Mon Tue Wed Thu Fri Sat Sun" # Assigning the month variable with the name of the months from Jan to Aug in their short forms. After ech month's name there is a new line character which while printing place the cursor on the next line. months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" # These two print commands print the days and months variable values as they are stored in the variables print "Here are the days: ", days print "Here are the months: ", months # This print statement can print multiple lines if use 3 double-quotes at the starting and the end of the print statement. print """ There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """
true
41925bae39b1ab9472d933a9f9a87e11f076fa0a
entropy-dj/word2vec
/key_lambda_test.py
612
4.28125
4
""" 在排序的时候,接使用sorted方法,返回一个列表就是排序好的 测试一下 啧啧啧 """ a = [4, 2, 6, 1, 8, 3, 6, 3] b = ["d", "a", "x", "w", "v", "c"] print(sorted(a)) print(sorted(b)) print(sorted(a, reverse=True)) print(sorted(b, reverse=True)) """ x[0]表示元组里的第一个元素,x[1]当然就是第二个元素; """ a = [("d", 4), ("a", 1), ("c", 9), ("b", 5), ("e", 2), ] print(sorted(a, key=lambda x: x[0])) print(sorted(a, key=lambda x: x[1])) print(sorted(a, key=lambda x: x[0], reverse=True)) print(sorted(a, key=lambda x: x[1], reverse=True))
false
198144fb410628ec9afe4457204c78cb7df7d12e
priscilalobo/Python_Studies
/aulas/aula9.py
1,052
4.125
4
# Manipulando textos '''frase = curso em video python frase.split() = dividir uma string em uma lista '-'.joint(frase) = junta as frases e separa pelo - frase.count('o') - contar quantas strings especificas len(frase) - contar quantas caracteres tem frase.found('deo') - procurar na frase a lista sempre começa a contar no 0, por exemplo: frase[0], ele vai aparecer a letra C 'Curso' in frase - vai responder true ou false frase.replace('Python','Android') frase.upper() = deixar maisculo frase.lower() = deixa minusculo frase.capitalize() = deixa as primeiras letras em maisculo frase.strip() = vai retirar espaços inuteis no começo e na final do str frase.rstrip() = tira somente os ultimos espaços (right) frase.lstrip() = tira somente os primeiros espaços (left) ''' frase = 'Curso em video Python' print(len(frase[3:9])) print("""Title function in python is the Python String Method which is used to convert the first character in each word to Uppercase and remaining characters to Lowercase in string and returns new string.""")
false
9224069954e9e321b596b41d93630454b4b016ba
priscilalobo/Python_Studies
/Exercicios/exercicio59.py
2,250
4.15625
4
#Crie um programa que leia dois valores e mostre um menu na tela: #[ 1 ] somar #[ 2 ] multiplicar #[ 3 ] maior #[ 4 ] novos números #[ 5 ] sair do programa #Seu programa deverá realizar a operação solicitada em cada caso. """n1 = int(input('Digite o primeiro número: ')) n2 = int(input('Digite o segundo numero: ')) escolha = 0 while escolha != 5: escolha = int(input('Escolha a opção no Menu:\n[ 1 ] somar\n[ 2 ] multiplicar\n[ 3 ] maior\n[ 4 ] novos números\n[ 5 ] sair do programa')) if escolha == 1: print(f'A soma é {n1+n2}') elif escolha == 2: print(f'O resultado da multiplicação é {n1*n2}') elif escolha == 3: if n1 > n2: print(f'O número maior é {n1}') else: print(f'O número maior é {n2}') elif escolha == 4: n1 = int(input('Digite o novo primeiro número: ')) n2 = int(input('Digite o novo segundo número: ')) else: print('Opção inválida, tente novamente!') print('Finalizando o programa!')""" #Crie um programa que leia dois valores e mostre um menu na tela: #[ 1 ] somar #[ 2 ] multiplicar #[ 3 ] maior #[ 4 ] novos números #[ 5 ] sair do programa #Seu programa deverá realizar a operação solicitada em cada caso. n1 = int(input('Escolha o primeiro valor: ')) n2 = int(input('Escolha o segundo valor: ')) opcao = 0 while opcao != 5: print('O que você quer fazer? \n[ 1 ] somar \n[ 2 ] multiplicar \n[ 3 ] maior \n[ 4 ] novos números\n[ 5 ] sair do programa') opcao = int(input('Escolha a opção: ')) if opcao == 1: soma = (n1+n2) print(f'A soma é {soma} \n=======================') elif opcao == 2: multiplicar = (n1*n2) print(f'A multiplicação é {multiplicar} \n=======================') elif opcao == 3: if n1 > n2: print(f'O número maior é {n1} \n=======================') else: print(f'O número maior é {n2} \n=======================') elif opcao == 4: n1 = int(input('Escolha um novo número: ')) n2 = int(input('Escolha um novo número: ')) elif opcao ==5: print('Você saiu do programa') else: print('Opçao inválida, digite um1 número de 1 a 5: \n=======================')
false
8df83445e494e7137b3ba2721433d7d63ba88244
tudormihaieugen/DataScientistCourse
/Courses/Course1.py
1,530
4.21875
4
# # Type of variables # a = 5 # print(type(a)) # # # Power: ** (double * operator) # print(2 ** 3) # =8 # # # Area of circle # pi = 3.14159 # radius = 2.2 # area = pi * (radius ** 2) # # # string concat # hi = "Hello there" # name = "Ana" # greet = hi + " " + name # print(greet) # # three_times = name * 3 # print(three_times) # # # variables conversion # x = 5 # x_str = str(x) # print("my favorite number is:", x) # print("my favorite number is:" + " " + x_str) # # # input # text = input("Type something... ") # print(text * 5) # number = int(input("Type a number...")) # print(number * 5) # # # comparison # x = float(input("x = ")) # y = float(input("y = ")) # if x == y: # print("x and y are equal") # if y != 0: # print("x / y =", x/y) # elif x < y: # print("x is smaller") # else: # print("y is smaller") # # # loops # n = 0 # while n < 5: # print(n) # n = n + 1 # # # scope # x = 3 # def scope(x): # a = 4 # x = x + 1 # print(a) # print(x) # # scope(x) # # # tuple # t = (2, 4, "a", 5) # len(t) # # # lists # L = [1, 2, 3, 4, "a", "b"] # print(len(L)) # print(L[5]) # L.append(5) # print(L) # L1 = [3, 4, 5, 10] # L2 = L + L1 # print(L2) # L.extend([10, 11]) # works like append # L.remove(2) # removes the element with the value of 2 # del(L[2]) # delete the element with the index of 2 # # # conversion # s = "I<3 ds" # print(list(s)) # # sentence = "I love Python and Datascience" # print(sentence.split(" ")) # # L = ["P", "y", "th", "o", "n"] # print(''.join(L))
false
d1608587d280fd2ed388aaa71241f856421f7648
todaatsushi/python-data-structures-and-algorithms
/algorithms/sort/insertion_sort.py
1,025
4.40625
4
""" Insertion sort. Sort list/array arr of ints and sort it by iterating through and placing each element where it should be. """ def insertion_sort(arr, asc=True): """ Inputs: - Arr - list of ints to be sorted. Assumes arr is longer than 1 element long. - asc - True for ascending, False for descending """ final = list(arr) # Iterate through list for i in range(1, len(final)): current = final[i] # Compare current to every preceding element for n in range(0, i): # If smaller, place before and remove current from current location if current < final[n]: final.pop(i) final.insert(n, current) break # Reverse list for descending order if not asc: return [final[i] for i in range(len(final) - 1, -1, -1)] return final import random unsorted = [random.randint(0, 1000) for i in range(0, 10)] print(insertion_sort(unsorted)) print(insertion_sort(unsorted, False))
true
453fc0baf0163d84d4b0b26ffa2164826bec58cf
fslichen/Python
/Python/src/main/java/Set.py
207
4.34375
4
# A set is enclosed by a pair of curly braces. # Set automatically removes duplicate elements. set = {'apple', 'pear', 'banana', 'apple'} print(set) if 'apple' in set: print('Apple is in the set.')
true
41bac5b84ed3e03a44faaf6a3cdcb39649e8ba0d
shubhamjain31/demorepo
/Python_practice/Practice_10.py
330
4.125
4
from collections import Counter str = 'In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.' count = Counter(str).most_common(10) print(count)
true
6ad58d5245bad903ce16648f61d2a31508fe8b51
Siddardha21/NUMERICAL-METHODS
/Differentiation_3_Formula.py
2,974
4.15625
4
from sympy import Symbol, Derivative import sympy as sym import math x = Symbol('x') # Given the Initial Conditions. fx = x**3 - 6*x**2 + 11*x - 6 x_gvn = 0.5 h = 0.5 # ---------------------------------------------- x_plus_h = x_gvn + h x_minus_h = x_gvn - h # --------------------------------------------- deriv = Derivative(fx, x) dfx = deriv.doit() # Derivative of F(x) print("\nF'(x) =",dfx) dfx_true_value = float(dfx.subs({x:x_gvn})) # Substituting the value in F'(x). print("True Value of F'(x) =",dfx_true_value) fx_value = float(fx.subs({x:x_gvn})) # f(x) value print("\nF(x) = F(",x_gvn,") =",fx_value) fx_plus_h = float(fx.subs({x:x_plus_h})) # f(x+h) value print("F(x+h) = F(",x_plus_h,") =",fx_plus_h) fx_minus_h = float(fx.subs({x:x_minus_h})) # f(x-h) value print("F(x-h) = F(",x_minus_h,") =",fx_minus_h) # 1st Order Differentiation ------------------------------------------------- fd_one = (fx_plus_h - fx_value)/h print("\n1st Order Forward Diff = ",fd_one) fe_one = (dfx_true_value - fd_one)/dfx_true_value*100 print("Forward Error = ",abs(fe_one),"%") bd_one = (fx_value - fx_minus_h)/h print("\n1st Order Backward Diff = ",bd_one) be_one = (dfx_true_value - bd_one)/dfx_true_value*100 print("Backward Error = ",abs(be_one),"%") cd_one = (fx_plus_h - fx_minus_h)/(2*h) print("\n1st Order Centered Diff = ",cd_one) ce_one = (dfx_true_value - cd_one)/dfx_true_value*100 print("Backward Error = ",abs(ce_one),"%") # 2nd Order Differentiation ------------------------------------------------------ print('----------------------------------') cd_two = (fx_plus_h - 2*fx_value + fx_minus_h)/(h**2) print("2nd Order Centered Diff = ",cd_two) # ce_two = (dfx_true_value - cd_two)/dfx_true_value*100 # print("Backward Error = ",abs(ce_two),"%") # 3rd Order Differentiation ------------------------------------------------------ print('----------------------------------') x_plus_2h = x_gvn + 2*h x_minus_2h = x_gvn - 2*h # ------------------- # fx_value = float(fx.subs({x:x_gvn})) # f(x) value print("F(x) = F(",x_gvn,") =",fx_value) # fx_plus_h = float(fx.subs({x:x_plus_h})) # f(x+h) value print("F(x+h) = F(",x_plus_h,") =",fx_plus_h) fx_minus_h = float(fx.subs({x:x_minus_h})) # f(x-h) value print("F(x-h) = F(",x_minus_h,") =",fx_minus_h) fx_plus_2h = float(fx.subs({x:x_plus_2h})) # f(x+2h) value print("F(x+2h) = F(",x_plus_2h,") =",fx_plus_2h) fx_minus_2h = float(fx.subs({x:x_minus_2h})) # f(x-2h) value print("F(x-2h) = F(",x_minus_2h,") =",fx_minus_2h) # --------------------- cd_three = (fx_plus_2h - 2*fx_plus_h + 2*fx_minus_h - fx_minus_2h)/(2*h**3) print("---------\n3rd Order Centered Diff = ",cd_three) # 4th Order Differentiation ------------------------------------------------------ cd_four = (fx_plus_2h - 4*fx_plus_h + 6*fx_value - 4*fx_minus_h + fx_minus_2h)/(h**4) print("---------\n4th Order Centered Diff = ",cd_four)
false
d39fd6e5e119959aa925225efd01b46abce8243f
tt-n-walters/uria-python
/adv_dictionaries/adv_dictionaries.py
696
4.125
4
hair_colours = { "Arthur": "ginger", "Bill": "ginger", "Charlie": "ginger", "Draco": "blond", "Errol": "feathers", "Fred": "ginger", "George": "ginger", "Harry": "black" } # Accessing items that may not exist print(hair_colours.get("Lucius", "Hair colour not found.")) # keys, values, items print(hair_colours.keys()) print(hair_colours.values()) print(hair_colours.items()) for name, colour in hair_colours.items(): print(name + " has " + colour + " hair.") from collections import defaultdict letters = "TXkOcdCuAaBayuYYPvroKvmYcDCnbYYzugdElReslpflGYEdgAqCWuDsBMQpdjSBUVoVFFJdkJbOrUlKYcROxyDzkDTmmbHYdVXxDcifsoUcoKrgtuwMjXAjIABbOHcL" times_appeared = defaultdict(int) for letter in letters: times_appeared[letter] = times_appeared[letter] + 1 print(times_appeared)
false
ad947590ffed3dcfe73337bea8ffe8e68b6910ef
sky-bot/Interview_Preparation
/Educative/Permutation_in_a_String_hard/sol.py
1,806
4.40625
4
# Given a string and a pattern, find out if the string contains any permutation of the pattern. # Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations: # abc # acb # bac # bca # cab # cba # If a string has ‘n’ distinct characters it will have n!n! permutations. # Example 1: # Input: String="oidbcaf", Pattern="abc" # Output: true # Explanation: The string contains "bca" which is a permutation of the given pattern. # Example 2: # Input: String="odicf", Pattern="dc" # Output: false # Explanation: No permutation of the pattern is present in the given string as a substring. # Example 3: # Input: String="bcdxabcdy", Pattern="bcdyabcdx" # Output: true # Explanation: Both the string and the pattern are a permutation of each other. # Example 4: # Input: String="aaacb", Pattern="abc" # Output: true # Explanation: The string contains "acb" which is a permutation of the given pattern. # Sol def find_permutation(str, pattern): print("str => {} pattern => {}".format(str, pattern)) pat_dict = dict() for i in pattern: if i in pat_dict.keys(): pat_dict[i] = pat_dict[i] + 1 else: pat_dict[i] = 1 for i in range(len(str)): if str[i] in pat_dict.keys(): pat_dict[str[i]] = pat_dict[str[i]]-1 else: return False for i in pat_dict.values(): if i != 0: return False return True def main(): str = "bcdxabcdy" pattern = "bcdyabcdx" for i in range(len(str)): if i+len(pattern)<=len(str): temp_val = find_permutation(str[i:i+len(pattern)], pattern) # print(temp_val) if temp_val: return True return False print(main())
true
a1ff9c00543721443a49cee0b3c9ecbe1741f740
sky-bot/Interview_Preparation
/Educative/LinkedList/Palindrome_LinkedList.py
1,343
4.125
4
class Node: def __init__(self, value, next=None): self.value = value self.next = next def is_palindromic_linked_list(head): slow = head fast = head tail = None count = 1 middle = None while(fast.next and fast.next.next): slow = slow.next fast = fast.next.next count += 2 if fast.next: count+=1 fast = fast.next tail = fast middle = slow reverse_the_list(slow) first = head last = tail i=0 count = int(count/2) while(i<count): if first.value != last.value: return False first = first.next last = last.next i = i + 1 return True return count def reverse_the_list(head): # display(head) prev = head cur = head.next temp = None while(cur): temp = cur.next cur.next = prev prev = cur cur = temp # head.next = None return prev def main(): head = Node(2) head.next = Node(4) head.next.next = Node(6) head.next.next.next = Node(4) head.next.next.next.next = Node(2) print("Is palindrome: " + str(is_palindromic_linked_list(head))) head.next.next.next.next.next = Node(2) print("Is palindrome: " + str(is_palindromic_linked_list(head))) main()
true
179576de0a97a3a2957d7cdcedf93d53e203869e
Switters37/helloworld
/lists.py
758
4.25
4
#print range(10) #for x in range (3): # print 'x=',x #names = [['dave',23,True],['jeff',24,False],['mark',21,True]] #for x in names: # print x #print names [1][1] #numbers in square brackets above will index over in the list. So in this case, the list will index over 1 list, and then 1 space in the second list. # thus giving 24, which is the second value in the second list. #use a number sign to comment out stuff.... #for x in range (3): # y = x**2 # print y # for-loops: # so for the range(4) [0, 1, 2, 3], for i = the range(4), it will loop and produce the array of [0, 1, 4, 9] #x = range (4) #y = [i**2 for i in x] #print y y = list() for x in range(3): y.append(x**2) print y y = [i+3 for i in y] print y
true
1260a7849253566d81c9d5c8d0836f3c20b71bac
NihalSayyad/python_learnigs
/51DaysOfCode/017/Enumerator_in_py.py
221
4.15625
4
''' In we are interested in an index of a list, we use enumerate. ''' countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] for index, i in enumerate(countries): print(f"country {i} is at index {index}")
true
465380ce5b174a59245d0691e8394672def2d779
devanbenz/PythonStuff
/MIT OCW/LectureSix/lectureSix.py
2,618
4.40625
4
## Recursion - # **Process of repeating items in a self-similar way # '''Droste effect''' - picture within a picture # Divide and conquer # Decrease and conquer # Algorithmically we reduce a problem into smaller parts in #order to solve problems # Semantically it is a function that is called within the body #of the function def recursionOne(x): x -= 1 if x == 1: print('Done!') return x else: recursionOne(x) print(x) #recursionOne(5) ##Recursive reduction # a * a == a + a + a..... + a # for recursion this is a + a * (b - 1) def mult(a,b): if b == 1: return a else: return a + mult(a, b -1) #print(mult(3,4)) def factorial(n): if n == 1: return 1 else: print(n) return n * factorial(n-1) #print(factorial(5)) #when writing recursive code once we hit the base case think #of the function back tracking and performing the return sequences #backwards ##MATHEMATICAL INDUCTION #If I want to prove a statement is true on all integers #I prove it is true for the smallest value of n and 'n+1' def fib(x): if x == 0 or x == 1: return 1 else: return fib(x - 1) + fib(x - 2) print(fib(5)) def isPalindrome(s): def toChars(s): s = s.lower() ans = '' for c in s: if c in 'abcdefghijklmnopqrstuvwxyz': ans = ans + c return ans def isPal(s): if len(s) <= 1: return True else: return s[0] == s[-1] and isPal(s[1:-1]) return isPal(toChars(s)) ############################################### #Dictionary data-type #way to store data in a key:value pair grades = {'Devan': ['A', 6.001], 'Carl': ['B',2.001]} print(grades) for e in grades.values(): print(e) def lyricFrequencies(lyrics): myDict = {} for word in lyrics: if word in myDict: myDict[word] += 1 else: myDict[word] = 1 #####CHAPTER 4.3 IN ICS##### #Recursion is made up of two parts a base case that specifies the result #for a special case and a recursive (inductive) case #A classic Inductive definition : # 1! = 1 <---- base case # (n + 1)! = (n + 1) * n! # Due to when you are back tracking in recursion we need to have the base case as the first possible #return value and work towards it, so in factorial so n is going to be multiplied by n - 1 during each turn #Lets do a factorial recursion def factorialICS(n): if n == 1: return 1 else: return n * factorialICS(n - 1) #print(factorialICS(n=20)) #Basic summation recursion - adds from n to 1 def summation(n): if n == 1: return 1 else: return n + summation(n - 1) print(summation(10))
true
bb17f15513d9e77d524d9396beabff0470adab0e
sejalg1019/project-97
/guessingGame.py
559
4.3125
4
import random print("Number guessing game!") number = random.randint(1,9) chances = 0 print("Guess a number between 1-9 (You only have 5 chances to guess correctly)") while chances < 5: guess = int(input("Enter your guess:")) if guess == number: print("Congratulations, you won!") break elif guess < number: print("Your guess is too low, guess again", guess) else: print("Your guess is too high, guess again", guess) chances += 1 if not chances < 5: print("You lose! The number is: ", number)
true
4158ddec48858494fea09623a6b935450fd87f4b
afatihirkli/data_science_practice
/physics-class.py
1,139
4.15625
4
# Codecademy Data Science Python Exercise : Getting Ready for Physics Class # train_mass = 22680 train_acceleration = 10 train_distance = 100 impact_mass = 1 ## Q1 ## def f_to_c(f_temp): c_temp = (f_temp - 32) * 5 / 9 return c_temp ## Q2 ## f100_in_celsius = f_to_c(100) print(f100_in_celsius) ## Q3 ## def c_to_f(c_temp): f_temp = c_temp * (9/5) +32 return f_temp ## Q4 ## c0_in_fahrenheit = c_to_f(0) print(c0_in_fahrenheit) ## Q5 ## def get_force(mass, acceleration): return mass * acceleration ## Q6 ## train_force = get_force(train_mass, train_acceleration) print(train_force) ## Q7 ## print("The GE train supplies ", train_force, " Newtons of force.") ## Q8 ## def get_energy(mass, c = 3*10**8): return mass * c ## Q9 ## impact_energy = get_energy (impact_mass) ## Q10 ## print("A 1kg impact supplies ", impact_energy, " Joules.") ## Q11 ## def get_work(mass, acceleration, distance): return get_force(mass, acceleration) * distance ## Q12 ## train_work = get_work(train_mass, train_acceleration, train_distance) ## Q13 ## print("The GE train does ", train_work, " Joules of work over ", train_distance, " meters.")
false
80be44b952612926061985837d905e02fea488ac
binoytv9/Think-Python-by-Allen-B-Downey--Exercises
/8th-chapter/12.py
529
4.15625
4
def rotate_word(word,num): new='' for letter in word: if letter.isupper(): ordr=ord(letter)+num if ordr > 90: new+=chr(ordr-26) elif ordr < 65: new+=chr(ordr+26) else: new+=chr(ordr) elif letter.islower(): ordr=ord(letter)+num if ordr > 122: new+=chr(ordr-26) elif ordr < 97: new+=chr(ordr+26) else: new+=chr(ordr) else: print '\n\n\tinvalid word\n\n' return None return new print rotate_word('binoy',3) print rotate_word('cheer',7) print rotate_word('melon',-10)
false
1442cba523d9be466df5c0b11c09430da9ee2fde
sudhamshu091/Sorting-Techniques
/tim_sort.py
1,606
4.125
4
#sorting technique used by python in sorted() #fastest sorting technique #hybrid technique #based on insertion sort and bubble sort RUN = 32 """ insertion_sort function""" def insertionSort(arr,left,right): for i in range(left+1, right,1): temp = arr[i] j = i-1 while(arr[j]>temp and j>= left): arr[j+1] = arr[j] j -=1 arr[j+1] = temp """merge function""" def merge(arr,l,m,r): len1 = m - l + 1 len2 = r - m left = [] right = [] for i in range(0, len1, 1): left.append(arr[l + i]) for i in range(0, len2, 1): right.append(arr[m + 1 + i]) i = 0 j = 0 k = l while (i < len1 and j < len2): if (left[i] <= right[j]): arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 while (i < len1): arr[k] = left[i] k += 1 i += 1 while (j < len2): arr[k] = right[j] k += 1 j += 1 """ tim_sort function""" def tim_sort(arr,n): for i in range(0,n,RUN): insertionSort(arr, i, min((i + 31), (n - 1))) size = RUN while(size<n): left = 0 while(left < n): mid = left + size-1 right = min((left + 2*size - 1), (n-1)) merge(arr, left, mid, right) left +=2*size size = 2*size """main function""" if __name__ == "__main__": list1 = [1,3,5,7,8,5,3,1,0] tim_sort(list1,len(list1)+1) print(list1)
false
19bc00052a6249859a29cbd57b55e1ac2821c175
Nsk8012/TKinter
/1.py
426
4.34375
4
from tkinter import * #import Tkinter lib window = Tk() #Creating window window.title("Print") #Giving name of the window l1 = Label(window, text="Hello World!",font=('Arial Bold',50)) #label is used to print line of text on window gui l1.grid(column=0,row=0) #grid set the position of label on window window.geometry('500x500') #sets the size of window window.mainloop() #Runs the event loop untill x button is clicked
true
83119fa61c4da7286fba5de1586d2df40a5bcb7f
SW1992/100-Days-Of-Code
/Forty-third-day.py
1,271
4.625
5
# Day Forty Three # Python Range & Enumerate # range() function # the python range function can be thought of as a form of loop # it loops through & produces list of integer values # it takes three parameters, start, end & step # if you specify only an end value, it will loop up to the number (exclusive) # starting from 0, as start defaults at 0 if it's omitted for w in range(3): print("w range:", w) # prints 0, 1, 2 # if you specify an start value & end value it will start from start & loop up to end for x in range(0,3): print("x range:", x) # prints 0, 1, 2 # if you specify a step value, it will use that to decide the incremental difference between each number it produces for y in range(3,15,3): print("y range:", y) # prints 3, 6, 9, 12 # you can also count downwards with range, aswell as upwards for z in range(5,-1,-1): print("z range:", z) # prints 5, 4, 3, 2, 1, 0 # enumerate() function # the native enumerate function will display the associative index & item, for each item in a list fruits = ["Apple", "Mango", "Orange"] print("Enumerate:", end = " ") for item in enumerate(fruits): print(item, end = " ") # Enumerate: (0, "Apple") (1, "Mango") (2, "Orange")
true
c3a81e455e13111e4f3d39301727e1b8a20ae464
codingandcommunity/intro-to-python
/beginner/lesson7/caesar.py
494
4.15625
4
''' Your task is to create a funcion that takes a string and turns it into a caesar cipher. If you do not know what a caesar cipher is, here's a link to a good description: https://learncryptography.com/classical-encryption/caesar-cipher ''' def makeCipher(string, offset): # Your code here return string s = input("Enter a string to be turned into a cipher: ") o = input("Enter an offset for your cipher: ") cipher = makeCipher(s, o) print("You're new cipher is: {}".format(cipher))
true
b530e63e5290ca037d25b0d547fee2f963b91a26
codingandcommunity/intro-to-python
/beginner/lesson7/piglatin.py
655
4.28125
4
''' Write a function translate that translates a list of words to piglatin ex) input = ['hello', 'world'] output = ['ellohay', 'orldway'] remember, you can concactenate strings using + ex) 'hello' + ' ' + 'world' = 'hello world' ''' def translate( ): # Your code here phrase = (input("Enter a phrase -> ")).split() # takes a string as input and splits it into a list of strings; ex: hello world becomes ['hello', 'world'] piglatin = translate(phrase) # write the function translate print(' '.join(piglatin)) # takes a list of strings and make them into one string with a space between each item; ex: ['hello', 'world'] becomes 'hello world'
true
6f5b4a260426de11c79686367fc4d854d3d2c10a
carlosarli/Learning-python
/old/str_methods.py
458
4.21875
4
name = 'lorenzo' #this is a string object if name.startswith('lo'): print('yes') if name.find('lo') != -1: #.find finds the position of a string in a string, and returns -1 if it's not succesfull in finding the string in the string print('yes') delimiter = '.' namelist = ['l', 'o', 'r', 'e', 'n', 'z', 'o'] print('imma the new florida: ', delimiter.join(namelist))#.join substitutes commas and spaces between strings in a list with a given string
true
e7ce661b78ca1fb34ee44f025de804f0fc4cec29
AkshayGulhane46/hackerRank
/15_string_split_and_join.py
512
4.28125
4
# Task # You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. # # Input Format # The first line contains a string consisting of space separated words. # # Output Format # Print the formatted string as explained above. def split_and_join(line): a = line.split(" ") # a is converted to a list of strings. a = "-".join(a) return a # write your code here if __name__ == '__main__': line = input() result = split_and_join(line) print(result)
true
625abfb54078aa303cfc1e7d9f358a0fc1b6528d
kolodziejp/Learning-Part-1
/Smallest_Value.py
343
4.28125
4
# Finding the smallest value in a range small = None print ("Let us look for the smallest value") for number in [21, 42, 13, 53, -5, 2, 56, 119, -23, 99, 2, 3, 9, 87]: if small is None: small = number elif number < small: small = number print (small, number) print ("The smallest number is", small)
true
c5f22e3b607f0af078e1506feb80d6d81041862c
kolodziejp/Learning-Part-1
/Ex_5_1.py
480
4.1875
4
# entered numbers are added, counted and average computed count = 0 total = 0 while True: num = input ("Enter a number: ") if num == "done": break try: fnum = float(num) #convert to floating number except: print ("Invalid Data!") continue # should only consider valid numbers continue and ignore error count = count + 1 total = total + fnum avg = total / count print (total, count,avg)
true
eb94db21432787349ffa87f4d1c7ea2da625a8c4
Savirman/Python_lesson01
/example04.py
1,065
4.25
4
# Программе нахождения наибольщей цифры в числе # Пользователь вводит целое число произвольной длины while True: number = int(input("Введите целое положительное число: ")) # Проверяем введенное число. Если оно отрицательное, то выдаем сообщение об этом и просим ввести положительное число if number < 0: print("Вы ввели отрицательное число. Введите положительное число") else: number = str(number) break # Запускаем цикл с поиском цифр в числе от 9 до 0 counter = 9 while counter >= 0: biggest_digit = '9' biggest_digit = str(counter) if biggest_digit in number: print("Самая большая цифра в числе: {}".format(biggest_digit)) break counter = counter - 1
false
e925e128a91016a06b95f1c88d3c9a7f8c1628f8
ApurvaW18/python
/Day 3/Q2.py
377
4.25
4
''' 2.From a list containing ints, strings and floats,make three lists to store them separately. ''' l=['aa','bb','cc',1,2,3,1.45,14.51,2.3] ints=[] strings=[] floats=[] for i in l: if (type(i))==int: ints.append(i) elif (type(i))==float: floats.append(i) else: strings.append(i) print(ints) print(strings) print(floats)
true
0ccd24589fd5833bd9dd205fe3bf34a315f533eb
ApurvaW18/python
/Day 6/Q2.py
678
4.125
4
''' 2.Write program to implement Selection sort. ''' a = [16, 19, 11, 15, 10, 12, 14] i = 0 while i<len(a): s=min(a[i:]) print(s) j=a.index(s) a[i],a[j] = a[j],a[i] i=i+1 print(a) def selectionSort(array, size): for step in range(size): min_idx = step for i in range(step + 1, size): if array[i] < array[min_idx]: min_idx = i # put min at the correct position (array[step], array[min_idx]) = (array[min_idx], array[step]) data = [-2, 45, 0, 11, -9] size = len(data) selectionSort(data, size) print('Sorted Array in Ascending Order:') print(data)
true
09e8a1f3816fcdbeba2632c33b93a7dbfc46d46d
JulietaCaro/Programacion-I
/Trabajo Practico 2/Ejercicio 11.py
830
4.40625
4
#11. Intercalar los elementos de una lista entre los elementos de otra. La intercalación #deberá realizarse exclusivamente mediante la técnica de rebanadas y no se creará #una lista nueva sino que se modificará la primera. Por ejemplo, si lista1 = [8, 1, 3] #y lista2 = [5, 9, 7], lista1 deberá quedar como [8, 5, 1, 9, 3, 7]. #FUNCIONES def intercalarListas(listaA, listaB): 'Intercala dos listas mediante la tecnica de rebanadas' listaC = [] listaC = listaA + listaB listaC[::2] = listaA listaC[1::2] = listaB return listaC def main(): 'Programa principal' lista1 = [8,1,3] lista2 = [5,9,7] print("Lista 1:",lista1) print("Lista 2:",lista2) lista3 = intercalarListas(lista1,lista2) print("Lista intercalada:",lista3) #PROGRAMA PRINCIPAL main()
false
2b957856684056fdad48fc84aa6edafa70598df9
JulietaCaro/Programacion-I
/Trabajo Practico 4/Ejercicio 13.py
1,539
4.1875
4
# 13.Escribir un programa que cuente cuántas veces se encuentra una subcadena dentro de otra cadena, sin diferenciar # mayúsculas y minúsculas. Tener en cuenta que los caracteres de la subcadena no necesariamente deben estar en forma # consecutiva dentro de la cadena, pero sí respetando el orden de los mismos. # FUNCIONES def buscarSubcadena(cad, subCad): cad = cad.lower() subCad = subCad.lower() i = 0 cont = 0 #indice de la cadena ind = -1 #Si es -1 el metodo find no encontró el caracter while i != -1: carac = 0 #Inicio el indice de la subcad en 0 y las condiciones se ejecutan mientras sea menor a la cant de elementos #de la subcad y encuentre el caracter while carac < len(subCad) and i != -1: #busco un caracter de la subcadena desde la posicion que se indica con ind+1 y me quedo con el #indice del caracter encontrado en la cadena ind = cad.find(subCad[carac], ind+1) #cambio el indice de la subcadena por el siguiente carac = carac + 1 #ind = indice de la palabra encontrada i = ind if carac == len(subCad): cont = cont + 1 return cont def main(): cadena = input("Ingrese una cadena: ") subCad = input("Ingrese la subcadena: ") contador = buscarSubcadena(cadena, subCad) print(f"Cantidad de veces que {subCad} aparece en {cadena}: {contador}") # PROGRAMA PRINCIPAL main()
false
9fef6a6753a7fc3f577a737d811d5179fe0d1435
oski89/udemy
/complete-python-3-bootcamp/my-files/advanced_lists.py
398
4.25
4
l = [1, 2, 3, 3, 4] l.append([5, 6]) # appends the list as an item print(l) l = [1, 4, 3, 3, 2] l.extend([5, 6]) # extends the list print(l) print(l.index(3)) # returns the index of the first occurance of the item l.insert(2, 'inserted') # insertes at index print(l) l.remove(3) # removes the first occurance print(l) l.remove('inserted') l.sort() # removes the first occurance print(l)
true
800319d01235504239ac6011970662a0b9dc7a76
Tduncan14/PythonCode
/pythonGuessGame.py
834
4.21875
4
#Guess my number ## #The computer picks a random number between 1 and 100 #The player tries to guess it and the computer lets #The player on guessing the numner is too high, too low # or right on the money import random print("\tWelcome to 'Guess My Number'!") print("\n I'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible. \n") # set the intial values the_number = random.randint(1,4) guess = int(input("Take a guess: ")) tries = 1 # guessing loop while guess != the_number: if guess > the_number: print("guess lower") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 print("You guessed it! The number was", the_number) print("And it only took you:" ,tries ," tries") input("press enter to exit the code")
true
78aa63ab11d675859c5f683cb02bbb1541bfbd18
Arlisha2019/Calculator-EvenOdd-FizzBuzz
/EvenOdd.py
215
4.28125
4
user_number = int(input("Enter a number: ")) def even_or_odd(): if(user_number % 2 == 0): print("You entered an even number!") else: print("You have entered an odd number!") even_or_odd()
false
4741931113c64c098b5d06449bceafc4949bab1f
seen2/Python
/workshop2019/secondSession/function.py
415
4.1875
4
# without parameter def func(): a, b = 10, 20 c = a+b print(c) # func() def funcP(a, b): ''' takes two integer and print its sum ''' c = a+b print(c) # default argument comes last in parameter sequence. def funcDefaultP(a, b=1, c=1): ''' takes three integer and print its sum or print default sum ''' c = a+b print(c) # funcP(10, 30) funcDefaultP(10, 30)
true
e90d7ae10791ac7dd407d940ed3e444770d087c1
seen2/Python
/bitwiseOperators/bitwiseLogicalOperators.py
406
4.125
4
def main(): a=2 # 2=ob00000010 b=3 # 3=ob00000011 # logical operations print(f"{a} AND {b}={a&b}") print(f"{a} OR {b}={a|b}") # takes binary of a and flips its bits and add 1 to it. # whilch is 2 's complement of a print(f"2's complement of {a} ={~a}") # exclusive OR (X-OR) print(f"{a} X-OR {b}={a^b}") if __name__=="__main__": main()
true
78c62c8944c81c10e80cc64673aab404ff0f4bd5
GeorgeMohammad/Time2ToLoseWeightCalculator
/WeightLossCalculator.py
1,081
4.3125
4
####outputs the amount of time required to lose the inputted amount of weight. #computes and returns the amount of weight you should lose in a week. def WeeklylbLoss(currentWeight): return (currentWeight / 100) #Performs error checking on a float. def NumTypeTest(testFloat): errorFlag = True while(errorFlag): try: float(testFloat) except: testFloat = input("Invalid Type. Enter a decimal") else: testFloat = float(testFloat) errorFlag = False return testFloat weight2Lose = input("How many pounds do you want to lose: ") weight2Lose = NumTypeTest(weight2Lose) #Gathering weight input weight = -1 while (weight < weight2Lose): weight = input("How much do you weigh: ") weight = NumTypeTest(weight) weightLost = 0 weekCount = 0 #Subtracts weight week by week. while ((weightLost < weight2Lose) and (weight2Lose <= weight)): weightLost += WeeklylbLoss(weight) weight -= WeeklylbLoss(weight) weekCount += 1 print("The weight loss will take", weekCount, "week/s.")
true
ff05aa7d85f2d7a414accb8daaebe64663c4606a
clementin-bonneau-riera/mathsPythonLycee
/pythagore/pythagoreCheck.py
677
4.15625
4
print("Vérifier la réciproque de Pythagore.") print("Ne marche qu'avec des nombres entiers.") a = input("longueur du côté A: ") b = input("Longueur du côté B: ") hyp = input("Longueur du côté C (hypoténuse): ") a_b_lenght_square = pow(int(a), 2) + pow(int(b), 2) # additionne les carrés des côtés A et B if a_b_lenght_square == pow(int(hyp), 2): # si la sommes edes carrés est strictement égale au carré de l'hypothénuse print("La réciproque de Pythagore est vérifiée. Le triangle est rectangle.") else: # sinon, donc si elle n'est pas égale print("La réciproque de Pythagore n'est pas vérifiée. Le triangle n'est pas rectangle.") # Clémentin Bonneau-Riera
false
24115f34af7e2162c885ffc7f22ec1f76550fc56
Goku0858756/rzzzwilson
/talks/recursion_1/code/fibonacci.py
1,228
4.21875
4
#!/usr/bin/env python """ Recursive solution for the Fibonacci function. With and without memoisation. Usage: fibonacci <integer> """ import time def fibonacci(n): """Return the 'n'th Fibonacci number.""" if n == 0: return 0 if n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) fib_memo = {0:0, 1:1} def fibonacci_memo(n): """Return the 'n'th Fibonacci number with memoisation.""" global fib_memo # so we can update fib_memo if n not in fib_memo: fib_memo[n] = fibonacci_memo(n-1) + fibonacci_memo(n-2) return fib_memo[n] if __name__ == '__main__': import sys if len(sys.argv) != 2: print __doc__ sys.exit(10) try: number = int(sys.argv[1]) except ValueError: print __doc__ sys.exit(10) print ' fibonacci(%d) =' % number, sys.stdout.flush() start = time.time() result = fibonacci(number) delta = time.time() - start print '%d took %9.6fs' % (result, delta) print 'fibonacci_memo(%d) =' % number, sys.stdout.flush() start = time.time() result = fibonacci_memo(number) delta = time.time() - start print '%d took %9.6fs' % (result, delta)
false
de97d0426ab25ac5d7ff658ba6903b8770ab4382
Goku0858756/rzzzwilson
/talks/recursion_1/code/hanoi.py
1,132
4.21875
4
#!/usr/bin/env python """ Recursive solution to the "Tower of Hanoi" puzzle. [http://en.wikipedia.org/wiki/Tower_of_Hanoi] Usage: hanoi <number_of_disks> """ def hanoi_original(n, src, dst, tmp): """Move 'n' disks from 'src' to 'dst' using temporary 'tmp'.""" if n == 1: print('move %s to %s' % (src, dst)) # move single disk to 'dst' else: hanoi_original(n-1, src, tmp, dst) # move n-1 to 'tmp' hanoi_original(1, src, dst, tmp) # move 1 to 'dst' hanoi_original(n-1, tmp, dst, src) # finally move n-1 from 'tmp' to 'dst' def hanoi(n, src, dst, tmp): """Move 'n' disks from 'src' to 'dst' using temporary 'tmp'.""" if n > 0: hanoi(n-1, src, tmp, dst) # move n-1 to 'tmp' print('move %s to %s' % (src, dst)) # move single disk to 'dst' hanoi(n-1, tmp, dst, src) # finally move n-1 to 'dst' if __name__ == '__main__': import sys if len(sys.argv) != 2: print __doc__ sys.exit(10) try: number = int(sys.argv[1]) except ValueError: print __doc__ sys.exit(10) hanoi(number, 'A', 'B', 'C')
false
b7df58e4d45c16fc5fe35e2ba028378c9cf227d8
rcreagh/network_software_modelling
/vertex.py
606
4.125
4
#! usr/bin/python """This script creates an object of class vertex.""" class Vertex(object): def __init__(self, name, parent, depth): """Initialize vertex. Args: name: Arbitrary name of the node parent: Parent vertex of the vertex in a tree. depth: Number of edges between the vertex itself and the root vertex. """ self.name = name self.parent = parent self.depth = depth def __repr__(self): """Change print format to show name, parent and depth of vertices.""" return '\n' + str( self.name) + ', ' + str(self.parent) + ', ' + str(self.depth)
true
b722454a775c2345a4ee44f318e38341872cb479
gittangxh/python_learning
/ds_seq.py
330
4.21875
4
shoplist=['apple', 'mango','carrot','banana'] name = 'swaroop' print('item -1 is', shoplist[-1]) print('character 0 is', name[0]) print('item 0 to 2 are:', shoplist[0:2]) print('item 1 to -1 are:', shoplist[1:-1]) print('reverse all items:', shoplist[-1::-1]) print('reverse the string:', name[-1::-1]) print(shoplist[::-1])
false
8c2e4e8110aa53f0b5ecffce8b2b80ba2bbeb1aa
gittangxh/python_learning
/io_input.py
364
4.3125
4
def reverse(text): return text[::-1] def is_palindrome(text): newtext='' for ch in text: if ch.isalpha() and ch.isnumeric(): newtext+=ch.lower() return newtext == reverse(newtext) something = input('Enter text:') if is_palindrome(something): print('yes, it is palindrome') else: print('no, it is not a palindrome')
true
6a6468dc982e95af935fbd3a353794d55da10dc2
emiliobort/python
/Practica1/Programas/Ejercicio2.py
1,118
4.125
4
# Visualizar un cuadrado con su vértice inferior izquierdo en el origen from turtle import * #Inicializamos la pantalla pantalla = Screen() pantalla.setup(425,225) pantalla.screensize(400,200) #Asignamos las variables x e y, y pedimos al usuario valores del lado x = 0 y = 0 lado = int(input("Dame el tamaño del lado: ")) #Inicializamos la tortuga tortuga = Turtle() tortuga.penup() tortuga.home() tortuga.pendown() #Dibujamos lado con sus coordenadas. coord_x = tortuga.xcor() coord_y = tortuga.ycor() tortuga.write(("({0},{1})").format(coord_x,coord_y)) tortuga.goto(lado,y) #Dibujamos lado con sus coordenadas. coord_x = tortuga.xcor() coord_y = tortuga.ycor() tortuga.write(("({0},{1})").format(coord_x,coord_y)) tortuga.goto(lado,lado) #Dibujamos lado con sus coordenadas. coord_x = tortuga.xcor() coord_y = tortuga.ycor() tortuga.write(("({0},{1})").format(coord_x,coord_y)) tortuga.goto(x,lado) #Dibujamos lado con sus coordenadas. coord_x = tortuga.xcor() coord_y = tortuga.ycor() tortuga.write(("({0},{1})").format(coord_x,coord_y)) tortuga.home() tortuga.hideturtle() pantalla.exitonclick()
false
20c13fa236de48a3a418bbac633f32554381c7c1
8589/codes
/python/my_test/interview/generator.py
504
4.125
4
''' show how to use generator, every generator is iteration, but not vice verse. ''' def yrange(n): # print n i = 0 # print i while i < n: # print i yield i i = i + 1 y_iter = yrange(10) # print y_iter.next() # print y_iter.next() for i in y_iter: print i # if __name__ == "__main__": # from minitest import * # only_test(yrange) # with test(yrange): # y_iter = yrange(3) # print y_iter.next() # print y_iter.next()
false
a5eaf5cc98c6aa37fbeb170cd98631833be34eaa
RavinduTharaka/COHDSE182F-001.repo
/01_ceaser.py
997
4.1875
4
def encrypt(string, shift): a = '' for char in string: if char.isalpha(): if char == ' ': a = a + char elif char.isupper(): a = a + chr((ord(char) + shift - 65) % 26 + 65) else: a = a + chr((ord(char) + shift - 97) % 26 + 97) else: print("Please enter characters") return a def decrypt(string, shift): a = '' for char in string: if char.isalpha(): if char == ' ': a = a + char elif char.isupper(): a = a + chr((ord(char) - shift - 65) % 26 + 65) else: a = a + chr((ord(char) - shift - 97) % 26 + 97) else: print("Please enter characters") return a print("Select your choice") c=input("e - Encript \nd - Decript\t") if c=='e': text = input("enter string: ") print("after encryption: ",encrypt(text, 3)) elif c=='d': text = input("enter string: ") print("after decryption: ",decrypt(text, 3)) else: print("Invalid Choice")
false
b54ece015da6564cd0c5c839f67149774f0e0888
niteshsrivats/IEEE
/Python SIG/Classes/Class 6/regularexp.py
2,377
4.375
4
# Regular expressions: Sequence of characters that used for # searching and parsing strings # The regular expression library 're' should be imported before you use it import re # Metacharacters: characters with special meaning # '.' : Any character "b..d" # '*' : Zero or more occurrences "bal*" # '+' : One or more occurrences "bal+" # '^' : Starts with "^bald" # '$' : Ends with "bald$" # '{}' : Exactly the specified number of occurrences "al{3}" # '()' : Capture and group # '|' : Either or "bald|ball" # '\' : Signals a special sequence "\d" # Special Sequences: A special sequence is a '\' followed by one of the # characters which has a special meaning # \d : Returns a match if string contains digits # \D : Returns a match if string DOES NOT contain digits # \s : Returns a match for a white space character # \S : Match for non white space character # \w : Match for word character(a-z,A-Z,0-9,_) # \W : Returns a match if it DOES NOT contain word characters # search function: Searches for first occurrence of pattern within a string. # Returns a match object if there is a match # Syntax: re.search(pattern,string) line = "Message from anjali@gmail.com to nitesh@gmail.com" mailId = re.search('\S+@\S+', line) print("The first mail id is at position:", mailId.start()) # If the pattern is not present it returns None line = "Message from anjali@gmail.com to nitesh@gmail.com @ 3:00" time = re.search("\d{2}:\d{2}", line) print(time) # Returns none as no such pattern # findall function: Returns a list containing all matches line = "Message from anjali@gmail.com to nitesh@gmail.com" mailId = re.findall('\S+@\S+', line) print(mailId) # Search for lines that start with From and have an at sign """ hand = open('example.txt') for line in hand: line = line.rstrip() if re.search('^From:.+@', line): print(line) """ # Escape characters: A way to indicate special characters by using backslash line = "I received $1000 as a scholarship" amount = re.findall("\$\d{4}", line) print(amount) # Since we prefix dollar sign with backslash it matches dollar sign and not # end of string
true
77f86f9689a16c3a8d9438a24b5d13b67bd6c6f0
alanvenneman/Practice
/Final/pricelist.py
614
4.125
4
items = ["pen", "notebook", "charge", "scissors", "eraser", "backpack", "cap", "wallet"] price = [1.99, .5, 4.99, 2.99, .45, 9.99, 7.99, 12.99] pricelist = zip(items, price) for k, v in pricelist: print(k, v) cart = [] purchase = input("Enter the first item you would like to buy: ") cart.append(purchase) second = input("Enter another item: ") cart.append(second) third = input("Enter one last item: ") cart.append(third) prices = [] for k, v in pricelist: if k in cart: prices.append(v) # print(v) total = 0 for p in prices: total += p # print(cart) # print(prices) print(total)
true
4e7693939c6098c938fce30f8915f19b80dc2ecd
SteveWalsh1989/Coding_Problems
/Trees/bst_branch_sums.py
2,265
4.15625
4
""" Given a Trees, create function that returns a list of it’s branch sums ordered from leftmost branch sums to the rightmost branch sums __________________________________________________________________ 0 1 / \ 1 2 3 / \ / \ 2 4 5 6 7 / \ / 3 8 9 10 Here there are 5 branches ending in 8,9,10,6,7 SO sums would be: 1+2+4+8 =15 1+2+4+9 = 16 1+2+5+10 = 18 1+3+6 = 10 1+3+7 = 11 result being : [15, 16, 18, 10, 11] __________________________________________________________________ - Need to keep runing total passed into recursive function, - when no more children it can be added to an array of branch values - Sum up values within the array __________________________________________________________________ Space and Time Complexity Space: O(N) - impacted by list of branch sums - impacted by recurisve nature of function Time: O(N) - need to traverse all nodes """ def get_branch_sum(root): """sums values of all branches within a Trees""" sums = [] branch_sum_helper(root, 0, sums) return sums def branch_sum_helper(node, total_sum, sums): # return if none if node is None: return # update branch total updated_sum = total_sum + node.value # check if need to continue if node.left is None and node.right is None: sums.append(updated_sum) return branch_sum_helper(node.left, updated_sum, sums) branch_sum_helper(node.right, updated_sum, sums) def main(): """ Main function""" # create Trees root = BinaryTree(1) root.left = BinaryTree(2) root.left.left = BinaryTree(4) root.left.left.left = BinaryTree(8) root.left.left.right = BinaryTree(9) root.left.right = BinaryTree(5) root.left.right.right = BinaryTree(10) root.right = BinaryTree(3) root.right.left = BinaryTree(6) root.right.right = BinaryTree(7) sums = get_branch_sum(root) print(f" The list of all sums of each branches within Trees is {sums}") # This is the class of the input binary tree. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None ''' Run Program ''' main()
true
a21b1e8a04826d5391cfa5eac83e0d4b12d22859
SteveWalsh1989/Coding_Problems
/Arrays/sock_merchant.py
634
4.3125
4
def check_socks(arr, length): """ checks for number of pairs of values within an array""" pairs = 0 # sort list arr.sort() i = 0 # iterate while i < (length - 1): # set values current = arr[i] next = arr[i + 1] # check if the same sock or different if next == current: pairs += 1 i += 2 else: i += 1 return pairs def main(): """ Main function""" arr = [2, 3, 3, 1, 2, 1, 4, 2, 2, 2, 1] res = check_socks(arr, len(arr) ) print(f"The array {arr} has {res} pairs") ''' Run Program ''' main()
true
70ed3e204149399b43259d4fa675d705cc4d9121
yueranwu/CP1404_prac06
/programming_language.py
946
4.125
4
"""CP1404/CP5632 Practical define ProgrammingLanguage class""" class ProgrammingLanguage: """represent a programming language""" def __init__(self, name, typing, reflection, year): """Initiate a programming language instance name: string, the name of programming language typing: string, the typing of programming language is dynamic or static reflection: string, year: """ self.name = name self.typing = typing self.reflection = reflection self.year = year def __str__(self): return "{}, {}, Reflection = {}, First appeared in {}".format(self.name, self.typing, self.reflection, self.year) def is_dynamic(self): """ returns True/False if the programming language is dynamically typed or not """ if self.typing == "Dynamic": return True else: return False
true
7804095933cc582dbff88b5369ed5d35f45e8c57
JosephZYU/Python-2-Intermediate
/27.Python Tutorial for Beginners 8: Functions.py
1,082
4.3125
4
# https://youtu.be/9Os0o3wzS_I def hello_func(name, host_name='Alexa'): return (f'How are you {name}! This is your host {host_name} speaking\nHow may I help you today?') # return (f'How are you! {name}\nHow are you twice! {name}') # return (f'How are you! {name} ' * 3) print(hello_func) print() print(hello_func('Joseph')) print() print(hello_func('Joseph').upper()) print() print(hello_func('Joseph').title()) print() """ 🧠 func(*args, **kwargs): 🧠 args = arguments 🧠 kwargs = key-word arguments 🧭 allowing us to accept an arbitrary number of positional or keyword argument 😎 Since we don't know upfront how many keyword or positional arguments there will be 👀 arbitrary number (any number) """ def student_info(*args, **kwargs): return (f'{args}\n{kwargs}') # print(student_info('Math', 'Science', f_name='Jason', l_name='Lee', age=23)) courses = ['Math', 'Science'] info = {'f_name': 'Jason', 'l_name': 'Lee', 'age': 23} # 👀 ALWAYS remember to place single* and double** in front of each! print(student_info(*courses, **info))
false
e5cd322b04d126d2283dd2be8caed59f1985ef17
Xuehong-pdx/python-code-challenge
/caesar.py
667
4.1875
4
from string import ascii_lowercase as lower from string import ascii_uppercase as upper size = len(lower) message = 'Myxqbkdevkdsyxc, iye mbkmuon dro myno' def caesar(message, shift): """ This function returns a caesar (substitution) cipher for a given string where numbers, punctuation, and other non-alphabet characters were passed through unchanged. Letter case is preserved. """ l_shift = {c:lower[(i+shift)%size] for i,c in enumerate(lower)} u_shift = {c:upper[(i+shift)%size] for i,c in enumerate(upper)} l_shift.update(u_shift) sf = [l_shift.get(c, c) for c in message] return ''.join(sf) print(caesar(message, 16))
true
cde0d233f7e9d53bd8e501fae8365584dadb402b
VitBomm/Algorithm_Book
/1.12/1_1_is_multiple.py
355
4.3125
4
# Write a short Python function, is_multiple(n, m), that takes two integer values and returns True if n # is a multiple of m, n = mi for some integer i, and False otherwise # def is_multiple(n, m): if n/m % 1 == 0: return True return False n = eval(input("Input your n: ")) m = eval(input("Input your m: ")) print(str(is_multiple(n,m)))
true
e1fb035396c96114dbc2b78f81f28faec0d812f0
GustavoBonet/pythonexercicios
/ex.038.py
270
4.15625
4
um = int(input('Primeiro número:')) dois = int(input('Segundo número:')) if um == dois: print('Os dois valores são IGUAIS') elif um > dois: print('O primeiro é maior') elif dois > um: print('O segundo é maior') else: print('Erro, tente novamente.')
false
45f2179deaa14abbb287fd2d956e12ce6bd3733e
Liam876/USEFUL_STUFF
/repos/factory.py
1,877
4.15625
4
from abc import ABC, abstractmethod import math from itertools import accumulate import random class Shape(ABC): @abstractmethod def perimeter (): pass @abstractmethod def area(): pass def __str__(self): return "This is a shape" class Triangle (Shape): def __init__ (self,sides): self.sides = sides ac = accumulate(sides) for i in range(len(sides)): if i == len(sides) -1: self.s = next(ac) else: next(ac) def area(self): s = self.s / 2 sid = self.sides print(sid) return math.sqrt(s * (s - sid[0]) * (s - sid[1]) *(s - sid[2])) def perimeter (self): return self.s def __str__(self): return super().__str__() + f" And also a triangle with sides : {self.sides}" class Rectangle(Shape): def __init__(self,side): self.side = side def area (self): return self.side * self.side def perimeter (self): return 4 * self.side def __str__(self): return super().__str__() + f" And also a rectangle with side: {self.side}" class Shape_Factory (): def __init__(self): self.shapes = [] while True: name = input("Please type desired shape name:") if name == "Rectangle": self.shapes.append(Rectangle(random.randint(1, 10))) elif name == "Triangle": self.shapes.append(Triangle([random.randint(20,30) for i in range(3)])) else: break def __str__(self): return str([str(i) for i in self.shapes]) Triangle tr = Triangle([5,12,13]) rec = Rectangle(3) sf = Shape_Factory() print(sf)
false
ce4a2f26dff9b7aae290e08ea4e02a6054f4e650
SBCV/Blender-Addon-Photogrammetry-Importer
/photogrammetry_importer/utility/type_utility.py
385
4.15625
4
def is_int(some_str): """ Return True, if the given string represents an integer value. """ try: int(some_str) return True except ValueError: return False def is_float(some_str): """ Return True, if the given string represents a float value. """ try: float(some_str) return True except ValueError: return False
true
52ae20a0eadb2ac4e684ef4920f6c105d6187a6d
jeffsnguyen/Python
/Level 1/Homework/Section_1_3_Functions/Exercise 5/variance_dof.py
1,003
4.40625
4
''' Type: Homework Level: 1 Section: 1.3: Functions Exercise: 4 Description: Create a function that calculates the variance of a passed-in list. This function should delegate to the mean function (this means that it calls the mean function instead of containing logic to calculate the mean itself, since mean is one of the steps to calculating variance). ''' from mean_passedin_list import mean # Return variance of a list, with degree of freedom def variance(list, degOfFreedom = 1): mean_list = mean(list) # Calculate mean l_temp = [(i - mean_list)**2 for i in list] # Initialize list of (x - mean)**2 return sum(l_temp) / (len(list) - degOfFreedom) def main(): # Initialize a list l = [1, 2, 3, 8, 9, 10] # Population Variance dof = 0 print('Variance = ' + str(variance(l, dof))) # Sample Variance dof = 1 print('Variance = ' + str(variance(l, dof))) ####################### if __name__ == '__main__': main()
true
55568741e62e8f4da5189d2582f58916995cd8a3
jeffsnguyen/Python
/Level_3/Homework/Section_3_2_Generators_101/Exercise_1/num_iterable.py
883
4.46875
4
# Type: Homework # Level: 3 # Section: 3.2: Generators 101 # Exercise: 1 # Description: Contains the tests to iterate through a list of numbers # Create a list of 1000 numbers. Convert the list to an iterable and iterate through it. ####################### # Importing necessary packages from random import random, seed ####################### ############################################### def main(): # Set seed to generate pseudo-random number seed(1) # Generate list l using list comprehension l = [random() for i in range(0, 1000)] # Convert to an iterable listIter = iter(l) # iterate through list l, Exception Stop Iteration will be raise when it reaches the end of the list. while True: print(next(listIter)) ############################################### ####################### if __name__ == '__main__': main()
true
a6948de57520137916bd17f153148e83f51d3f35
jeffsnguyen/Python
/Level 1/Homework/Section_1_5_Dicts_and_Sets/Exercise 2/name_usuk.py
2,581
4.21875
4
''' Type: Homework Level: 1 Section: 1.5 Dicts and Sets Exercise: 2 Description: Create two sets: Set 1 should contain the twenty most common male first names in the United States and Set 2 should contain the twenty most common male first names in Britain (Google it). Perform the following: a. Find the first names that appear in both sets. b. Find the first names that appear in the United States set, but not Britain. c. Find the first names that appear in the Britain set, but not United States. d. Use a set comprehension to create a subset of names that have more than five letters. ''' def main(): # Set 1 contain the twenty most common male first names in the United States name_set_us = set(['James', 'John', 'Robert', 'Michael', 'William', 'David', 'Richard', 'Charles', 'Joseph', 'Thomas', 'Christopher', 'Daniel', 'Paul', 'Mark', 'Donald', 'George', 'Kenneth', 'Steven', 'Edward', 'Brian']) # Set 1 contain the twenty most common male first names in the United Kingdom name_set_uk = set(['Noah', 'Oliver', 'Leo', 'Archie', 'Alfie', 'Logan', 'Oscar', 'George', 'Freddie', 'Charlie', 'Harry', 'Arthur', 'Jacob', 'Muhammad', 'Jack', 'Thomas', 'Henry', 'James', 'William', 'Joshua']) # Find first names that appear in both sets using intersection name_usuk = name_set_us.intersection(name_set_uk) print('First names that appear in both US and UK:\n', name_usuk) # Find the first names that appear in the United States set, but not UK using difference name_us_notuk = name_set_us.difference(name_set_uk) print('First names that appear in US but not UK:\n', name_us_notuk) # Find the first names that appear in the Britain set, but not United States. name_uk_notus = name_set_uk.difference(name_set_us) print('First names that appear in UK but not US:\n', name_uk_notus) # Use a set comprehension to create a subset of names that have more than five letters. # Create a set of unique names from US and UK using union name_us_plus_uk = name_set_us.union(name_set_uk) # Set comprehension to filter only names that have more than five letters name_fiveletters = {name for name in name_us_plus_uk if len(name) > 5} print('Names that have more than five letters from US and UK:\n', name_fiveletters) ####################### if __name__ == '__main__': main()
true
92209793e197de9c33c0d3f6c219455620de4282
jeffsnguyen/Python
/Level 1/Homework/Section_1_6_Packages/Exercise 2/anything_program/hello_world_take_input/take_input_triangle/take_input/take_input.py
332
4.25
4
''' Type: Homework Level: 1 Section: 1.1 Variables/ Conditionals Exercise: 4 Description: Create a program that takes input from the user (using the input function), and stores it in a variable. ''' def take_input(): var = input('Input anything: ') # Take user's input and store in variable var print(var)
true
c0f0fbf101b3a648ef5dfd24d760fdcca394c260
jeffsnguyen/Python
/Level_3/Homework/Section_3_3_Exception_Handling/Exercise_2/divbyzero.py
1,719
4.4375
4
# Type: Homework # Level: 3 # Section: 3.3: Exception Handling # Exercise: 2 # Description: Contains the tests for handling div/0 exception # Extend exercise 1) to handle the situation when the user inputs something other than a number, # using exception handling. If the user does not enter a number, the code should provide the user # with an error message and ask the user to try again. # Note that this is an example of duck typing. ####################### # Importing necessary packages ####################### ############################################### ############################################### def main(): # Program takes 2 input from user, handle input exception # If no input exception, handle division by 0 exception and print result of division # Also catch other unknown exceptions # 1st try-except block to handle input try: x = float(input('Input a number: ')) # take input and convert to float y = float(input('Input a number: ')) except ValueError as valueEx: # handle non-number exception, for example: string print(valueEx) pass except Exception as ex: # handle other unknown exception print('Unknown error: ' + str(ex)) pass else: # 2nd try-except block to handle division try: print('Division result = ', x/y) except ZeroDivisionError as divZeroEx: # handle div/0 exception print(divZeroEx) pass except Exception as ex: # handle other unknown exception print('Unknown error: ' + str(ex)) ############################################### ####################### if __name__ == '__main__': main()
true
a1f40e6da78edd81dadd58f19b78490f33aeb4ea
jeffsnguyen/Python
/Level_4/Lecture/string_manipulation_lecture.py
1,778
4.46875
4
# string manipulation lecture def main(): s = 'This is my sample string' # indexing print(s[0]) print(s[-1]) print() # slicing print(s[0:2:3]) print(s[:3]) print() # upper: create a new string, all uppercase print(s.upper()) print() # lower: create a new string, all lowercase print(s.lower()) print() # count the letter in the string, case sensitive print(s.count('t')) print(s.count('is')) print(s.count('x')) # if none found, return 0 print() # s.index() return the index of the sub string inside the string, first occurence only print(s.index('is')) #print(s.index('x')) # get value error print() print(s.find('x')) # similar to index but return -1 if not found s = ' This is my spaced string ' print(s) print(s.strip()) # strip the spaces inside the string print() s = ' This is my spaced string....' print(s) print(s.strip('.')) # strip the specified value from the string # Dealing with file path f = 'C:\\Users\\username\\desktop\\filename.txt' print(f) f.split('\\') # split each directory in the path print(f.split('\\')) l = f.split('\\') print(l) print('\\'.join(l)) # join each directory in the list with the \\ g = f.rsplit('\\', 1) # split the file name from the rest of the directory print(g) print() # Replace print(s) print(s.replace(' ', '')) print(s.replace('T', 'l')) print() s = 'My new string' print(s.startswith(('My'))) # check starting portion of string print(s.startswith(('The'))) print(s.endswith(('ng'))) print(s.endswith(('ng1'))) ####################### if __name__ == '__main__': main()
true
5afb09b8eb3c629211076857bfc6b1f859d28f46
jeffsnguyen/Python
/Level_4/Lecture/string_formatting_lecture.py
1,421
4.21875
4
# string formatting lecture def main(): age = 5 print('Ying is %i years old'%age) # format flag i = integer print('Ying is %f years old'%age) # format flag f = float print('Ying is %.1f years old' % age) # format flag f = floag, truncate it 1 decimal place print('Ying is %e years old' % age) # format flag e= exponential print('%s is 5 years old' %'Ying') # format flag s = string print() name = 'Ying' age = 5 print('%s is %i years old'%(name, age)) # multiple format flag print() print('{0} is {1} years old'.format(name, age)) # better because python figure out the type # better because python figure out the type, descriptive and use keyword arg so order doesn't matter print('{name} is {age} years old'.format(name = name, age = age)) print('Same is {:.1f} years old'.format(5.75)) # specify decimal print('Same is {:,.1f} years old'.format(100000)) # specify decimal print() # f string name = 'Julie' print(f'Hello {name}') height = 61.23 print(f'{round(height)}') # evaluate any expression inside the f string print() heightDict = {'Julie': 65, 'Sam':75, 'Larry':64} name = 'Sam' print(f'{name} is {heightDict[name]} inches') # floating point precision using f string print(f'{name} is {heightDict[name]:,.2f} inches') ####################### if __name__ == '__main__': main()
true
8251f87063be621d270c55e3c3849c758ae2f28b
jeffsnguyen/Python
/Level 1/Homework/Section_1_3_Functions/Exercise 1/day_of_week.py
1,320
4.3125
4
''' Type: Homework Level: 1 Section: 1.3: Functions Exercise: 1 Description: Write a function that can print out the day of the week for a given number. I.e. Sunday is 1, Monday is 2, etc. It should return a tuple of the original number and the corresponding name of the day. ''' import sys # Look up the day number and return matching tuple of weekday name and the day number def day_of_week(x): # Set up week and day reference list week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] day = [1, 2, 3, 4, 5, 6, 7] # Return the tuple of (week, day) in the zip object if day match the lookup variable return [(week, day) for week, day in zip(week, day) if day == x] def main(): print('This program takes an integer value and return a matching tuple of weekday, day number') try: # Exception handling if user enter anything that is not an integer from 1 -> 7 lookup_day = int(input('Enter an integer from 1 -> 7: ')) if lookup_day not in range(1,8): sys.exit('Must be a integer from 1 -> 7') except: sys.exit('Must be a integer from 1 -> 7') # Display the matching tuple print(day_of_week(lookup_day)) ####################### if __name__ == '__main__': main()
true
0e7639bd5f7fc3b37bfa0cdbcd091fd94121e827
jeffsnguyen/Python
/Level_3/Homework/Section_3_2_Generators_101/Exercise_4/fibonacci.py
2,283
4.46875
4
# Type: Homework # Level: 3 # Section: 3.2: Generators 101 # Exercise: 4 # Description: Contains the tests to modified fn() method to generate Fibonacci sequence # Modify the Fibonacci function from Exercise 1.3.2 to be a generator function. Note that the function # should no longer have any input parameter since making it a generator allows it to return the # infinite sequence. Do the following: # a. Display the first and second values of the Fibonacci sequence. # b. Iterate through and display the next 100 values of the sequence. ####################### # Importing necessary packages ####################### ############################################### # Fibonacci generator def fn(): fibo = [] # Initialize empty list num = -1 # Set count value # For the first 2 values, yield specific constants and append to empty list # For subsequent values, yield using fibonacci formula and append to list while True: num += 1 if num == 0: yield 0 fibo.append(0) elif num == 1: yield 1 fibo.append(1) else: yield fibo[num-2] + fibo[num-1] fibo.append(fibo[num-2] + fibo[num-1]) ############################################### def main(): # Testing block 1 # Scenario: # This block will: # 1. Test modified fn() function by printing out the first 2 value of Fibonacci sequence # 2. Test modified fn() function by printing out the next 100 value of Fibonacci sequence ############################################### # Test 1 # 1.1 Test modified fn() function by printing out the first 2 value of Fibonacci sequence print('Test 1.1. Printing out the first 2 value of Fibonacci sequence') fib = fn() print(next(fib)) print(next(fib)) print() # 1.2 Test modified fn() function by printing out the next 100 value of Fibonacci sequence (#3 to #102) print('Test 1.2. Test modified fn() function by printing out the next 100 value of Fibonacci sequence (#3 to #102)') for i in range (0,101): print(next(fib)) i +=1 ############################################### ####################### if __name__ == '__main__': main()
true
5792af4a3d9edc774bba3c6cf4bb7cba31ef6b0d
jeffsnguyen/Python
/Level_3/Homework/Section_3_1_Advanced_Functions/Exercise_1/test_hypotenuse.py
1,140
4.375
4
# Type: Homework # Level: 3 # Section: 3.1: Advanced Functions # Exercise: 1 # Description: This contains the method to test the hypotenus of a right triangle # Create a stored lambda function that calculates the hypotenuse of a right triangle; it should take # base and height as its parameter. Invoke (test) this lambda with different arguments. # Importing necessary packages ####################### from math import sqrt def main(): # Testing block # Scenario: # This block will: # 1. Test the calcHypotenuse lambda function ############################################### # Test 1.1 # Scenario: Test the calcHypotenuse method to calculate the hypotenuse of a right triangle using lambda function. print('Test 1.1') calcHypotenuse = lambda base, height: sqrt(base**2 + height**2) print(calcHypotenuse(3, 4)) print(calcHypotenuse(20, 21)) print(calcHypotenuse(119, 120)) print(calcHypotenuse(696, 697)) print(calcHypotenuse(4059, 4060)) print() ############################################### ####################### if __name__ == '__main__': main()
true
4f999f411dc875269cba559dcdfdcc478f3bdd7b
BrandonOdiwuor/Problem-Solving-With-Algorithms-and-Data-Structures
/queue/queue.py
691
4.125
4
class Queue: def __init__(self): self.queue_list = [] def is_empty(self): ''' Returns a boolean indicating if the Queue is empty Wost Case Complexity O(1) ''' return self.queue_list == [] def size(self): ''' Returns the size of the Queue Worst Case Complexity O(1) ''' return len(self.queue_list) def enqueue(self, item): ''' Adds an adds and element to the end of the Queue Worst Case Complexity O(1) ''' self.queue_list.insert(0, item) def dequeue(self): ''' Removes the firt item from the Queue Wost Case Complexity O(1) ''' return self.queue_list.pop()
true
61ee1f89ea4b3f3e0862c729f4bce4f91d96148a
BrandonOdiwuor/Problem-Solving-With-Algorithms-and-Data-Structures
/sorting-and-searching/sorting/insertion_sort.py
575
4.375
4
def insertion_sort(lst): ''' Sorts a list in ascending order according to Insertion Sort algorithm Time Complexity O(N^2) ''' for index in range(1, len(lst)): item = lst[index] i = index while i > 0 and item < lst[i - 1]: lst[i] = lst[i - 1] i = i - 1 lst[i] = item return lst def main(): assert(insertion_sort([54, 26, 93, 17, 77, 31, 44, 55, 20]) == [17, 20, 26, 31, 44, 54, 55, 77, 93]) assert(insertion_sort([5, 1, 4, 6, 3, 8, 7, 2]) == [1, 2, 3, 4, 5, 6, 7, 8]) print('Test Pass') if __name__ == '__main__': main()
false
5def4ffc1d4aa1f09363d0a3d3e86661085c23b0
damingus/CMPUT174
/weather1.py
407
4.4375
4
#This program sees whether 2 inputted temperatures are equal or not #assign 'a' to the first temperature we ask for and 'b' for the next a = input("What is the first temperature? ") b = input("What is the second temperature? ") #we convert 'a' into a string from an integer a = str(a) b = str(b) if a == b: print(a + " and " + b + " are equal!") else: print(a + " and " + b + " are NOT equal!")
true
3bb05110f4e61837f3033087526ee6f96e418f8d
andrew1236/python
/organism population calculator.py
864
4.1875
4
#ask user for number of intital organisms, the average increases of organisms, and how many days to calcualte def calculate_organism_population(): organisms=int(input('Enter number of organisms:')) average_increase =int(input('Enter average daily increase:')) days=int(input('Enter number of days to multiply:')) counter=days-days+1 days=days-days+1 print('DAY APPROXIMATE POPULATION') print('-------------------------------') while counter<=10: organisms=organisms*(1+average_increase/100) if days==1: organisms=organisms-.600 print(days," ", format(organisms, '.0f')) if days>1 and days<10: print(days," ", format(organisms, '.3f')) if days==10: print(days," ", format(organisms, '.3f')) days+=1 counter+=1
true
e03234ead130d80f81f623ad279e8a1987578390
Muhammadtawil/Python-Lessons
/set-part1.py
822
4.3125
4
# ----------------------------- # -- Set -- # --------- # [1] Set Items Are Enclosed in Curly Braces # [2] Set Items Are Not Ordered And Not Indexed # [3] Set Indexing and Slicing Cant Be Done # [4] Set Has Only Immutable Data Types (Numbers, Strings, Tuples) List and Dict Are Not # [5] Set Items Is Unique # ----------------------------- # Not Ordered And Not Indexed mySetOne = {"Mark", "edwen", 100} print(mySetOne) # print(mySetOne[0]) # Slicing Cant Be Done mySetTwo = {1, 2, 3, 4, 5, 6} # print(mySetTwo[0:3]) # Has Only Immutable Data Types # mySetThree = {"Osama", 100, 100.5, True, [1, 2, 3]} # unhashable type: 'list' mySetThree = {"Osama", 100, 100.5, True, (1, 2, 3)} print(mySetThree) # Items Is Unique mySetFour = {1, 2, "Mark", "Edwen", "Mark", 1} print(mySetFour)
true
2f9b3ee9e458ca2e53599ca5a3a1befd90d04268
dshipman/devtest
/part_2_6.py
621
4.25
4
""" Write a short docstring for the function below, so that other people reading this code can quickly understand what this function does. You may also rename the functions if you can think of clearer names. """ def create_step_function(start_time, end_time, value): """ Create a step function that takes a single input ('time'), and returns <value> if that input is between start_time and end_time (inclusive), otherwise 0.0 """ def step_function(time): if start_time <= time <= end_time: y = value else: y = 0.0 return y return step_function
true
d91fc95f364e491f76c5c341aa5d777caa2c1911
AmirMoshfeghi/university_python_programming
/Functions/wine_house.py
1,549
4.46875
4
# Working with Functions # Making a house wine project # Wine Temperature must be closely controlled at least most of the time. # The program reads the temperature measurements of the wine container # during the fermentation process and tells whether the wine is ruined or not. def main(): # Get number of measurements from the user number = int(input("Enter the number of measurements: ")) # The entered number should not be negative or zero if number <= 0: print("The number of measurements must be a positive number.") # Check the status of the wine if check_temperature(number): print("Your wine is ready.") def check_temperature(number): # count -> steps start from one, # alarm -> for checking if two numbers in a row are out in range, # per -> for count percentage count = 1 alarm = 0 per = 0 # calculate 10% of total number of measurements percent = number * 0.1 while count <= number: temp = int(input("Enter the temperature {}: ".format(count))) # Check if the measured number is in acceptable range if temp not in range(20, 26): alarm += 1 per += 1 else: alarm = 0 # Go to next step count += 1 # Wine is ruined if 2 measurements in a row # or 10% of total inputs are out of range if alarm == 2 or per > percent: print("The wine is ruined") break # if everything went fine else: return True main()
true
f6e66580b128af7d4d0f757ec2a1062eb40001c0
baha312/chapter4_task7
/task7.py
735
4.1875
4
# Implement Students room using OOP: # Steve = Student("Steven Schultz", 23, "English") # Johnny = Student("Jonathan Rosenberg", 24, "Biology") # Penny = Student("Penelope Meramveliotakis", 21, "Physics") # print(Steve) # <name: Steven Schultz, age: 23, major: English> # print(Johnny) # <name: Jonathan Rosenberg, age: 24, major: Biology> class Student: def __init__(self, name, age, major): self.name = name self.age = age self.major = major def output(self): return "name: ",self.name, "age: ",str(self.age), "major: ", self.major st1 = Student("Steven Schultz", 23, "English").output() st2 = Student("Jonathan Rosenberg", 24, "Biology").output() st3 = Student("Penelope Meramveliotakis", 21, "Physics").output() print(" ".join(st1)) print(" ".join(st2)) print(" ".join(st3))
false
7fd2ed27b7956cf58308ab4832b503f4668fc8f3
brunopurper/Python-Curso-em-Video
/ex022.py
728
4.125
4
#Exercício Python 22: Crie um programa que leia o nome completo de uma pessoa e mostre: # – O nome com todas as letras maiúsculas e minúsculas. # # – Quantas letras ao todo (sem considerar espaços). # # – Quantas letras tem o primeiro nome. nome = str(input("Digite seu nome: ")).strip() nomeup= nome.upper() nomelow= nome.lower() nomefatia = nome.split() nomefatia = len(nomefatia[0]) + len(nomefatia[1]) primeiro_nome = nome.split() primeiro_nome = len(primeiro_nome[0]) print(f""" ============================================= O seu nome em letras maisculas é {nomeup} e minisculas é {nomelow}: Seu nome completo tem {len(nome) - nome.count(' ')} letras, e somente seu primeiro nome tem {primeiro_nome} """)
false
ae430661d281a65275da7d7230c35096d68c593e
Jayu8/Python3
/assert.py
636
4.125
4
""" It tests the invariants in a code The goal of using assertions is to let developers find the likely root cause of a bug more quickly. An assertion error should never be raised unless there’s a bug in your program. assert is equivalent to: if __debug__: if not <expression>: raise AssertionError """ # Asserts a = 5 # checks if a = 5 assert(a == 5) # uncommenting the below code will throw assertion error #assert(a == 6) def KelvinToFahrenheit(Temperature):   assert (Temperature >= 0),"Colder than absolute zero!"   return ((Temperature-273)*1.8)+32 print KelvinToFahrenheit(273) print int(KelvinToFahrenheit(505.78))
true
b2d675b96a26428a9bd8695a2425a1d0f09dfe59
netteNz/Python-Programming-A-Concise-Introduction
/problem2_5.py
1,296
4.21875
4
'''Problem 2_5: Let's do a small simulation. Suppose that you rolled a die repeatedly. Each time that you roll the die you get a integer from 1 to 6, the number of pips on the die. Use random.randint(a,b) to simulate rolling a die 10 times and printout the 10 outcomes. The function random.randint(a,b) will generate an integer (whole number) between the integers a and b inclusive. Remember each outcome is 1, 2, 3, 4, 5, or 6, so make sure that you can get all of these outcomes and none other. Print the list, one item to a line so that there are 10 lines as in the example run. Make sure that it has 10 items and they are all in the range 1 through 6. Here is one of my runs. In the problem below I ask you to set the seed to 171 for the benefit of the auto-grader. In this example, that wasn't done and so your numbers will be different. Note that the seed must be set BEFORE randint is used. problem2_5() 4 5 3 1 4 3 5 1 6 3 Problem 2_5:''' import random def problem2_5(): """ Simulates rolling a die 10 times.""" # Setting the seed makes the random numbers always the same # This is to make the auto-grader's job easier. random.seed(171) # don't remove when you submit for grading for r in range(0,10): print(random.randint(1,6)) #print(problem2_5())
true
f3db3ba1af9a34c6b223dd1d4d0e55c99e1319fe
prudhvireddym/CS5590-Python
/Source/Python/ICP 2/Stack Queue.py
852
4.15625
4
print("Enter Elements of stack: ") stack = [int(x) for x in input().split()] con ="yes" while con[0]=="y": ans = input("Enter 0 for push\n1 for pop\n2 to print stack\n3 for Top most element : ") while ans == "0": a = int(input("Enter the element to append")) stack.append(a) print(stack) con =input("Do you want to continue y or n") break while ans == "1": print("Stack element poped is:") print(stack.pop()) con = input("Do you want to continue y or n") break while ans == "2": print("Stack elements are:") print(stack) con = input("Do you want to continue y or n") break while ans == "3": print("The stop of the stack is: ") print(stack[-1]) con = input("Do you want to continue y or n") break
true
2853c45cb2b7883d73a62a288916aa026c6db2be
aligol1/beetroot111
/lesson37.py
1,421
4.59375
5
"""Task 1 Create a table Create a table of your choice inside the sample SQLite database, rename it, and add a new column. Insert a couple rows inside your table. Also, perform UPDATE and DELETE statements on inserted rows. As a solution to this task, create a file named: task1.sql, with all the SQL statements you have used to accomplish this task""" import sqlite3 db = sqlite3.connect('task0111.sql') sql = db.cursor() #создание табл sql.execute("""CREATE TABLE IF NOT EXISTS users(userid INT PRIMARY KEY, first_name TEXT, lastname TEXT); """) db.commit() #переименование табл sql.execute(""" ALTER TABLE users RENAME TO usersdb """) db.commit() #добавление новой колоны sql.execute(""" ALTER TABLE usersdb ADD COLUMN 'nickname''TEXT' """) db.commit() #добавление данных sql.execute(""" INSERT INTO usersdb VALUES (1,"Igor","Ivanov","kokshka"); """) db.commit() sql.execute(""" INSERT INTO usersdb VALUES (2,"Oleg","Petrov","Frider"); """) db.commit() sql.execute(""" INSERT INTO usersdb VALUES (3,"John","Malkovic","NEO"); """) db.commit() #удаление записи sql.execute(""" DELETE FROM usersdb WHERE userid = '1' """) db.commit() #редактирование sql.execute(""" UPDATE usersdb SET first_name = 'Ira' WHERE userid = '2' """) db.commit() for value in db.execute("SELECT * FROM usersdb"): print(value)
true
69eaa079f4ad20db8c19efa7af08adcdcf174e1a
aligol1/beetroot111
/lesson14.py
2,240
4.65625
5
"""Lesson 14 Task 1 Write a decorator that prints a function with arguments passed to it. NOTE! It should print the function, not the result of its execution! For example: "add called with 4, 5" def logger(func): pass @logger def add(x, y): return x + y @logger def square_all(*args): return [arg ** 2 for arg in args]""" def logger(func): def wraper(*args): print(f'{func.__name__} called with {args}') return func(*args) return wraper @logger def add(*args): return sum(arg for arg in args) @logger def square_all(*args): return [arg ** 2 for arg in args] if __name__ == '__main__': add(5, 6) square_all(8, 9, 10) """Lesson 14 Task 2 Write a decorator that takes a list of stop words and replaces them with * inside the decorated function def stop_words(words: list): pass @stop_words(['pepsi', 'BMW']) def create_slogan(name: str) -> str: return f"{name} drinks pepsi in his brand new BMW!" assert create_slogan("Steve") == "Steve drinks * in his brand new *!" """ StopList = ['pepsi', 'BMW'] def stop_words(words:list): def replace_word(func): def wraper(*args): text = func(*args) for word in words: text = text.replace(word, '*') return text return wraper return replace_word @stop_words(StopList) def create_slogan(name: str, lastname: str): return f'{name} {lastname} drinks pepsi in his brand new BMW!' if __name__ == '__main__': print(create_slogan('john','Wick')) """Task 3 Write a decorator `arg_rules` that validates arguments passed to the function. A decorator should take 3 arguments: max_length: 15 type_: str contains: [] - list of symbols that an argument should contain If some of the rules' checks returns False, the function should return False and print the reason it failed; otherwise, return the result. ``` def arg_rules(type_: type, max_length: int, contains: list): pass @arg_rules(type_=str, max_length=15, contains=['05', '@']) def create_slogan(name: str) -> str: return f"{name} drinks pepsi in his brand new BMW!" assert create_slogan('johndoe05@gmail.com') is False assert create_slogan('S@SH05') == 'S@SH05 drinks pepsi in his brand new BMW!' """
true
7a85e32340f82247a32ce4f234a38b3b30c9ffc9
Gwinew/To-Lern-Python-Beginner
/Tutorial_from_Flynerd/Lesson_4_typesandvariables/Task2.py
817
4.21875
4
# Make a list with serial movie # # Every serial movie should have assigned rate in scale 1-10. # Asking users what they serial movie want to see. # In answer give they rate value. # Asking user if they want to add another serial movie and rate. # Add new serial movie to the list. # -*- coding: utf-8 -*- dictserial={"Soprano":6,"Dark":9,"Rick and Morty":8} listserial=list(dictserial.keys()) name=input("Hi! Welcome to serial movie data base.\n{}\nWhat serial movie want to see?\n".format(listserial)) enter=input("{} have {} in rating.\nPress Enter to continue".format(name, dictserial[name])) newserial=input("If you want to add a new serial to the list, write the name\n") newserialrate=input("Write a rate\n") dictserial[newserial]=newserialrate print("This is a new list with rates:\n{}".format(dictserial))
true
b1077695d8b814286c878c7d809eed423b224f72
Gwinew/To-Lern-Python-Beginner
/Tutorial_from_Flynerd/Lesson_3_formattingsubtitles/Task2.py
886
4.125
4
# -*- coding: utf-8 -*- # # Create a investment script which will have information about: # -Inital account status # -Annual interest rate # -The number of years in the deposit # # Result show using any formatting text. # enter=input("Hi! This is Investment script.\nI want to help you to count your money impact at the end of the deposit.\nPlease press \"Enter\" to continue") name=input("Before we start, I would like to ask you, what\'s your name?\n") rate=float(input("Hi {}. Write what interest rate you want to have. (in percentage)\n".format(name))) inpu=float(input("Can you input initial account status? (in PLN)\n")) time=int(input("Please enter, how long you want to keep your money in deposit? (in month)\n")) ratep=rate/100 year=time/12 end=(inpu*time*ratep/12)+inpu print("{} you will have {:.4f} PLN after {} months ({:.1f} years) in deposit".format(name,end,time,year))
true
931c283cfe56acb0b02c9e26205980a3fda9f4ff
Gwinew/To-Lern-Python-Beginner
/Pluralsight/Intermediate/Unit_Testing_with_Python/1_Unit_Testing_Fundamentals/2_First_Test/test_phonebook.py
1,405
4.1875
4
"""Given a list of names and phone numbers. Make a Phonebook Determine if it is consistent: - no number is a prefix of another - e.g. Bob 91125426, Anna 97625992 - Emergency 911 - Bob and Emergency are inconsistent """ import unittest #class PhoneBook: # Right-click, choose Refactor, and choose Move... to phonebook.py # pass from phonebook import PhoneBook class PhoneBookTest(unittest.TestCase): def test_lookup_by_name(self): phonebook = PhoneBook() # Click alt+enter and choose a create new class phonebook.add("Bob", '12345') # PyCharm is highlight a word which needed to define -> click right ande choose 'Add method add() to class PhoneBook' number = phonebook.lookup("Bob") # Click 'Add method lookup() to class PhoneBook' self.assertEqual("12345", number) # To initiate test we need use to command line: # python -m unittest # error: AssertionError: '12345' != None # We can add unittest to PyCharm: # Click 'Add Configuration' # Click '+' # Choose Python test # Choose Unittest # Name configuration: Unittest # Add a path to script which we want to test (or folder if script using more files) # If test is failed then we see on the left yellow cross. # For Working interactively: An IDE like PyCharm # For Continues integration: A Command Line Test Runner
true
3816745c2b680faf5ed5b87fb6a9cc7503a5a818
351116682/Test
/20.py
572
4.25
4
#coding=utf-8 ''' 交换两个数的值 其实原理都是一样的,只不过Python可以借助于tuple,元组的形式来一次性的返回多个值 相对于其他编程语言而言,这真的很方便 ''' def change(a,b): temp = a a = b b = temp return a,b def exchange(a,b): a,b = b,a return a,b if __name__ == "__main__": a ,b = 1,2 print '原来的值:%d---%d'%(a,b) a,b = exchange(a,b) print '值交换后:%d---%d'%(a,b) c,d = change(a,b) print '值交换后:%d---%d'%(a,b) print type(change(a,b))
false
ee0eb65582ce9db9cc635038101221a257bbc5f6
Aa-yush/Learning-Python
/BMICalc.py
331
4.28125
4
weight = float(input("Enter your weight in kg : ")) height = float(input("Enter your height in meters : ")) BMI = weight / (height**2) if(BMI <= 18.5): print("Underweight") elif(BMI >18.5 and BMI <= 24.9): print("Normal weight") elif(BMI>24.9 and BMI<=29.9): print("Overweight") else: print("Obesity")
true
8a2edf5d14180fefe7c387a81465edb89c12eca0
rohit98077/python_wrldc_training
/24_read_write_text_files.py
816
4.375
4
''' Lesson 2 - Day 4 - read or write text files in python ''' # %% # read a text file # open the file for reading with open("dumps/test.txt", mode='r') as f: # read all the file content fStr = f.read() # please note that once again calling f.read() will return empty string print(fStr) # this will print the whole file contents # %% # load all lines into a list with open("dumps/test.txt", mode='r') as f: # load all the lines of the file into an array textLines = f.readlines() print(textLines) # %% # writing text to a file # with mode = 'w', old text will be deleted # with mode = 'a', the new text will be appended to the old text with open("dumps/test.txt", mode='w') as f: f.write("The first line\n") f.write("This is the second line\nThis the third line") # %%
true
b096fbd435e5058f59aa46d546a0a4ade727fa69
rohit98077/python_wrldc_training
/13_pandas_dataframe_loc.py
574
4.125
4
''' Lesson 2 - Day 3 - Pandas DataFrame loc function loc function is used to access dataframe data by specifying the row index values or column values ''' #%% import pandas as pd # create a dataframe df = pd.DataFrame([[2, 3], [5, 6], [8, 9]], index=['cobra', 'viper', 'sidewinder'], columns=['max_speed', 'shield']) print(df) # %% # select rows with index as 'viper', 'cobra' but all columns df2 = df.loc[['viper', 'cobra'], :] # %% # select rows with index as 'viper', 'cobra' and columns as 'max_speed' df2 = df.loc[['viper', 'cobra'], ['max_speed']] # %%
true