blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7942e0b8ab102a3a2ae845dbd0c882a9c1a50580
ronaldfalcao/pythoncodes
/factorial/factorial_recursive.py
598
4.375
4
#coding: utf-8 def factorial_recursive(x): if x == 0: return 1 elif x == 1: # Base case return 1 else: return x * factorial_recursive(x-1) # Recursive expression #Exemplo de uso da função factorial() num = int(input("Entre com um número (inteiro e positivo): ")) if (factorial_recursive(num) < 0): print "O valor de entrada precisa ser um inteiro positivo!" elif (factorial_recursive(num) == 0): print "O valor para o fatorial de 0 é 1 por definição." else: print "O valor do fatorial para a posição", num, "é", factorial_recursive(num)
false
b74c18f10daa14b813dff047f81d76fa6fef9edc
lyoness1/skills-cd-data-structures-2
/recursion.py
2,907
4.59375
5
# --------- # # Recursion # # --------- # # 1. Write a function that uses recursion to print each item in a list. def print_item(my_list): """Prints each item in a list recursively. >>> print_item([1, 2, 3]) 1 2 3 """ if not my_list: return print my_list[0] print_item(my_list[1:]) # 2. Write a function that uses recursion to print each node in a tree. def print_all_tree_data(tree): """Prints all of the nodes in a tree. >>> class Node(object): ... def __init__(self, data): ... self.data=data ... self.children = [] ... def add_child(self, obj): ... self.children.append(obj) ... >>> one = Node(1) >>> two = Node(2) >>> three = Node(3) >>> one.add_child(two) >>> one.add_child(three) >>> print_all_tree_data(one) 1 2 3 """ print tree.data for child in tree.children: print_all_tree_data(child) # 3. Write a function that uses recursion to find the length of a list. def list_length(my_list): """Returns the length of list recursively. >>> list_length([1, 2, 3, 4]) 4 """ if not my_list: return 0 return 1 + list_length(my_list[1:]) # 4. Write a function that uses recursion to count how many nodes are in a tree. nodes = [] def num_nodes(tree): """Counts the number of nodes. >>> class Node(object): ... def __init__(self, data): ... self.data=data ... self.children = [] ... def add_child(self, obj): ... self.children.append(obj) ... >>> one = Node(1) >>> two = Node(2) >>> three = Node(3) >>> four = Node(4) >>> one.add_child(two) >>> one.add_child(three) >>> two.add_child(four) >>> num_nodes(one) 4 """ # nodes.append(tree.data) # if tree.children: # for child in tree.children: # num_nodes(child) # return len(nodes) # I spent three hours on this one... it's super easy to use a list or counter # globally, but I can't, for the life of me, figure out how to do this without # the global variable :( count = 1 for child in tree.children: count += num_nodes(child) return count # UPDATE: After I wrote lines 86-94, I came up with lines 96-99 in about 10 min # I've never felt such a love-hate relationship with anyone or anything as I do # with recursion!! ##################################################################### # END OF ASSIGNMENT: You can ignore everything below. if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED. GOOD WORK!" print
true
5b95b484392c7e58a9bf5a98cb8db1cf91e400b4
jorgeaugusto01/DataCamp
/Data Scientist with Python/21_Supervised_Learning/Cap_2/Pratices4_5.py
2,944
4.21875
4
#Train/test split for regression #As you learned in Chapter 1, train and test sets are vital to ensure that your supervised learning model # is able to generalize well to new data. This was true for classification models, and is equally true for # linear regression models. #In this exercise, you will split the Gapminder dataset into training and testing sets, # and then fit and predict a linear regression over all features. # In addition to computing the R2 score, you will also compute the Root Mean Squared Error (RMSE), # which is another commonly used metric to evaluate regression models. # The feature array X and target variable array y have been pre-loaded for you from the DataFrame df. # Import necessary modules from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge import pandas as pd import numpy as np # Read the CSV file into a DataFrame: df df = pd.read_csv('../../DataSets/gapminder/gapminder.csv') # Create arrays for features and target variable y = df['life'].values X = df['fertility'].values # Reshape X and y y = y.reshape(-1, 1) X = X.reshape(-1, 1) # Create training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=42) # Create the regressor: reg_all reg_all = LinearRegression() # Fit the regressor to the training data reg_all.fit(X_train, y_train) # Predict on the test data: y_pred y_pred = reg_all.predict(X_test) # Compute and print R^2 and RMSE print("R^2: {}".format(reg_all.score(X_test, y_test))) rmse = np.sqrt(mean_squared_error(y_test, y_pred)) print("Root Mean Squared Error: {}".format(rmse)) #5-fold cross-validation #Cross-validation is a vital step in evaluating a model. It maximizes the amount of data that is used to # train the model, as during the course of training, the model is not only trained, but also tested on all of # the available data. # In this exercise, you will practice 5-fold cross validation on the Gapminder data. # By default, scikit-learn's cross_val_score() function uses R2 as the metric of choice for regression. # Since you are performing 5-fold cross-validation, the function will return 5 scores. Your job is to compute # these 5 scores and then take their average. # The DataFrame has been loaded as df and split into the feature/target variable arrays X and y. The modules pandas and numpy have been imported as pd and np, respectively. # Import the necessary modules from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_score # Create a linear regression object: reg reg = LinearRegression() # Compute 5-fold cross-validation scores: cv_scores cv_scores = cross_val_score(reg, X, y, cv=5) # Print the 5-fold cross-validation scores print(cv_scores) print("Average 5-Fold CV Score: {}".format(np.mean(cv_scores)))
true
0de409619de9e651b2508a9fae5009fa10fcf226
shailsoni44/pytrain20
/pyt1.py
1,835
4.125
4
print("Question 1\n") x= 1 ; y= 2.5 ; z='string' print("Type of x:",type(x) , "\nType of y:", type(y) , "\nType of z:", type(z)) print("\nQuestion 2\n") a=(1j+2) ; b = 3 print("Assigned value of a:", a,"\nAssigned value of b:",b) a,b = b,a print("After swapping value of a is:", a , "\nAfter swapping value of b is:", b) print("\nQuestion 3\n") a = 4 ; b = 5 print("Assigned value of a:", a,"\nAssigned value of b:",b) x=a ; a=b ; b=x print("After swapping value of a:", a,"\nAfter swapping value of b:",b) #without using other variable a=4 ; b = 5 print("Assigned value of a:", a,"\nAssigned value of b:",b) a,b = b,a print("After swapping value of a:", a,"\nAfter swapping value of b:",b) print("\nQuestion 4\n") print("for python 3+ \n v1 = eval (input('Please enter a value: ')) \n or v1 = input('Please eneter a value: ')") print("For python 2\n v2 = input('Please enter the value: ')\n which is same as \n v2= eval(raw_input('Please enter the value: '))") print("\nQuestion 5\n") x = int(input("Please enter two integer numbers between 1 and 10 \n First number is: ")) y = int(input("Second number is: ")) z = x+y print("Total sum of the given numbers adding 30 into them:",z+30) print("\nQuestion 6\n") x= eval(input('Please enter any kind of data: ')) print("The input value data type is:",type(x)) print("\nQuestion 7\n") helloWorld = "lower Camel case" HelloWorld = "Upper camel case" hello_world = "snake case" print('we can write Hello world in',helloWorld,'like helloWorld' , '\nwe can write Hello world in',HelloWorld,'like HelloWorld' , '\nwe can write Hello world in',hello_world,'like hello_world') print("\nQuestion 8\n") print("Yes it will change value of a, Python is Dynamic language so it will take the latest value of a," , "\nand every variable is free to have any data type")
false
e56eb114b90742ca083d9812ce7e11e5d9504c2e
daniloaleixo/30DaysChallenge_HackerRank
/Day08_DictionairesAndMaps/dic_n_maps.py
2,134
4.3125
4
# Objective # Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video! # Task # Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead. # Note: Your phone book should be a Dictionary/Map/HashMap data structure. # Input Format # The first line contains an integer, , denoting the number of entries in the phone book. # Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend's name, and the second value is an -digit phone number. # After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input. # Note: Names consist of lowercase English alphabetic letters and are first names only. # Constraints # Output Format # On a new line for each query, print Not found if the name has no corresponding entry in the phone book; otherwise, print the full and in the format name=phoneNumber. # Sample Input # 3 # sam 99912222 # tom 11122222 # harry 12299933 # sam # edward # harry # Sample Output # sam=99912222 # Not found # harry=12299933 n = int(raw_input()) phone_book = {} inputs = [] for i in range(0, n): line = raw_input().strip().split(' ') phone_book[line[0]] = line[1] # print phone_book # line = raw_input().strip() # # print line # while line != None and len(line) > 0: # inputs.append(line) # line = raw_input().strip() while True: try: line = raw_input().strip() inputs.append(line) except EOFError: break # print inputs for elem in inputs: if elem in phone_book: print elem + '=' + phone_book[elem] else: print 'Not found' # print inputs, phone_book
true
b8c2b94be9e48ae10bf5c47817f6af19109ced0c
LouisTuft/RSA-Calculator-and-Theory
/1.RSAValues.py
2,147
4.25
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 30 02:13:03 2020 @author: Louis """ """ The theory behind RSA is explained in the Readme file in the repository. This python file is the first of three that form a complete RSA system. This file in particular will allow you to construct your own set of keys for RSA. The goal of this file is to establish the size of primes required to encrypt the message you have and then provide you with an encryption and decryption key. Currently the user has to input there own encryption key, in the future I hope to add a 'choosingE():' function thatwill allow the user to pick from one of many random possible values of e or input their own. Due to this the user is required to know how to pick a 'good' value for e (and p,q), this information can be found in the readme file. """ def valuesRSA(p,q): #Calculates n and phi(n) from two input primes p,q. n = p*q phi = (p-1)*(q-1) return [n,phi] def calculatingD(e,phi): #After choosing the encryption key, this function if e == 0: #calculates the decryption key. (Bezout's Theorem). return (phi, 0, 1) else: gcd, x, y = calculatingD(phi%e,e) return (gcd, y-(phi//e)*x,x) def signOfD(d,phi): #Occasionally d is negative, but since we work if d < 0: #modulo phi(n), we can change this easily. return d + phi else: return d def main(): message = input('Input the message you wish to encrypt with RSA: ') p = int(input('Input a prime with roughly ' + str(len(message)+1) + ' digits: ')) q = int(input('Input another prime with at least ' + str(2*len(message)-len(str(p))+1) + ' digits: ')) n = valuesRSA(p,q)[0] phi = valuesRSA(p,q)[1] e = int(input('Input a value for e: ')) print('') d = calculatingD(e,phi)[1] d = signOfD(d,phi) print('message = ' + message) print('p = ' + str(p)) print('q = ' + str(q)) print('n = ' + str(n)) print('phi(n) = ' + str(phi)) print('e = ' + str(e)) print('d = ' + str(d)) return main() """ The RSA encryption key is (e,n) and decryption key is (d,n). """
true
b14350b1729a7ad4dca30edae721cd6f82b04d42
anirudhagaikwad/Python10Aug21
/PythonWorkPlace/Python_DataTypes/Manipulations/PythonSetExmpl.py
709
4.1875
4
# initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B)#Union is performed using | operator. print(A.union(B))#union using Function #Intersection of A and B is a set of elements that are common in both sets. print(A & B) #Intersection is performed using & operator. # Intersection can be accomplished using the method intersection(). print(A.intersection(B)) print(A - B)#Difference is performed using - operator. """" Difference of A and B (A - B) is a set of elements that are only in A but not in B. B - A is a set of element in B but not in A. """ #Same can be accomplished using the method difference(). print(A.difference(B))
true
f70aa44924847d48183279a297ef6cda93f1b3d0
anirudhagaikwad/Python10Aug21
/PythonWorkPlace/Python_DataTypes/Python_Tuple.py
1,153
4.6875
5
#tuples are immutable. #defined within parentheses () where items are separated by commas #Tuple Index starts form 0 in Python. x=('python',2020,2019,'django',2018,20.06,40j,'python') #Tuple # you can show tuple using diffrent way print('Tuple x : ',x[:]) # we can use the index with slice operator [] to access an item in a tuple. Index starts from 0. print('Tuple x : ',x[:]) print('Tuple x : ',x[0:]) print('Tuple x : ',x) # extract/access specific element from tuple print('Tuple x[0] : ',x[0]) print('Tuple x[1:5] : ',x[1:5]) # characters from position(index) 1 (included) to position(index) 5 (excluded i.e. 5-1) it will print index 1 element to index 4 element """" Python allows negative indexing for its sequences.The index of -1 refers to the last item, -2 to the second last item and so on. """ print('Tuple negative indexing x[-2]: ',x[-2]) print('Tuple negative indexing x[0:-4]: ',x[0:-4]) print('Tuple negative indexing x[:-4]: ',x[:-4]) z =x.count('python') # Returns the number of items x print(z,'number of python string found in tuple') z=x.index(2019) # Returns the index of the item print('index number of 2019 is : ',z)
true
c3f0fe5252715fd2df8084c40d654f73913977b7
anirudhagaikwad/Python10Aug21
/PythonWorkPlace/Python_DataTypes/Python_Dictionary.py
1,315
4.5625
5
"""" dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type. """ #keys must be of immutable type and must be unique. d = {1:'value_of_key_1','key_2':2} #Dictionary print('d is instance of Dictionary : ',isinstance(d,type(d))) #To access values, dictionary uses keys. print("using key access value d[1] = ", d[1]) print("using key access value d['key_2'] = ", d['key_2']) print('access values using get() : ',d.get(1))#access values using get() # update value d[1] = 'Banana' print('update d[1] = Banana : ',d[1]) # add item d['Dry Fruit'] = 'Badam' print('add item d[Dry Fruit] = Badam',d) print('d.items() :',d.items()) #To access the key value pair, you would use the .items() method print('d.keys() :',d.keys()) #To access keys separately use keys() methos print('d.values() :',d.values()) #To access values separately use values() methos #print("d[2] = ", d[2]); # Generates error # remove dict pair d.pop(1) #remove a particular item, returns its value print('after d.pop(1) : ',d) d.popitem() #remove an arbitrary item,return (key,value) print('after d.popitem() : ',d) # remove all items d.clear() print('after use function clear() : ',d) # delete the dictionary itself del d #print('after delete dictionary : ',d)
true
ba925036cd692feb041c9305eba8a89b438a528e
pedronet28/curso-pyton-udemy
/06-list.py
1,451
4.5625
5
#En python los arreglos son llamados list #definiendo y cargando un ana list en python #Ejemplo1 lenguajes = ['Python','Kotlin','Java','JavaScrip'] numeros = [3,5,7,2] print(lenguajes) #Ejemplo2 Aplicando método de ordenamiento #acendente y alfabetico en list de python lenguajes.sort() print(lenguajes) numeros.sort() print(numeros) #Ejemplo3 Accediendo a registro de una lista #Nota los lista al igual que los arreglos #inician en la pocicion 0 print(lenguajes[0]) print(numeros[3]) #Ejemplo4 adicionando elementos a la lista lenguajes.append('Php') numeros.append(9) print(lenguajes) print(numeros) #Ejemplo5 Remplazando el valor de un registro en la lita lenguajes[2] = 'Ruby' numeros[2] = 6 print(lenguajes) print(numeros) #Ejemplo6 formas de eliminar un elemento de la lista #Forma1 elimina el registro por indice de pocicion del lenguajes[1] del numeros[0] print(lenguajes) print(numeros) print(lenguajes[1]) print(numeros[0]) #Forma2 eliminar registro utilizan el metodo pop() sin parametros y com paramentros lenguajes.pop() # elimina el ultimo registro de la lista numeros.pop() print(lenguajes) print(numeros) lenguajes.pop(1)# elimina el elemento especificado por su indice en el parametro numeros.pop(2) print(lenguajes) print(numeros) #Forma3 elimina un registro de la lista especifico por su valor # utilizando el método remove('valor') lenguajes.remove('Java') numeros.remove(6) print(lenguajes) print(numeros)
false
a0fe310c8be1f85b9fbeb61c83c833104ebdd6ef
morganhowell95/TheFundamentalGrowthPlan
/Data Structures & Algorithms/Queues & Stacks/LLImplOfStack.py
1,460
4.28125
4
#Stack is a Last In First Out (LIFO) data structure #Data is stored by building the list "backwards" and traversing forwards to return popped values class Stack: def __init__(self): self.tail = None def push(self, d): #create new node to store data node = Stack.Node(d) #link new node "behind" the old node if not self.is_empty(): old_node = self.tail self.tail = node self.tail.next = old_node #if no linked list currently exists, create a node associated with tail pointer else: self.tail = Stack.Node(d) def peek(self): if not self.is_empty(): return self.tail.data else: return None def pop(self): if not self.is_empty(): rdata = self.tail.data self.tail = self.tail.next return rdata else: return None def is_empty(self): return not self.tail #Local class representing the nodes of our linked list class Node: def __init__(self, data): self.data = data self.next = None #Minor crude tests of our Stack s = Stack() for i in range(0,10): s.push(i) def notExpected(op): raise Exception('Stack not functioning as expected on ' + op) if s.is_empty() != False: notExpected('empty') if s.peek() != 9: notExpected('peek') if s.pop() != 9: notExpected('pop') if s.peek() != 8: notExpected('peek') while not s.is_empty(): s.pop() if s.is_empty() != True: notExpected('empty') print ("Your stack works as expected")
true
b39cba591c93f4c5b772479ce76828234f751fb0
gabrielsp20/Ex_Python
/004.py
493
4.25
4
'''Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possiveis sobre ele.''' a = input('Digite algo:') print('O tipo primitivo desse valor é', type(a)) print('Só tem espaço?',a.isspace()) print('É número', a.isnumeric()) print('É alfabético?', a.isalpha()) print('É alfanumérico?', a.isalnum()) print('Está com maiúscula?',a.isupper()) print('Está em minúsculo?',a.islower()) print('Está capitalizada?', a.istitle())
false
1973b0884e9b91bc6d9678d3eb30bb30e7bd500d
gabrielsp20/Ex_Python
/039.py
833
4.125
4
''' Faça u programa que leia o ano de nascimento de um jovem e informe de acordo com sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora de se alistar ou sejá passou do tempo de alistamento. seu programa também deverá mostrar o tempo que faltou ou que passou de prazo. ''' from datetime import date ano = int(input('Ano de nascimento: ')) idade = date.today().year - ano print('Quem nasceu em {} tem {} em {}'.format(ano, idade, date.today().year)) if idade >= 18: print('Você ja deveria ter se alistado há {}'.format(idade - 18)) print('Seu alistamento foi em {} anos '.format( date.today().year - (idade - 18) )) elif idade < 18: print('Ainda faltam {} anos para o seu alistamento'.format(18 - idade)) print('Seu alistamento será em {}'.format((18 - idade + date.today().year )))
false
556b4d097c89b6b0761c4fb4e1850ed0f6f664fb
HansHuller/Python-Course
/ex010 Real para Dolar.py
302
4.1875
4
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela pode comprar. Considere US$1.00 = R$3.27 wallet = float(input("Digite quanto dinheiro possue em sua carteira: R$")) print("Com esse dinheiro você poderia comprar US${:.2f} !!!!".format(wallet/3.27))
false
6e47aade01ffdbb8906585316b6f177517cd3df1
HansHuller/Python-Course
/ex097 Função Titulo.py
402
4.1875
4
''' Faça um programa que tenha uma função chamada escreva(), que receba um texto qualqer como parâmetro e mostre uma mensagem com tamanho adaptável. (linha = tamanho da frase) ''' def escreva(frase): frase = " " + frase + " " tam = len(frase) print("-" * tam) print(f"{frase.upper()}") print("-" * tam) #Inicio do programa escreva(str(input("Digite o título desejado: ")))
false
df6e6fcf0d079f19b91fd44db367e3e521479cad
HansHuller/Python-Course
/ex085 LISTA COMP Dividir par e impar em duas listas em uma lista.py
831
4.1875
4
''' Crie um programa onde o usuário possa digitar sete valores númericos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente. ''' lista = [[], [], []] for i in range(1, 8): v = "" while not isinstance(v, int): v = input(f"Digite o {i}º valor: ") try: v = int(v) except ValueError: print("Você digitou um valor inválido, digite um nº inteiro!") if v % 2 == 0: lista[0].append(v) lista[1].append(v) else: lista[0].append(v) lista[2].append(v) lista[0].sort() lista[1].sort() lista[2].sort() print(f"Os números digitados são: {lista[0]}") print(f"Os números pares são: {lista[1]}") print(f"Os números ímpares são: {lista[2]}")
false
f261890f30cecd7c20b0cdcbb849879e346b1189
HansHuller/Python-Course
/ex074 TUPLA Sorteada Menor e Menor.py
650
4.21875
4
''' Crie um programa que vai gerar 5 números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla. Exibir sorteados, mostrar resultados de maior e menor ''' from random import randint tupla = (randint(0, 100), randint(0, 100), randint(0, 100), randint(0, 100), randint(0, 100)) print(tupla) print("-="*35) print("Os números sorteados foram: ", end="") for n in tupla: print(f"{n:^7}", end="") print("\n", end="") print("-="*35) print(f"O maior número sorteado foi:{max(tupla)}") print("-="*35) print(f"O menor número sorteado foi:{min(tupla)}")
false
83c040a380c738e171e118900d10ae4273101b9c
HansHuller/Python-Course
/ex018 Sen Cos Tang.py
376
4.125
4
#Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse angulo. from math import radians, sin, cos, tan, degrees ang = (radians(float(input("Digite o ângulo: ")))) print("Para o ângulo de {:.2f} graus seu seno é: {:.2f}\nSeu cosseno é: {:.2f}\n E sua tangente é: {:.2f}".format(degrees(ang),sin(ang),cos(ang),tan(ang)))
false
b0d77ccab453c03c5f53e254ebd3ee69a44ec84f
HansHuller/Python-Course
/ex105 FUNÇÃO C RETURN Análise de notas de alunos.py
1,075
4.125
4
''' Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações: - Quantidade de notas - A maior nota - A menos nota - A média da turma - A situação (opcional) [média > 7 = BOA, >5 = RAZOAVEL, <5 = ruim] Fazer DOCSTRINGS ''' def notas(*notas, sit = False): """ Função para analisar notas de alunos :param notas: uma ou mais notas de alunos :param sit: valor opcional, indica se deve ou não adicionar situação :return: dicionário com várias informações sobre a situação da turma. """ result = dict() result["total"] = len(notas) result["maior"] = max(notas) result["menor"] = min(notas) result["média"] = sum(notas)/len(notas) if sit: if result["média"] >= 7: result["situação"] = "BOA" elif result["média"] >= 5: result["situação"] = "RAZOÁVEL" else: result["situação"] = "RUIM" return result resp = notas(5.5, 2.5, 1.5, sit=True) print(resp)
false
505074bf8af967451a4d1524b4425e7e6db352db
navy-xin/Python
/黑马学习/while-02循环计数器的习惯写法.py
339
4.125
4
""" while 条件: 条件成立要重复执行的代码 。。。。。 """ # 需求:重复打印100次媳妇儿,您辛苦了 --- 1,2,3,4,5.。。100--数据表示循环的次数,依次 # 1+1+1+1.。。。。 i = 0 while i <5: print('媳妇儿,您辛苦了') i += 1 # i = i +1 print('你也辛苦了!')
false
33042110ed9758f6036bed0b925747afa5eeba5d
navy-xin/Python
/黑马学习/while-09-循环嵌套应用之打印星号(正方形).py
311
4.1875
4
""" 1、打印1个星星 2、一行5个:循环 --5个星星在一行显示 3、打印5行星星:循环-- 一行5个 """ j =0 while j < 5: # 一行星星开始 i = 0 while i < 5: print("*",end='') i += 1 # 一行星星结束:换行显示下一行 print() j += 1
false
14901244b9c06406fa9c8e721febc1108f2885c9
masterbpk4/matchmaker_bk
/matchmaker_bk.py
2,927
4.1875
4
##Brenden Kelley 2020 All Rights Reserved ##Just kidding this is all open source ##Just make sure you credit me if you realize that this is a marvel of coding genius and decide to use it in the future ##First we need to get our questions placed in an array and ready to be pulled on command, we'll also need an empty array to keep track of the user's score question = ["- Cats are better than dogs." , "- Mountains are better than beaches." , "- Sitting down and watching anime is a good pastime" , "- I enjoy tabletop rpgs or would be interested in trying them." , "- I prefer sweet snacks over salty ones."] score = [] finalscore = [] ##We need an introduction to our program def Intro(): print("=".center(120, "=")) print("Hello and Welcome to The Ultimate Matchmaker! You will be given a series of statements where you are asked to rate how\n much you agree or disagree with them on a scale of 1 to 5 where 1 is strongly disagree and 5 is strongly agree.") print("=".center(120, "=")) ##Next we need to figure out what to do with user inputs def userInputs(): k = 0 while k < 1: try: k = int(input("Your answer: ")) if k == 1 or k == 2 or k == 3 or k == 4 or k == 5: score.append(k) else: raise ValueError except ValueError: k = 0 print("Please enter a number between 1 and 5") ##Next we need the function to ask the questions to the user def askquestions(): for i in range(0, len(question)): print("=".center(120, "=")) print("Question #"+str(i+1)) print(question[i]) print("=".center(120, "=")) print("Please Type Your Answer: ") userInputs() print("=".center(120, "=")) ##Now we need to do math on the scores to determine if the user is a good match def scorecalcs(): for n in range(0, len(score)): if n == 0 or n == 4: p = int(score[n]) p = 5 - abs(5-p) finalscore.append(p) elif n == 1 or n == 3: p = int(score[n]) p = 5 - abs(5-p) p = 3 * p finalscore.append(p) elif n == 2: p = int(score[n]) p = 5 - abs(5-p) p = p * 2 finalscore.append(p) ##And now we need to make the final score def results(): total = 0 for m in range(0, len(finalscore)): total = total + finalscore[m] total = total * 2 if total < 40: print("I hope we never meet, you got a score of: " + str(total)) elif total >= 40 and total < 80: print("I think we would be good friends, you got a score of: " + str(total)) elif total >= 80: print("I think we were made for each other! You got a score of: "+ str(total)) ##Now it's time to put everything we've done to work Intro() input("Press any key to continue. . .") askquestions() scorecalcs() results()
true
d03dcebc6a6787440c5381f6df2d071ff86c6916
academia08-2019/n303-exercicios-resolucoes
/ex2.py
683
4.1875
4
'''Faça um programa que receba dois inputs, uma palavra/frase e uma letra. O programa deve retornar quantas vezes a letra apareceu na palavra/frase. Dica: contagem de valores .count('valor')''' def contar_letra(): palavra = input("Digite um palavra") letra = input("Digite a letra que deseja contar na palavra") return palavra.count(letra) #JEITO MAIS COMPLETO COM VALIDAÇÃO PARA UMA LETRA def contar_letra2(): palavra = input("Digite um palavra") letra = input("Digite a letra que deseja contar na palavra") while len(letra) > 1: letra = input("Digite a letra que deseja contar na palavra") return palavra.count(letra) print(contar_letra2())
false
d2b896e0dbd0dc25858882e9adc0379aef020fe3
vladimir4919/purpose
/borndayforewer.py
847
4.375
4
def bornyeardayforewer(year_birth,notability,day,month): print(year_birth) year = int(input(f'Введите год рождения {notability}:')) while int(year) != year_birth: print("Не верно") year = input(f'Введите год рождения {notability}:') day = input(f'В какой день {month} день рождения {notability}:') while day != '6': print("Не верно") day = input(f'В какой день {month} родился {notability}?') print('Верно') notability='Пушкин' year_birth=1799 day_birth=6 month='июня' bornyeardayforewer(year_birth,notability,day_birth,month) notability='Дарвин' year_birth=1809 day_birth=12 month='февраля' bornyeardayforewer(year_birth,notability,day_birth,month)
false
6bf9042e0c296379fbe1c557904bfc04c224f31f
rajatpanwar/python
/Dictonary/Dictionary.py
2,580
4.625
5
/// A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets <--------example1-------> thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) <-------example2---------> // how to access the element in dictionary detail= { "Name":"Rajat panwar", "sapid":500069414, "Roll no":80, "course":"B.Tech", } x=detail["Name"] print(x) <-----------example 3----- ------------> //access the element detail= { "Name":"Rajat panwar", "sapid":500069414, "Roll no":80, "course":"B.Tech", } print("Name :%s "%detail["Name"]) print("sapid :%d "%detail["sapid"]) print("Roll no :%d "%detail["Roll no"]) print("course :%s "%detail["course"]) <------------example4-------------------> // add new data in the dictionary detail= { "Name":"Rajat panwar", "sapid":500069414, "Roll no":80, "course":"B.Tech", } print(detail) print("<------enter new detail---------->") detail["Name"]=input("Name ") detail["sapid"]=int(input("sapid ")) detail["Roll no"]=int(input("Roll no ")) detail["course"]=input("course ") print("-----printing the new data-------") print(detail) <-------example5--------------> //similiar to example3 detail= { "Name":"Rajat panwar", "sapid":500069414, "Roll no":80, "course":"B.Tech", } x=detail.get("Name") //we can use get function to access the element print(x) <-------example6------------> //print all the attribute on by one using for loop detail= { "Name":"Rajat panwar", "sapid":500069414, "Roll no":80, "course":"B.Tech", } for i in detail: print(i) //output is --- Name,sapid,Rollno,course <-------------example7---------------------> //print all the value of key attribute detail= { "Name":"Rajat panwar", "sapid":500069414, "Roll no":80, "course":"B.Tech", } for i in detail: print(detail[i]) //output is--- Rajat Panwar 500069414 80 B.Tech <------------example8------------------------> detail= { "Name":"Rajat panwar", "sapid":500069414, "Roll no":80, "course":"B.Tech", } for i,j in detail.items(): //using items() function we can print key and value both print(i,j) <-----------------------example9----------------> detail= { "Name":"Rajat panwar", "sapid":500069414, "Roll no":80, "course":"B.Tech", } del detail["sapid"] // use del we can remove the key and value for the dctionary print(detail)
true
a0444ca1776cae4cc5a73af7e82a9dc4f4577080
mornville/Interview-solved
/LeetCode/September Challenge/word_pattern.py
950
4.21875
4
""" Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. Example 1: Input: pattern = "abba", str = "dog cat cat dog" Output: true Example 2: Input:pattern = "abba", str = "dog cat cat fish" Output: false """ class Solution(object): def wordPattern(self, pattern, str): words = str.split(' ') if len(set(list(pattern))) != len(set(words)): return False wordDict = {} index = 0 length = len(pattern) for i in words: if index >= length: return False key = pattern[index] if key in wordDict and wordDict[key] != i: return False elif key not in wordDict: wordDict[key] = i index += 1 return True
true
0c359a7b16b7fbece29a96fa1b19e49aaddfed73
bluella/hackerrank-solutions-explained
/src/Arrays/Minimum Swaps 2.py
974
4.375
4
#!/usr/bin/env python3 """ https://www.hackerrank.com/challenges/minimum-swaps-2 You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. Find the minimum number of swaps required to sort the array in ascending order. """ import math import os import random import re import sys def minimumSwaps(arr): """ Args: arr (list): list of numbers. Returns: int: min number of swaps""" i = 0 count = 0 # since we know exact place in arr for each element # we could just check each one and swap it to right position if thats # required while i < len(arr): if arr[i] != i + 1: arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1] count += 1 else: i += 1 return count if __name__ == "__main__": ex_arr = [1, 2, 3, 5, 4] result = minimumSwaps(ex_arr) print(result)
true
e477ab371361b476ded3fbeb89c663c253ee77a6
bluella/hackerrank-solutions-explained
/src/Warm-up Challenges/Jumping on the Clouds.py
1,623
4.1875
4
#!/usr/bin/env python3 """ https://www.hackerrank.com/challenges/jumping-on-the-clouds There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. The player must avoid the thunderheads. Determine the minimum number of jumps it will take to jump from the starting postion to the last cloud. It is always possible to win the game. For each game, you will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided. """ import math import os import random import re import sys # # Complete the 'jumpingOnClouds' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY c as parameter. # def jumpingOnClouds(c): """ Args: c (int): array of ones and zeros. Returns: int: min number of jumps""" current_cloud = 0 jumps = 0 len_c = len(c) # count jumps whilst looping over the clouds while current_cloud < len_c - 1: if len_c > current_cloud + 2: # check if we are able to do long jump if c[current_cloud + 2] == 0: current_cloud += 2 # else do short jump else: current_cloud += 1 else: current_cloud += 1 jumps += 1 # print(current_cloud, jumps) return jumps if __name__ == "__main__": jumps_arr = [0, 1, 0, 0, 0, 1, 0] result = jumpingOnClouds(jumps_arr) print(result)
true
98fa867c2dd374990ca6d8b682de24e796234d46
Romancerx/Lesson_01
/Task_1.py
2,567
4.3125
4
#1. Поработайте с переменными, #a) создайте несколько, выведите на экран, #б) запросите у пользователя несколько чисел и строк, сохраните в переменные, #в) выведите на экран. #a) Creating new variables number = 0 number_float = 2.14 string = "Hello!" error_flag_1 = 0 # Используем для проверки ввода правильного типа данных error_flag_2 = 0 # Используем для проверки ввода правильного типа данных error_flag_3 = 0 # Используем для проверки ввода правильного типа данных #print new variables print(number, number_float, string) #б) request some numbers and strings """ Ввод строкового значения при запросе числа выдает ошибку. По идее нужно проверять, что ввели. без проверки: user_number1 = int(input("Введите первое число: ")) user_number2 = int(input("Введите второе число: ")) user_number3 = int(input("Введите третье число: ")) """ # C проверкой (уверен можно сделать код короче, но мне не хватает времени додумать): while error_flag_1 == 0: try: user_number1 = int(input("Введите первое число: ")) error_flag_1 = 1 except: print('Введено "неправильное" число') while error_flag_2 == 0: try: user_number2 = int(input("Введите второе число: ")) error_flag_2 = 1 except: print('Введено "неправильное" число') while error_flag_3 == 0: try: user_number3 = int(input("Введите третье число: ")) error_flag_3 = 1 except: print('Введено "неправильное" число') user_string1 = input("Введите текст: ") user_string2 = input("Введите еще немного букоф: ") user_string3 = input("Введите и еще пару слов : ") #в) Print print("Введенные числа \n", user_number1, user_number2, user_number3) print("Введенные строки \n", user_string1, "\n", user_string2, "\n", user_string3) # Почему "\n" вводит пробел или отступ в начале строки???
false
2ca1392aa7be9fe4f7f7efbcd531459d4d40d538
Tigresska/learn_python_matthes
/6_1_3.py
468
4.125
4
famous_person1 = { 'first_name': 'Angelina', 'last_name': 'Joile', 'age': '50', 'city': 'New York', } famous_person2 = { 'first_name': 'Bred', 'last_name': 'Pitt', 'age': '52', 'city': 'Washington', } famous_person3 = { 'first_name': 'Lewis', 'last_name': 'Hamilton', 'age': '38', 'city': 'London', } people = [famous_person1, famous_person2, famous_person3] for person in people: print() for key, value in person.items(): print(f"{key}: {value}")
false
a5259c0f1618344c5788637a406943352a01b5d9
anoubhav/Project-Euler
/problem_3.py
971
4.15625
4
from math import ceil def factorisation(n): factors = [] # 2 is the only even prime, so if we treat 2 separately we can increase factor with 2 every step. while n%2==0: n >>= 1 factors.append(2) # every number n can **at most** have one prime factor greater than sqrt(n). Thus, we have the upper limit as sqrt(n). If after division with earlier primes, n is not 1, this is the prime factor greater than sqrt(n). for i in range(3, ceil(n**0.5) + 1, 2): while n%i == 0: n //= i factors.append(i) if n!=1: factors.append(n) # it has a prime factor greater than sqrt(n) return factors n = 600851475143 print(max(factorisation(n))) # Proof: Every number n can at most have one prime factor greater than n. https://math.stackexchange.com/questions/1408476/proof-that-every-positive-integer-has-at-most-one-prime-factor-greater-than-its/1408496
true
97f21e92543f97bf7be3a7603c366c371fbbe0a8
luabras/Angulo-vetores
/AnguloEntreVetores.py
1,829
4.28125
4
import numpy as np import matplotlib.pyplot as plt def plotVectors(vecs, cols, alpha=1): """ Plot set of vectors. Parameters ---------- vecs : array-like Coordinates of the vectors to plot. Each vectors is in an array. For instance: [[1, 3], [2, 2]] can be used to plot 2 vectors. cols : array-like Colors of the vectors. For instance: ['red', 'blue'] will display the first vector in red and the second in blue. alpha : float Opacity of vectors Returns: fig : instance of matplotlib.figure.Figure The figure of the vectors """ plt.figure() plt.axvline(x=0, color='#A9A9A9', zorder=0) plt.axhline(y=0, color='#A9A9A9', zorder=0) for i in range(len(vecs)): x = np.concatenate([[0,0],vecs[i]]) plt.quiver([x[0]], [x[1]], [x[2]], [x[3]], angles='xy', scale_units='xy', scale=1, color=cols[i], alpha=alpha) #funcao para calcular angulo entre vetores def ang2Vet(v, u): #calculando o produto escalar entre v e u vInternoU = v.dot(u) #calculando os modulos de v e u vModulo = np.linalg.norm(v) uModulo = np.linalg.norm(u) #calculando o cosseno do angulo entre v e u r = vInternoU/(vModulo*uModulo) #angulo em radianos ang = np.arccos(r) #retornando em graus return (180/np.pi)*ang #criando vetores u = np.array([0,1]) v = np.array([1, 0]) #definindo as cores dos vetores para plotar o grafico red = 'red' blue = 'blue' #usando funcao do matplotlib para plotar vetores plotVectors([u, v], [red, blue]) plt.xlim(-5, 10) plt.ylim(-5, 5) plt.show() #usando a funcao criada para calcular o angulo entre u e v angulo = ang2Vet(u, v) print(angulo)
true
31c247fdb56a75015b434f3721249b5711901b57
2pack94/CS50_Introduction_to_Artificial_Intelligence_2020
/1_Knowledge/0_lecture/0_harry.py
1,540
4.125
4
from logic import * # Create new classes, each having a name, or a symbol, representing each proposition. rain = Symbol("rain") # It is raining. hagrid = Symbol("hagrid") # Harry visited Hagrid. dumbledore = Symbol("dumbledore") # Harry visited Dumbledore. # Save sentences into the Knowledge Base (KB) knowledge = And( Implication(Not(rain), hagrid), # ¬(It is raining) → (Harry visited Hagrid) Or(hagrid, dumbledore), # (Harry visited Hagrid) ∨ (Harry visited Dumbledore). Not(And(hagrid, dumbledore)), # ¬(Harry visited Hagrid ∧ Harry visited Dumbledore) i.e. Harry did not visit both Hagrid and Dumbledore. dumbledore # Harry visited Dumbledore. ) # The query is: Is it raining? # The Model Checking algorithm is used to find out if the query is entailed by the KB. query = rain print(modelCheck(knowledge, query)) # If the KB does not contain enough information to conclude the truth value of a query, model check will return False. # Example: # knowledge = dumbledore # query = rain # The enumerated models would look like this: # dumbledore rain KB # ------------------------------ # False False False # False True False # True False True # True True True # For the model dumbledore -> True and rain -> False, the KB is true, but the query is False. # If the query would have been: query = Not(rain) # Then for the model dumbledore -> True and rain -> True, the KB is true, but the query is False.
true
213454dcd8c830d4752d7915b2b4f91b721485b5
vigneshsinha04/DSA
/Algorithms - Recursive/Fibonacci.py
370
4.21875
4
def FibonacciRecursive(number): #Big-O = 2^n Exponential if number < 2: return number return FibonacciRecursive(number-1) + FibonacciRecursive(number-2) def FibonacciIterative(number): num1 = 0 num2 = 1 num3 = 0 for i in range(0,number-1): num3 = num1 + num2 num1 = num2 num2 = num3 return num3 print(FibonacciRecursive(5)) print(FibonacciIterative(5))
false
182456c4be118753b0ca6ece47d81a041e3aa3db
zackkattack/-CS1411
/cs1411/Program_01-1.py
500
4.65625
5
# Calculate the area and the circumfrence of a circle from its radius. # Step 1: Prompt for radius. # Step 2: Apply the formulas. # Step 3: Print out the result. import math # Step 1 radius_str = input("Enter the radius of the circle: ") radius_int = int(radius_str) # Convert radius_str into a integer # Step 2 circumfrence = 2*math.pi*radius_int area = (math.pi)*(radius_int**2) # Step 3 print print "The area of the circle is:", area print "The circumfrence of the circle is:" , circumfrence
true
70de8dc6a37fd9e059bb23d8a96ec2139ffc8257
WinnyTroy/random-snippets
/4.py
670
4.1875
4
# # Order the list values = [1, 3, -20, -100, 200, 30, 201, -200, 9, 3, 4, 2, -9, 92, 99, -10] # # a.) In ascending Order values.sort() print values # # b.) In descending Order values.reverse() print(values) # # c.) Get the maximum number in the list print max(values) # # d.) Get the minimum number in the list print min(values) # # e.) Get the average of the list average = sum(values)/len(values) print average # f.) list of dictionaries from the list with the key being the absolute value of an element and the value being the cube of that element final = [] for x in values: ans = zip(str(abs(x)), str(x**3)) final.append(ans) print final
true
84397ef0767501c2754433972550e2ad3a180464
phnguyen-data/PythonHomework
/hwss2/BMI.py
333
4.15625
4
height = int(input("Your Height : ")) weight = int(input("Your Weight : ")) BMI = weight / ((height * height) / 10000) print(BMI) if BMI < 16: print("Severely underweight") elif BMI < 18.5: print("Underweight") elif BMI < 25: print("Normal") elif BMI < 30: print("Overweight") else: print("Obese")
false
c3cae72e8baded407d00e9bd9ad6c50bfce2547e
nabin2nb2/Nabin-Bhandari
/introEx2.py
246
4.53125
5
#2.Gets the radius of a circle and computes the area. Radius = input("Enter given Radius: ") Area = (22/7)*int(Radius)**2 #Formula to calculate area of circle print ("The area of given radius is: "+ str(Area.__round__(3)))
true
7e75e47b78db23fcd088cc057f0357431d75f236
nomadsarychev/repo
/python/lesson_2/step_2.py
532
4.15625
4
# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, надо вывести 6843. num = input("Введите число") num_end = "" for i in num: num_end = i + num_end print(f"{int(num_end)}") # def num_end(num): # if len(num) == 0: # return num # return num_end(num[1:]) + num[0] # # # a = "100500" # print(int(num_end(a)))
false
d592b8d81d0e7c9bb31113d1b2b7b2fee352ddef
Mugdass/datastructures
/data structures example.py
1,512
4.125
4
#This is a 'List' type of data structure myList = [] myList.append(1) myList.append(2) myList.append(3) myList.append(4) print(myList) print(myList.index(3)) myList.remove(4) print(myList) print() print() #This is a 'Tuple' type of data structure numbers=(1,2,2,2,2,1,3) print(numbers.index(2)) # with index() print() print() t1=(1,2,2,2,2,1,3) # this will count how many same numbers print(t1.count(1)) print(t1.count(2)) print(t1.count(3)) t1=(1,2,2,2,2,1,3) l1 = list(t1) l1.insert(3,'ins') t1 = tuple(l1) print(t1) print() print() #dictionary d = {'key':'value'} d = {'key':'value'} print(d.keys()) print(d.values()) print() d = {'firstNum':5, 'secondNum':2} print(d.keys()) print(d.values()) Total = d['firstNum'] + d['secondNum'] print('Total = ', Total) print() print() print() #to get values from dictionary object Total = d.get('firstNum') + d.get('secondNum') print('Total = ', Total) print() print() #to add item to dictionary d.update({'item3': 3}) print() print() print() #Converting dictionary object to List object v=list(d.values()) k=list(d.keys()) print(v[0]) print(k[0]) print() print() print() # so here the tuple () becomes the list [] t1=(1,2,2,2,2,1,3) l1 = list(t1) print(l1) print() print() # this will sort the list [] in order from lowest to higher number l1.sort() print(">>>", l1) print() print() sl=l1.sort() print (">>> ", sl)
false
4412e9ed8736bd3e3ccabbfd2e5f3cb380be6561
Alexsik76/Beetroot
/7_Functions/task2.py
318
4.1875
4
# Creating a dictionary dictionary = [] def make_country(name, capital): dictionary.append({'name': name, 'capital': capital}) make_country('USA', 'New York City') make_country('Україна', 'Київ') for i in dictionary: print(f"Країна: {(i['name']):10} Столиця: {(i['capital']):10}")
false
5067886008c47e705d0848903e77709ec99e811d
Alexsik76/Beetroot
/3_Booleans and control structures with while iteration/Classwork/work5.py
457
4.1875
4
text = 'Hello world' print('Колличество символов в строке: ' + str(len(text))) print('Колличество букв в строке: ' + str(len(text) - text.count(' '))) print('В верхнем регистре: ' + text.upper()) print('В нижнем регистре: ' + text.lower()) text_upper = text.upper() print('Текст с заглавными: ' + text_upper.capitalize()) for i in text: print(int(i) + '\n')
false
ace5e6c5659b45988cab23e38cefc5713d94161f
Alexsik76/Beetroot
/3_Booleans and control structures with while iteration/task2.py
414
4.28125
4
# The valid phone number program phone_num = input('Введите номер телефона: ') if phone_num.isnumeric() and len(phone_num) == 10: print('Спасибо за корректный номер') elif not phone_num.isnumeric(): print('Номер содержит не только цифры') elif not len(phone_num) == 10: print('Длина номера отличается от 10')
false
ca18170a10f6b4ecfa367cdb6b90aa1b8c9b2efe
skalunge1/python-p
/DictPgm.py
1,004
4.71875
5
# How to access elements from a dictionary? # 1. with the help of key : # 2. using get() method : If the key has not found, instead of returning 'KeyError', it returns 'NONE' my_dict = {'name':'Jack', 'age': 26} # Output: Jack print(my_dict['name']) print(my_dict.get('name')) # Output: 26 print(my_dict.get('age')) print(my_dict['age']) # get() : If the key has not found, instead of returning 'KeyError', it returns 'NONE' print(my_dict.get('adress')) # with the help of key only : If the key has not found, returning 'KeyError'. #print(my_dict['adress']) # How to change or add elements in a dictionary? # dictionary is mutable.We can add or edit existing values using assignment operator # if key is already present, value gets updated else new key:value pair get added my_dict = {'Name' : 'Smita', 'Adress' : 'Pune', 'Age': 29} my_dict['Name'] = 'Deepika' print("Name value after change :{}".format(my_dict['Name'])) my_dict['Age'] = 30 print("Age after change : {}".format(my_dict['Age']))
true
b4e460797dcf9d15466f25559adcaa19b0cd86eb
skalunge1/python-p
/DemoDeleteDict.py
1,261
4.46875
4
# How to delete or remove elements from a dictionary? # 1. pop() : Remove particular item from list # : It removes particular item after providing key and returns removed value squares = {1:1, 2:4, 3:9, 4:16, 5:25} print(squares.pop(4)) print(squares.pop(2)) print(squares) print(squares.popitem()) print(squares) print("*********") # popitem() : used to remove and return an arbitrary item (key, value) form the dictionary. # 2. removes 5:25 , 4:16, 3:9, 2:4, and last removes 1:1 squares = {1:1, 2:4, 3:9, 4:16, 5:25} print(squares.popitem()) print(squares.popitem()) print(squares.popitem()) print(squares.popitem()) print(squares.popitem()) # after removing all items, it displays empty list print(squares) print("*********") # 3. clear() : All the items can be removed at once using the clear() method. # It returns None squares = {1:1, 2:4, 3:9, 4:16, 5:25} print(squares.clear()) print("After deletion of all the itmes :{}".format(squares)) print("*********") # 4. 'del' keyword: We can also use the del keyword to remove individual items # or remove the entire dictionary itself. squares = {1:1, 2:4, 3:9, 4:16, 5:25} del squares[4] del squares[5] del squares # print squares after deletion of entire dictionary, throws error #print(squares)
true
cce65666f67ef2fb7a33c9372f03cdacf67ac500
FabrizioFubelli/machine-learning
/05-regressor-training.py
1,269
4.25
4
#!/usr/bin/env python3 """ Machine Learning - Train a predictive model with regression Video: https://youtu.be/7YDWaTKtCdI LinearRegression: https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html """ from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split import numpy as np np.random.seed(2) dataset = load_boston() # X contains the features X = dataset['data'] # y contains the target we want to find y = dataset['target'] X_train, X_test, y_train, y_test = train_test_split(X, y) model = LinearRegression() model.fit(X_train, y_train) # Train model from data p_train = model.predict(X_train) # Predict X_train after training p_test = model.predict(X_test) # Predict X_test after training mae_train = mean_absolute_error(y_train, p_train) mae_test = mean_absolute_error(y_test, p_test) print('MAE train', mae_train) print('MAE test', mae_test) # We need to know the model mean squared error mse_train = mean_squared_error(y_train, p_train) mse_test = mean_squared_error(y_test, p_test) print('MSE train', mse_train) print('MSE test', mse_test)
true
754e26560f3768a87fc88f9f4ce9fbc2b9648d40
FabrizioFubelli/machine-learning
/01-hello-world.py
1,390
4.28125
4
#!/usr/bin/env python3 """ Machine Learning - Hello World Video: https://www.youtube.com/watch?v=hSZH6saoLBY 1) Analyze input data 2) Split features and target 3) Split learning data and test data 4) Execute learning with learning data 5) Predict result of learning data and test data 6) Compare the accuracy scores between learning and test data """ from sklearn import datasets from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier # The input data is an iris flower dataset. # The desired output is the class of flower, by analyzing # the following parameters: # - Sepal length # - Sepal width # - Petal length # - Petal width iris_dataset = datasets.load_iris() X = iris_dataset.data # Features y = iris_dataset.target # Target print(iris_dataset['DESCR']) print() # Split data into training and test data X_train, X_test, y_train, y_test = train_test_split(X, y) # The test data is not used during learning, but is needed to measure # the final model learning quality # Execute learning model = DecisionTreeClassifier() model.fit(X_train, y_train) predicted_train = model.predict(X_train) predicted_test = model.predict(X_test) print('Train accuracy') print(accuracy_score(y_train, predicted_train)) print('Test score') print(accuracy_score(y_test, predicted_test))
true
0fce5a66b71ab421c5ff48b90bc5d13eb163d469
tapan2930/ds
/linked-list.py
677
4.25
4
# -------------------------Creating Linked List-------------------------# # Creating Node class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Printing Linkedlist items def ll_print(ll): if(ll == None): print("Empty LL") while (ll): print(ll.val, end=" ") ll = ll.next print(" ") # Creating ll: def ll_create(arr): head = ListNode(0) temp = ListNode(0) temp.next = head for _ in arr: node = ListNode(_) head.next = node head = node return temp.next.next """ Use Case: l1 = ll_Create([1,2,3,4,5,6,7,]) Use Case: ll_print(l1) """
false
d21287426535a76963e6a5dce8015f051b2f1f12
slviajero/number-theory
/numberfunctions.py
1,623
4.21875
4
from math import sqrt, factorial # # euklids algorithm to find the greatest common divisor of two integers # non recursive for a change # no optimization like for example handling situation where one factor is # much bigger than the other # def euklid(i,j): if (i<1 or j<1): return 0 while (i!=j): if (i>j): i=i-j else: j=j-i return j def euklid2(i,j): q=max(i,j) p=min(i,j) r=q%p if (r==0): return p else: return euklid(r,p) def coprime(i,j): return euklid(i,j)==1 def congruent(i,j,m): return ((i%m)==(j%m)) def divisible(i,j): return ((i%j)==0) def odd(n): return not divisible(n,2) def even(n): return divisible(n,2) # # Naive binomial # def binomial(n, m): if (n<0): return 0 if (m>n): return 0 return factorial(n) // factorial(m) // factorial(n - m) def binomial2(n, m): if (n<0) or (m<0): return 0 if (m>n): return 0 numerator=1 demoninator=1 for k in range(1,m+1): numerator=numerator*(n-k+1) demoninator=demoninator*k return numerator//demoninator if __name__=="__main__": d=euklid(187, 123) print("Greatest common divisor of {} and {} is {}".format(187, 123, d)) if coprime(187,123): print("187 and 123 are coprime") d=euklid(11, 121) print("Greatest common divisor of {} and {} is {}".format(11, 121, d)) a=12*8 b=12*8*3 d=euklid(a, b) e=euklid2(a, b) print("Greatest common divisor of {} and {} is {} or {}".format(a, b, d, e )) if not coprime(11,121): print("11 and 121 are not coprime") print("Binomial (10, 5) is {}".format(binomial(10,5))) a=10 b=9 print("Binomial ({}, {}) is {}".format(a, b, binomial2(a,b)))
false
950c0661c44ff43eaef662c124d1d3a9057122e1
EgorKolesnikov/YDS
/Python/Chapter 01/01. Basics/02. Shuffling the words.py
1,095
4.15625
4
## Egor Kolesnikov ## ## Shuffling letters in words. First and last letters are not changing their positiona. ## import sys import random import string import re def shuffle_one_word(word): if len(word) > 3: temp_list = list(word[1:-1]) random.shuffle(temp_list) word = word[0] + ''.join(temp_list) + word[-1] return word def check_scientists_theory(whole_text): pattern = re.compile("[^a-zA-Z_]") only_words = re.sub(pattern, ' ', whole_text).split() position = 0 word_count = 0 while position < len(whole_text): if whole_text[position].isalpha(): shuffled = shuffle_one_word(only_words[word_count]) length = len(shuffled) whole_text = (whole_text[0:position] + shuffled + whole_text[(position + length):]) word_count += 1 position += length else: position += 1 return whole_text text = sys.stdin.read() result = check_scientists_theory(text) print(result)
true
3127d121f6f06faa85a09de26f6879220b6fd00d
paarubhatt/Assignments
/Fibonacci series.py
634
4.34375
4
#Recursive function to display fibonacci series upto 8 terms def Fibonacci(n): #To check given term is negative number if n < 0: print("Invalid Input") #To check given term is 0 ,returns 0 elif n == 0: return 0 # To check given term is either 1 or 2 because series for 1 or 2 terms will be 0 1 elif n == 1 or n == 2: return 1 #Return a series until term value exceeds else: return Fibonacci(n-1)+Fibonacci(n-2) #initialized term value term = 8 #For loop prints the fibonacci series upto 8 terms for i in range(term): print(Fibonacci(i))
true
a48e9a490f51dbd08f9cec47f9de5bd6eab47712
megha-20/String_Practice_Problems
/Pattern_Matching.py
544
4.34375
4
# Function to find all occurrences of a pattern of length m # in given text of length n def find(text,pattern): t = len(text) p = len(pattern) i = 0 while i <= t-p: for j in range(len(p)): if text[i+j] is not pattern[j]: break if j == m-1: print("Pattern occurs with shift",i) i = i+1 # Program to demonstrate Naive Pattern Matching Algorithm in Python text = "ABCABAABCABAC" pattern = "CAB" find(text,pattern)
true
95355c972888adfa97a5ce64afbb80effedfd3f4
pauleclifton/GP_Python210B_Winter_2019
/students/jeremy_m/lesson04_exercises/dict_lab.py
1,493
4.125
4
#!/usr/bin/env python3 # Lesson 04 Exercise: Dictionary and Set Lab # Jeremy Monroe dict_one = {"name": "Chris", "city": "Seattle", "cake": "Chocolate"} print("Dictionaries 1") print(dict_one) del dict_one['cake'] print(dict_one) dict_one['fruit'] = 'Mango' print('\n\nDict Keys:') for key in dict_one: print(key + ', ', end='') print() print('\nDict Values:') for value in dict_one.values(): print(value + ', ', end='') print() print('\nIs cake a key in dict_one?') print('cake' in dict_one) print('\nIs Mango a value in dict_one?') print('Mango' in dict_one.values()) print('\n\nDictionaries 2') temp_dict = {} t_count = 0 for key, value in dict_one.items(): for letter in value: if letter.lower() == 't': t_count += 1 temp_dict[key] = t_count t_count = 0 print(dict_one) print(temp_dict) print('\n\nSets 1') s2 = {i for i in range(21) if i % 2 == 0} s3 = {i for i in range(21) if i % 3 == 0} s4 = {i for i in range(21) if i % 4 == 0} print('s2: {}\ns3: {}\ns4: {}'.format(s2, s3, s4)) print('\nIs s3 subset of s2? : {}'.format(s3.issubset(s2))) print('Is s4 subset of s2? : {}'.format(s4.issubset(s2))) print('\n\nSets 2') set_python = {'P', 'y', 't', 'h', 'o', 'n'} set_python.add('i') mara_set = {'m', 'a', 'r', 'a', 't', 'h', 'o', 'n'} mara_frozen_set = frozenset(mara_set) print('Union of sets: {}'.format(set_python.union(mara_frozen_set))) print('Intersection of sets: {}'.format(set_python.intersection(mara_frozen_set)))
false
8f70983510f211453fb51f8f9c396f58eaee33b7
pauleclifton/GP_Python210B_Winter_2019
/students/douglas_klos/session8/examples/sort_key.py
1,286
4.3125
4
#!/usr/bin/env python3 """ demonstration of defining a sort_key method for sorting """ import random import time class Simple: """ simple class to demonstrate a simple sorting key method """ def __init__(self, val): self.val = val def sort_key(self): """ sorting key function --used to pass in to sort functions to get faster sorting Example:: sorted(list_of_simple_objects, key=Simple.sort_key) """ return self.val def __lt__(self, other): """ less than --required for regular sorting """ return self.val < other.val def __repr__(self): return "Simple({})".format(self.val) if __name__ == "__main__": N = 10000 a_list = [Simple(random.randint(0, 10000)) for i in range(N)] # print("Before sorting:", a_list) print("Timing for {} items".format(N)) start = time.clock() sorted(a_list) reg_time = time.clock() - start print("regular sort took: {:.4g}s".format(reg_time)) start = time.clock() sorted(a_list, key=Simple.sort_key) key_time = time.clock() - start print("key sort took: {:.4g}s".format(key_time)) print("performance improvement factor: {:.4f}".format((reg_time / key_time)))
true
25755d77d073cc66284597e63283cd3f93b14fc3
pauleclifton/GP_Python210B_Winter_2019
/students/douglas_klos/extra/rot13/rot13.py
699
4.34375
4
#!/usr/bin/env python3 """ Function to convert rot13 'encrypt' """ # Douglas Klos # March 6th, 2019 # Python 210, Extra # rot13.py # a - z == 97 - 122 # A - Z == 65 - 90 # We'll ignore other characters such as punctuation def rot13(value): """ Function to perform rot13 on input """ output = '' for letter in value: if ord(letter) >= 97 and ord(letter) <= 122: output += chr(ord(letter) - 13) if ord(letter) >= 110 else chr(ord(letter) + 13) elif ord(letter) >= 65 and ord(letter) <= 90: output += chr(ord(letter) - 13) if ord(letter) >= 78 else chr(ord(letter) + 13) else: output += letter print(output) return output
false
0bd34168459f1da60426f683ac7ce4ffb5eebc4a
pauleclifton/GP_Python210B_Winter_2019
/students/jeremy_m/lesson03_exercises/slicing_lab.py
1,499
4.5
4
#!/usr/bin/env python3 # Lesson 03 - Slicing Lab # Jeremy Monroe def first_to_last(seq): """ Swaps the first and last items in a sequence. """ return seq[-1] + seq[1:-1] + seq[0] # print(first_to_last('hello')) assert first_to_last('dingle') == 'eingld' assert first_to_last('hello') == 'oellh' def every_other(seq): """ Returns a sequence with every other item removed """ return seq[::2] # print(every_other('hello')) assert every_other('hello') == 'hlo' assert every_other('cornholio') == 'crhlo' def first_four_last_four(seq): """ Removes the first four and last four items and then removes every other item from what is left. """ return seq[4:-4:2] # print(first_four_last_four("I'll need a long sequence for this")) assert first_four_last_four("I'll need a long sequence for this") == ' edaln eunefr' assert first_four_last_four('Many mangy monkeys') == ' ag o' def reverso(seq): """ Returns a sequence in reverse order. """ return seq[::-1] # print(reverso('ham sammich')) assert reverso('ham sammich') == 'hcimmas mah' assert reverso('Turkey sandwhich') == 'hcihwdnas yekruT' def thirds_reversal(seq): """ Returns a sequence with what was the last third now first, followed by the first third, and middle third. """ return seq[-(len(seq) // 3):] + seq[:-(len(seq) // 3)] # print(thirds_reversal('easy string')) assert thirds_reversal('easy string') == 'ingeasy str' assert thirds_reversal('twelve letters ') == "ters twelve let"
true
4e71942f4dfb235107981620e653050980bd8f5d
pauleclifton/GP_Python210B_Winter_2019
/students/jesse_miller/session02/print_grid2-redux.py
931
4.375
4
#!/usr/local/bin/python3 # Asking for user input n = int(input("Enter a number for the size of the grid: ")) minus = (' -' * n) plus = '+' """Here, I'm defining the variables for printing. Made the math easier this way""" def print_line(): print(plus + minus + plus + minus + plus) """This defines the tops and bottoms of the squares""" def print_post(): print('|' + (' ' * (2*n) ) + '|' + (' ' * (2*n) ) + '|'), """This defines the column markers. The 2*n is to compensate for the length of the column being double the length of a row in print""" def print_grid(): """The remainder of the magic. It doubles the above function and prints the last row""" print_line() for line in range(2): for post in range(n): print_post() print_line() print_grid() """This defines the grid function. It executes print_row twice through do_two, and the print_line to close the square."""
true
a8f751f2df136d17415a32d53cf8ffe2d060b574
pauleclifton/GP_Python210B_Winter_2019
/students/ScottL/session02/fizzbuzz.py
468
4.1875
4
def FizzBuzz(): """Return a list of integers from 1 - 100 (inclusive) where numbers divisible by 3 return 'Fizz', integers divisible by 5 return 'Buzz' and integers divisible by both 3 & 5 return 'FizzBuzz' """ for i in range(1, 101): if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i) FizzBuzz()
false
883a6827c335dd475687f06cd829f20a12dc0010
pauleclifton/GP_Python210B_Winter_2019
/students/alex_whitty/session03/list_lab_series1.py
782
4.1875
4
#!/usr/bin/env python3 fruits = ['apples', 'pears', 'oranges', 'peaches'] print(fruits) new_fruit = input("Which fruit would you like to add? >>>") fruits.append(new_fruit) print(fruits) item_num = input("Which item number do you want to see? >>>") if item_num == "1": print("You chose 1," + " the fruit is " + fruits[0]) elif item_num == "2": print("You chose 2," + " the fruit is " + fruits[1]) elif item_num == "3": print("You chose 3," + " the fruit is " + fruits[2]) elif item_num == "4": print("You chose 4," + " the fruit is " + fruits[3]) elif item_num == "5": print("You chose 5," + " the fruit is " + fruits[4]) else: print("Invalid item number.") fruits.insert(0, 'bananas') print(fruits) for fruit in fruits: if fruit[0] == "p": print(fruit)
false
d73861363b1723dc3aafade4529f5ed030429680
pauleclifton/GP_Python210B_Winter_2019
/students/jeremy_m/lesson03_exercises/string_formatting_lab.py
1,594
4.34375
4
#!/usr/bin/env python3 # lesson 03 Exercise - String Formatting Lab # Jeremy Monroe # TASK 1 first_tup = (2, 123.4567, 10000, 12345.67) print('Task one:') print('file_{:03d} : {:06.2f}, {:.2E}, {:.2E}'.format(*first_tup)) # TASK 2 print('\nTask Two:') print( f'file_{first_tup[0]:03d} : {first_tup[1]:06.2f}, {first_tup[2]:.2E}, {first_tup[3]:.2E}') # TASK 3 print("\nTask Three:") def formatter(seq): l = len(seq) return ("the {} numbers are: " + ", ".join(['{}'] * l)).format(l, *seq) print(formatter(first_tup)) print(formatter((1, 4, 5, 6, 7, 3, 2, 1))) # TASK 4 print("\nTask Four:") task_four_tup = (4, 30, 2017, 2, 27) for num in sorted(task_four_tup): print('{:03d} '.format(num), end="") print() # TASK 5 print("\nTask Five:") task_five_list = ['oranges', 1.3, 'lemons', 1.1] print( f'The weight of an {task_five_list[0][:-1]} is {task_five_list[1]} and the weight of a {task_five_list[2][:-1]} is {task_five_list[3]}') print( f'The weight of an {task_five_list[0][:-1].upper()} is {task_five_list[1] * 1.2} and the weight of a {task_five_list[2][:-1].upper()} is {task_five_list[3] * 1.2}') # TASK 6 print("\nTask Six:") task_six_tup = (['Pretzel', '12', '$5.75'], ['Tuna Fish', '62', '$62.99'], [ 'PB&J', '4', '$126.33'], ['Freeze Dried Tomato', '664', '$1242.96']) days_old = 'Days Old' for task in task_six_tup: print(f'{task[0]:25}{task[1]:5}{days_old:15}{task[2]}') print('\nSecond part of task six') task_six_tup_two = (123, 223, 32, 3, 53, 623, 7124, 842, 9, 10) print(("".join(['{:5}'] * 10).format(*task_six_tup_two)))
false
4bad0ec8024dea5b25d678ea50a74313474066f5
pauleclifton/GP_Python210B_Winter_2019
/students/elaine_x/session03/slicinglab_ex.py
1,915
4.40625
4
''' ########################## #Python 210 #Session 03 - Slicing Lab #Elaine Xu #Jan 28,2019 ########################### ''' #Write some functions that take a sequence as an argument, and return a copy of that sequence: #with the first and last items exchanged. def exchange_first_last(seq): '''exchange the first and last items''' first = seq[len(seq)-1:len(seq)] mid = seq[1:len(seq)-1] last = seq[0:1] return first+mid+last #with every other item removed. def remove_every_other(seq): '''remove every other item''' return seq[::2] #with the first 4 and the last 4 items removed, and then every other item in the remaining sequence. def remove_4_every_other(seq): '''remove the first 4 and last 4, the nevery other item''' seq1 = seq[4:-4] seq2 = seq1[::2] return seq2 #with the elements reversed (just with slicing). def reverse_element(seq): '''reverse the elements''' return seq[::-1] #with the last third, then first third, then the middle third in the new order. def last_first_mid(seq): '''with the last third, then first third, then the middle third in the new order''' mid_seq = len(seq)//2 return seq[-3:]+seq[:3]+seq[mid_seq-1:mid_seq+2] #tests A_STRING = "this is a string" A_TUPLE = (2, 54, 13, 12, 5, 32) B_TUPLE = (2, 54, 13, 12, 5, 32, 2, 5, 17, 37, 23, 14) assert exchange_first_last(A_STRING) == "ghis is a strint" assert exchange_first_last(A_TUPLE) == (32, 54, 13, 12, 5, 2) assert remove_every_other(A_STRING) == "ti sasrn" assert remove_every_other(A_TUPLE) == (2, 13, 5) assert remove_4_every_other(A_STRING) == " sas" assert remove_4_every_other(B_TUPLE) == (5, 2) assert reverse_element(A_STRING) == "gnirts a si siht" assert reverse_element(A_TUPLE) == (32, 5, 12, 13, 54, 2) assert last_first_mid(A_STRING) == "ingthi a " assert last_first_mid(A_TUPLE) == (12, 5, 32, 2, 54, 13, 13, 12, 5) print("test completed")
true
9e2062f46a32508373a55afb7fb110dda8579d4e
markuswesterlund/beetroot-lessons
/python_skola/rock_paper_scissor.py
651
4.28125
4
import random print("Let's play rock, paper, scissor") player = input("Choose rock, paper, scissor by typing r, p or s: ") if player == 'r' or player == 'p' or player == 's': computer = random.randint(1, 3) # 1 == r # 2 == p # 3 == s if (computer == 1 and player == 'r' or computer == 2 and player == 'p' or computer == 3 and player == 's'): print("It is a draw") elif (computer == 1 and player == 'p' or computer == 2 and player == 's' or computer == 3 and player == 'r'): print("Gz, you win!") else: print("You lost noob!") else: print("Your input was in the wrong format, no game for you")
true
d57b6adc5a6e62ce236f104c577c1329925b84ae
markuswesterlund/beetroot-lessons
/python_skola/Beetroot_Academy_Python/Lesson 4/guessing_game.py
557
4.25
4
import random print("Try to guess what number the computer will randomly select: ") numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] player = input("Choose a number between 1-10: ") if int(player) in numbers: computer = random.randint(1, 10) if player == computer: print("The computers number was:", computer, "and your number was:", player) print("You win!") else: print("The computers number was:", computer, "and your number was:", player) print("You lose!") else: print("Sorry this game really isn't for you")
true
6e3ce3b082ca45aa478ee73fdc200b84f13e7b45
manuel-garcia-yuste/ICS3UR-Unit6-04-Python
/2d_list.py
1,456
4.46875
4
#!/usr/bin/env python3 # Created by: Manuel Garcia Yuste # Created on : December 2019 # This program finds the average of all elements in a 2d list import random def calculator(dimensional_list, rows, columns): # this finds the average of all elements in a 2d list total = 0 for row_value in dimensional_list: for single_value in row_value: total += single_value total = total/(rows*columns) return total def main(): # this function places random integers into a 2D list dimensional_list = [] # Input rows = (input("How many rows would you like: ")) columns = (input("How many columns would you like: ")) try: # Process rows = int(rows) columns = int(columns) for rows_loop in range(0, rows): temp_column = [] for column_loop in range(0, columns): random_int = random.randint(1, 50) temp_column.append(random_int) # Output 1 print("Random Number " + str(rows_loop + 1) + ", " + str(column_loop + 1) + " is " + str(random_int)) dimensional_list.append(temp_column) print("") # Output 2 averaged = calculator(dimensional_list, rows, columns) print("The average of the random numbers is: {0} ".format(averaged)) except Exception: print("Invalid input") if __name__ == "__main__": main()
true
4e1a819c2a901470c8b7200035ce3dcb04e87c16
rbose4/Python-Learning
/hello.py
1,115
4.125
4
# My first python program print("Hello World") print("My favourite song is We will rock you") print("My favourite movie is Sound of Music") print("My favourite day for the year is November", 18) print() print("Hello") print("World!") print("Hello World") print() print('Good to see you') print("My favorite numbers are",10+5,"and",3+6) print("Good morning","'Roopa!'",sep='') print('G','F','H',sep=',') print('G','F','H',sep='') print('09','12','2016',sep=',') print('roopbose9','gmail',sep='@',end='.') print('com') print('Hello') print('WOrld') print('roopbose9','gmail',sep='@',end='78') print('bose') ## # Lab excercise 2 # integer1 = int(input("Please enter the first number:")) integer2 = int(input("Please enter the second number:")) sum = integer1 + integer2 product = integer1 * integer2 distance = abs(integer1 - integer2) average_num = sum/2 maxvalue = max(integer1, integer2) print("%-10s %-3d" % ("Sum:", sum)) print("%-10s %-3d" % ("Product:", product)) print("%-10s %-3d" % ("Distance:", distance)) print("%-10s %-3d" % ("Average:", average_num)) print("%-10s %-3d" % ("Maximum:", maxvalue))
false
9981b9084b75157e002eeab791beda9a40af6555
Linh-T-Pham/Study-data-structures-and-algorithms-
/palindrome_recursion.py
1,326
4.34375
4
""" Write a function that takes a string as a parameter and returns True if the string is a palindrome, False otherwise. Remember that a string is a palindrome if it is spelled the same both forward and backward. For example: radar is a palindrome. for bonus points palindromes can also be phrases, but you need to remove the spaces and punctuation before checking. for example: madam i’m adam is a palindrome. Other fun palindromes include: >>> recursive_palin("kayak") True >>> recursive_palin("aibohphobia") True >>> recursive_palin("able was i ere i saw elba") True >>> recursive_palin("kanakanak") True >>> recursive_palin("wassamassaw") True >>> recursive_palin("Go hang a salami; I’m a lasagna hog") True """ def recursive_palin(string): """ use recursion to solve this problem """ # slice_string = string[::-1].lower() # if string == slice_string: # return True # return False if len(string) <= 1: return True if string[0] == string[len(string)-1]: return recursive_palin(string[1: len(string)-1]) return False if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. GO GO GO!\n")
true
012ab172576e4caa22fa0661ae304825a6e0f3a5
Linh-T-Pham/Study-data-structures-and-algorithms-
/merge_ll.py
2,625
4.15625
4
""" Merge Linked Lists Write a function that takes in the heads of two singly Ll that are in sorted order, respectively. The function should merge the lists in place(i.e, it should not create a brand new list and return the head of the merged list; the merged list should be in sorted order) Each linked list node has an integer value as well as a next node pointing to the next node in the list or to None/Null if its the tail of the list. You can assume that input linked lists will always have at least one node; in other words, the heads will be never be None/Null. """ class Node: def __init__(self, value): self.value = value self.next = None # last item # if # h1 > h2 # insert head_two.data before head_one.data # pointer2 += 1 # else: # h1 < h2: # insert head_two.data after head_one.data # head_one 1-2-6-7-8 # head_two 4-5-10-11-12 # out put 4 """ """ def merge_ll(head1, head2): p1prev = None p1 = head1 p2 = head2 while p1 is not None and p2 is not None: if p1.value < p2.value: # p1 = p1.next p1prev = p1 p1 = p1.next elif p1.value > p2.value: if p1 is not None: # What happen when P1 is not None p1prev.next = p2 # because p1pev is None so it does not make sense # to assign p1prev = p2 p1prev = p2 p2 = p2.next p1prev.next = p1 if p1 is None: p1prev.next = p2 if head1.value < head2.value: return head1 else: return head2 head_one = Node(2) head_one.next = Node(6) head_one.next.next = Node(7) head_one.next.next.next = Node(8) head_two = Node(1) head_two.next = Node(3) head_two.next.next = Node(4) head_two.next.next.next = Node(5) head_two.next.next.next.next = Node(9) head_two.next.next.next.next.next = Node(10) # def merge_ll(head_one, head_two): # point1 = head_one # point2 = head_two # point1_prev = None # previous node in the first linked list # # 1 -> 6 ->7 # while point1 is not None and point2 is not None: # if point1 < point2: # point1_prev = point1 #none #6 # point1 = point1.next #1 #7 # else: # # p2 comes before p1 # # so p1prev shoudl point to p2 # if point1_prev is not None: # point1_prev = point2 # point_prev = point1 # before overwite p2 # point2 = point2.next # point1_prev.next = point1
true
1cca158cb53fe6acf0e9c972240e43af6f30efe1
Linh-T-Pham/Study-data-structures-and-algorithms-
/recursion2.py
596
4.5
4
"""Write a function, reverseString(str), that takes in a string. The function should return the string with it's characters in reverse order. Solve this recursively! Examples: >>> reverseString("") '' >>> reverseString("c") 'c' >>> reverseString("internet") 'tenretni' >>> reverseString("friends") 'sdneirf' """ def reverseString(Str): if Str == "": return Str return reverseString(Str[1:]) + Str[0] if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** Awesome!. GO GO GO!\n")
true
b83be788e7f15af3f915632c37ea64314b4b12a8
mariormt17/Lenguajes-y-Automatas-2
/triangulo.py
805
4.1875
4
#Nombre: triangulo.py #Objetivo: identifica el tipo de triangulo de acuerdo al valor de sus lados #Autor: Mario Rubén Mancilla Tinoco #Fecha: 01 de julio 2019 #Función para identificar el tipo de triangulo def identificar(l1, l2, l3): if(l1 == l2 and l1 == l3): print("EL triangulo ingresado es Equilatero") elif(l1 != l2 and l1 != l3 and l2 != l3): print("El triangulo ingresado es Escaleno") else: print("EL triangulo ingresado es Isoceles") #Función principal def main(): print("---Script para identificar triangulos") lado1 = float(input("Ingrese el lado 1: ")) lado2 = float(input("Ingrese el lado 2: ")) lado3 = float(input("Ingrese el lado 3: ")) #Invocar funcion identificar(lado1, lado2, lado3) print("EL perimetro del triangulo es: ",(lado1 + lado2 + lado3)) if __name__ == '__main__': main()
false
7cb17368d61a76b8bda586fdb12c656cf9f4f37f
Timothy-py/Python-Challenges
/Factorial.py
986
4.40625
4
# A Python program to print the factorial of a number # L1 - This line of code creates a variable named 'multiplier' which will # be used to save the successive multiplications and it # is initialized to 1 because it will be used to do the first multiplication # L3 - Prompt the user to enter a number and save the number in a variable named 'number' # L5 - The for loop is used to take each number in the range of number entered from 1 to number inclusive # L6 - This line is the same as writing multiplier = multiplier * i, which implies that it takes the value of i and # multiplied it with multiplier(which is initially 1) and in turn save the result in the multiplier variable # L7 - The print() function is used to print the output with the help of the format() method, the curly braces # {} are called placeholders multiplier = 1 number = int(input('Enter the number here :')) for i in range(1, number+1): multiplier *= i print('{}! is = {}'.format(number, multiplier))
true
ca3c224af2531b5777378548a13d2cb2e980bd8a
aloysiogl/CES-22_solutions
/Bimester1/Class1/ex6/exercise6.py
1,316
4.40625
4
#!/usr/bin/python3 import turtle from time import sleep # Question # Use for loops to make a turtle draw these regular polygons (regular means all sides the same # lengths, all angles the same): # ◦ An equilateral triangle # ◦ A square # ◦ A hexagon (six sides) # ◦ An octagon (eight sides) # Function for drawing polygons def drawPoly(nSides, turtle, side = 50): # Turtle speed turtle.speed(1) # Turtle style turtle.color("blue") turtle.shape("turtle") turtle.pencolor("black") turtle.pensize(3) # Using degrees units turtle.degrees() # Showing turtle turtle.showturtle() # Drawing the polygon for i in range(0, nSides): turtle.forward(side) turtle.left(360/nSides) # End animation turtle.left(360) # Hiding turtle turtle.hideturtle() # Getting screen wn = turtle.Screen() # Setting screen parameters wn.bgcolor("lightblue") wn.title("Tartaruga do Aloysio") # Creating turtle aloysio = turtle.Turtle() # Drawing polygons # Triangle drawPoly(3, aloysio, 200) sleep(3) wn.reset() # Square drawPoly(4, aloysio, 180) sleep(3) wn.reset() # Hexagon drawPoly(6, aloysio, 100) sleep(3) wn.reset() # Octagon drawPoly(8, aloysio, 80) sleep(3) wn.reset() # Keeping the window open wn.mainloop()
true
7d7fe99aa3c635252af1a6d74b987fd0ec42c5ba
aloysiogl/CES-22_solutions
/Bimester1/Class6/decorators/decorators.py
1,014
4.3125
4
#!/usr/bin/python3 def round_area(func): """ This decorators rounds the area :param func: area function :return: the rounded area function """ def round_area_to_return(side): """ This function calculates the rounded area to 2 decimal digits :param side: the side of the square :return: the area """ return round(func(side), 2) return round_area_to_return @round_area def get_square_area_with_decorator(side): """ This function calculates the area of a square using the round decorator :param side: the side of the square :return: the area """ return side*side def get_square_area_without_decorator(side): """ This function calculates the area of a square :param side: the side of the square :return: the area """ return side*side print("Result with decorator", get_square_area_with_decorator(5.1234)) print("Result without decorator", get_square_area_without_decorator(5.1234))
true
f34db4522943068e6e25c0984a6bc52859e92c3a
kbalog/uis-dat630-fall2016
/practicum-1/tasks/task4.py
1,090
4.5625
5
# Finding k-nearest neighbors using Eucledian distance # ==================================================== # Task # ---- # - Generate n=100 random points in a two dimensional space. Let both # the x and y attributes be int values between 1 and 100. # - Display these points on a scatterplot. # - Select one of these points randomly (i.e., pick a random index). # - Find the k closest neighbors of the selected record (i.e., the k records # that are most similar to it) using the Eucledian distance. # The value of k is given (i.e., hard-coded). # - Display the selected record and its k closest neighbors in a distinctive # manner on the plot (e.g., using different colors). # Solution # -------- # We import the matplotlib submodule **pyplot**, to plot 2d graphics; # following a widely used convention, we use the `plt` alias. import matplotlib.pyplot as plt # The number of random points we want. n = 100 # The number of nearest neighbors. k = 5 # Generate random points with x and y coordinates. # TODO # Find k-nearest neighbors. # TODO # Plot data. # TODO
true
dac2cb25d763900c9b477c0ec27f813b500e2d89
newbieeashish/datastructures_algo
/ds and algo/linkedlist,stack,queue/falttenLL.py
2,556
4.34375
4
'''Suppose you have a linked list where the value of each node is a sorted linked list (i.e., it is a nested list). Your task is to flatten this nested list—that is, to combine all nested lists into a single (sorted) linked list.''' #creating nodes and linked List class Node: def __init__(self,value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self,head): self.head = head def append(self,value): if self.head is None: self.head = Node(value) return node = self.head while node.next: node = node.next node.next = Node(value) def merge(list1, list2): merged = LinkedList(None) if list1 is None: return list2 if list2 is None: return list1 list1_elt = list1.head list2_elt = list2.head while list1_elt is not None or list2_elt is not None: if list1_elt is None: merged.append(list2_elt) list2_elt = list2_elt.next elif list2_elt is None: merged.append(list1_elt) list1_elt = list1_elt.next elif list1_elt.value <= list2_elt.value: merged.append(list1_elt) list1_elt = list1_elt.next else: merged.append(list2_elt) list2_elt = list2_elt.next return merged class NestedLinkedList(LinkedList): def flatten(self): return self._flatten(self.head) def _flatten(self,node): if node.next is None: return merge(node.value,None) return merge(node.value,self._flatten(node.next)) linked_list = LinkedList(Node(1)) linked_list.append(3) linked_list.append(5) second_linked_list = LinkedList(Node(2)) second_linked_list.append(4) merged = merge(linked_list, second_linked_list) node = merged.head while node is not None: # This will print 1 2 3 4 5 print(node.value) node = node.next # Lets make sure it works with a None list merged = merge(None, linked_list) node = merged.head while node is not None: # This will print 1 2 3 4 5 print(node.value) node = node.next nested_linked_list = NestedLinkedList(Node(linked_list)) nested_linked_list.append(second_linked_list) flattened = nested_linked_list.flatten() node = flattened.head while node is not None: #This will print 1 2 3 4 5 print(node.value) node = node.next
true
a6412b37f0cbd97d812d04f6edb564fb43c19b31
newbieeashish/datastructures_algo
/ds and algo/Sorting_algos/counting_inversions.py
2,026
4.15625
4
'''Counting Inversions The number of inversions in a disordered list is the number of pairs of elements that are inverted (out of order) in the list. Here are some examples: [0,1] has 0 inversions [2,1] has 1 inversion (2,1) [3, 1, 2, 4] has 2 inversions (3, 2), (3, 1) [7, 5, 3, 1] has 6 inversions (7, 5), (3, 1), (5, 1), (7, 1), (5, 3), (7, 3) The number of inversions can also be thought of in the following manner. Given an array arr[0 ... n-1] of n distinct positive integers, for indices i and j, if i < j and arr[i] > arr[j] then the pair (i, j) is called an inversion of arr. Problem statement Write a function, count_inversions, that takes an array (or Python list) as input, and returns a count of the total number of inversions present in the input.''' def count_inversions(items): if len(items) <= 1: return items,0 mid = len(items)//2 left = items[:mid] right = items[mid:] inversion_left = 0 inversion_right = 0 left, inversion_left = count_inversions(left) right, inversion_right = count_inversions(right) merged, inversions = merge(left,right) return merged, inversion_left+inversion_right+inversions def merge(left,right): merged = [] inversions = 0 left_index = 0 right_index =0 while left_index < len(left) and right_index < len(right): if left[left_index] > right[right_index]: merged.append(right[right_index]) inversions +=1 right_index +=1 else: merged.append(left[left_index]) left_index +=1 merged += left[left_index:] merged += right[right_index:] return merged,inversions def test_function(test_case): arr = test_case[0] solution = test_case[1] if count_inversions(arr)[1] == solution: print("Pass") else: print("Fail") arr = [2, 5, 1, 3, 4] solution = 3 test_case = [arr, solution] test_function(test_case)
true
d25ae8395ca06e243b00f3041c19c90c9402377a
mahasahyoun/python-for-everybody
/ch-2/gross-pay.py
586
4.1875
4
""" Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking or bad user data. """ # Get inputs as strings strHrs = input("Enter Hours:") strRate = input("Enter Rate:") # Convert inputs from string to number floatHrs = float(strHrs) floatRate= float(strRate) # Compute gross pay grossPay = floatHrs * floatRate print("Pay:", grossPay)
true
6e161afe596049d1f120fbc2e8ad3f7cd41e411c
patrickForster/Sandbox
/password_entry.py
388
4.25
4
# password checker MIN_LENGTH = 4 print("Please enter a valid password") print("Your password must be at least", MIN_LENGTH, "characters long") password = input("> ") while len(password) < MIN_LENGTH: print("Not enough characters!") password = input("> ") hidden_password = len(password)*'*' print("Your {}-character password is valid: {}".format(len(password), hidden_password))
true
fd6140a6a5012f540e30db95bcb99baf6bd5dd78
sczhan/wode
/xitike(习题课)/xitike(第4章python高级语法)/xitike37.py
1,599
4.125
4
# 编写一个计算减法的方法, 当第一个数小于第二个数时, 抛出"被减数不能小于减数的异常" # def jianfa(a, b): # if int(a) < int(b): # raise BaseException("被减数不能小于减数") # else: # return int(a) - int(b) # # try: # jianfa(3, 7) # except BaseException as error: # print("好像出错了, 出错的内容是{}".format(error)) # 定义一个函数func(filename)filename: 文件路径, # 函数功能: 打开文件, 并且返回文件内容, 最后关闭, 用异常来处理可能发生的错误 # # import os # # # def func(filename): # try: # file = open(filename) # except Exception as error: # print("出错了, 出错的内容是{}".format(error)) # else: # print(file.read()) # file.close() # # # func("haha.txt") # 自己定义一个异常类, 继承Exceptionlei, 铺货下面过程:判断输入的字符串长度是是否小于5 # # # class MyError(Exception): # def __init__(self, str): # self.str = str # # def process(self): # if len(self.str) < 5: # print("字符串长度必须大于5") # else: # print("算你聪明") # # try: # er = MyError("ssss") # er.process() # except MyError as error: # print(error) def jianfa(a, b): try: if int(a) < int(b): raise BaseException("被减数不能小于减数") else: return a - b except BaseException as error: print("好像出错了, 出错的内容是{}".format(error)) print(jianfa(8, 7))
false
f7b19217b3ef9895ba0151e729e668e2f7e962cf
ericdong66/leetcode-50
/python/48.search_insert_position.py
1,101
4.1875
4
# Given a sorted array and a target value, return the index if the target is # found. If not, return the index where it would be if it were inserted in # order. # # You may assume no duplicates in the array. # # Here are few examples. # [1,3,5,6], 5 -> 2 # [1,3,5,6], 2 -> 1 # [1,3,5,6], 7 -> 4 # [1,3,5,6], 0 -> 0 # # Time: O(log(n)) # Space: O(1) import argparse class Solution(object): @staticmethod def search_insert(nums, target): left, right = 0, len(nums) - 1 while left <= right: middle = left + (right - left) // 2 if nums[middle] >= target: right = middle - 1 else: left = middle + 1 return left if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--list', dest='list', required=True, nargs='+', help='list of integer') parser.add_argument('--target', dest='target', required=True, help='target number') args = parser.parse_args() print(Solution.search_insert(args.list, args.target))
true
8678563bed00c089031a5522b26b6747e23f7859
victorwp288/kea_python
/misc/list.py
2,613
4.34375
4
# By using the slicing syntax change the following collections. # After slicing: # ['Hello', 'World', 'Huston', 'we', 'are', 'here'] should become -> ['World', 'Huston', 'we', 'are'] # ['Hello', 'World', 'Huston', 'we', 'are', 'here'] -> ['Hello', 'World'] # ['Hello', 'World', 'Huston', 'we', 'are', 'here'] -> ['are', 'here'] # ['Hello', 'World', 'Huston', 'we', 'are', 'here'] -> ['are'] # ['Hello', 'World', 'Huston', 'we', 'are', 'here'] -> ['Hello', 'Huston', 'are'] # ['Hello', 'World', 'Huston', 'we', 'are', 'here'] -> ['here', 'are', 'we', 'Huston', 'World', 'Hello'] # ('Hello', 'World', 'Huston', 'we', 'are', 'here') should become -> ['World', 'Huston', 'we', 'are'] # 'Hello World Huston we are here' -> 'World Huston we' # Figure out more on your own and practice this a lot! # Ex 1: Build-in functions on lists # Look at this list of pythons build in functions. # Try all of these in the interpretor (on a list you create). e.g len(a) # Not all will work on lists, but try it out and see what works. # Ex 2: Sort a Text # Solution l = [] def sort_list(x): for i in x: if i in ['a', 'e', 'i', 'o', 'u', 'y', 'æ', 'ø', 'å']: l.append(i) l.sort() return print(l) sort_list('hello world') # Create a function that takes a string as a parameter and returns a list. # The function should remove all vowels and sort the consonants in alphabetic order, and the return the result. # Ex 3: Sort a list # Solution # Create a list of strings with names in it. (l = [‘Claus’, ‘Ib’, ‘Per’]) # Sort this list by using the sorted() build in function. # Sort the list in reversed order. # Sort the list on the lenght of the name. # Sort the list based on the last letter in the name. # Sort the list with the names where the letter ‘a’ is in the name first. # Ex 4: Files # Solution # Create a file and call it lyrics.txt (it does not need to have any content) # Create a new file and call it songs.docx and in this file write 3 lines of text to it. # open and read the content and write it to your terminal window. * you should use both the read(), readline(), and readlines() methods for this. (so 3 times the same output). # Ex 5: Sort a list of tuples # Solution # 1. Based on this list of tuples: [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3, 1)] t = [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3, 1)] sorted(t, ) # 2. Sort the list so the result looks like this: [(2, 1), (3, 1), (10, 1), (1, 2), (2, 2), (2, 2), (3, 2), (10, 4), (1, 5)]
false
2b9172bdbc0e4eee3650c75033c6610faabfeecc
zentino/CVIS
/intro to python/Aufgabe2.py
1,754
4.21875
4
#Aufgabe 2: #Schreibe ein Python Programm, das #- Die Konvertierung von Temperaturangaben in Celsius nach Fahrenheit oder Kelvin ermöglicht #- Zuerst wird beim Benutzer abgefragt welche Konvertierung er machen möchte #- Danach muss der Benutzer eine Temperatur in Celsius angeben #- Es wir die Temperatur in Fahrenheit oder Kelvin ausgegeben #Hinweise: #- Celsius = 5/9 * (Fahrenheit - 32). #- Celsius = Kelvin - 273.15. #- Die tiefste mögliche Temperatur ist der absolute Nullpunkt von -273.15 Grad Celsius def converter(): print("Geben Sie die Zahl '1' für die Konvertierung in Celcius nach Fahrenheit ein.\n") print("Geben Sie die Zahl '2' für die Konvertierung in Celcius nach Kelvin ein.") x = input("Eingabe Zahl -> ") if x == "1": print("Celsius -> Fahrenheit\n") celsius = input("Geben Sie eine Temperatur in Celsius ein -> ") celsius = float(celsius) while celsius < -273.15: print("Die tiefste mögliche Temperatur ist -273.15 Grad Celsius") celsius = input("Bitte geben Sie eine Temperatur in Celsius >= -273.15 Grad ein -> ") celsius = float(celsius) fahrenheit = celsius * 9/5 + 32 print(fahrenheit) elif x == "2": print("Celsius -> Kelvin\n") celsius = input("Geben Sie eine Temperatur in Celsius ein -> ") celsius = float(celsius) while celsius < -273.15: print("Die tiefste mögliche Temperatur ist -273.15 Grad Celsius") celsius = input("Bitte geben Sie eine Temperatur in Celsius >= -273.15 Grad ein -> ") celsius = float(celsius) kelvin = celsius + 273.15 print(kelvin) else: converter() converter()
false
222c0630766643a98e24c8218c8bf148fd2c514d
h3llopy/web-dev-learning
/Learn Python the Hard Way/exercises/ex03.py
812
4.53125
5
print "I will now count my chickens:" # These print out the answer after a string. # The numbers are turned into floating point numbers with a decimal point and zero at the end for accuracy. print "Hens", 25.0 + 30.0 / 6.0 print "Roosters", 100.0 - 25 * 3 % 4 print "Now I will count the eggs" # This prints out the answer. It follows PEMDAS. print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 print "Is it true that 3 + 2 < 5 - 7?" # #This prints out either True or False. print 3.0 + 2.0 < 5.0 - 7.0 # Without the comma after the string, you will get a TypeError. print "What is 3 + 2?", 3 + 2 print "What 5 - 7?", 5-7 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
true
387d986223c06ade6346901334c275f70ae5b89f
xcobaltfury3000/baby-name-generator
/Baby_name_generator.py
2,466
4.40625
4
print ("Hello world") import string print(string.ascii_letters) print(string.ascii_lowercase) #since we want a random selection we import random import random #from random library we want to utilize choice method print(random.choice("pullaletterfromhere")) print(random.choice(string.ascii_lowercase)) letter_input_1 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter') letter_input_2 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter') letter_input_3 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter') letter_input_4 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter') letter_input_5 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter') vowels = 'aeiouy' consonant = 'bcdfghjklmnpqrstvwxz' letter = string.ascii_lowercase # copy conditional loop for the rest of the letter inputs def generator(): if letter_input_1 == "v": letter1 = random.choice(vowels) elif letter_input_1 == "c": letter1 = random.choice(consonant) elif letter_input_1 == "l": letter1 = random.choice(letter) else: letter1 = letter_input_1 # allows user to put a specific letter if letter_input_2 == "v": letter2 = random.choice(vowels) elif letter_input_2 == "c": letter2 = random.choice(consonant) elif letter_input_2 == "l": letter2 = random.choice(letter) else: letter2 = letter_input_2 if letter_input_3 == "v": letter3 = random.choice(vowels) elif letter_input_3 == "c": letter3 = random.choice(consonant) elif letter_input_3 == "l": letter3 = random.choice(letter) else: letter3 = letter_input_3 if letter_input_4 == "v": letter4 = random.choice(vowels) elif letter_input_4 == "c": letter4 = random.choice(consonant) elif letter_input_4 == "l": letter4 = random.choice(letter) else: letter4 = letter_input_4 if letter_input_5 == "v": letter5 = random.choice(vowels) elif letter_input_5 == "c": letter5 = random.choice(consonant) elif letter_input_5 == "l": letter5 = random.choice(letter) else: letter5 = letter_input_5 name =letter1 + letter2+letter3+letter4+letter5 return(name) for i in range (20): # to generate 20 different names print(generator())
true
d5507e8d1e4565bf343205fcf933096abeead382
AtharvaDahale/Python-BMI-Calculator
/Python BMI Calculator.py
529
4.34375
4
height = float(input("Enter your height in centimeters: ")) weight = float(input("Enter your weight in Kg: ")) height = height/100 BMI = weight/(height*height) print("Your BMI is: ",BMI) if (BMI > 0): if(BMI<=16): print("Your are severely underweight") elif(BMI<=18.5): print("you are underweight") elif(BMI<=25): print("You are healthy") elif(BMI<=30): print("You are overweight") else: print("You are severely overweight") else:("enter valid details")
true
82f5c6de2568a82c08a8e6f17427b6478277309b
khanmaster/eng88_python_control_flow
/control_flow.py
1,721
4.3125
4
# Control Flow with if, elif and else - loops weather = "sunny" if weather == "thinking": # if this condition is False execute the next line of code print("Enjoy the weather ") # if true this line will get executed if weather != "sunny": print(" waiting for the sunshine") if weather == "cloudy": print(" still waiting for sunshine") else: print("Opps sorry something went wrong .. please try later") # If false this line will get executed # add a condition to use elif when the condition is False #Loops are used to ITERATE through data #Lists, Dict, sets list_data = [1, 2, 3, 4, 5] print(list_data) #First iteration for list in list_data: if list == 3: print("I found 3") if list == 2: print(" now I found 2") if list == 5: print(" this is the last number and I found it as well - 5") else: print("Better Luck next time") # Second Iteration student_1 = { "name": "Shahrukh", "key": " value ", "stream": "Cyber Security ", # string "completed_lessons": 3, # int "complete_lessons_names": ["variables", "operators", "data_collections"] # list } for data in student_1.values(): if data == " value ": break print(data) # # # # # # user_prompt = True # # while user_prompt: # age = input("What is your age? ") # if age.isdigit(): # user_prompt = False # else: # print("Please provide your answer in digits") # # print(f"Your age is {age}") # While loops user_prompt = True while user_prompt: age = input("Please enter your age? ") if age.isdigit(): user_prompt = False else: print("Please provide your answer in digits") print(f"Your age is {age}")
true
404d754f6ee9882e6eac12318f3847c3c46d2a9f
s-anusha/automatetheboringstuff
/Chapter 8/madLibs.py
1,814
4.78125
5
#! python3 # madLibs.py ''' Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this: The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events. The program would find these occurrences and prompt the user to replace them. Enter an adjective: silly Enter a noun: chandelier Enter a verb: screamed Enter a noun: pickup truck The following text file would then be created: The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events. The results should be printed to the screen and saved to a new text file. ''' # Usage: python madLibs.py input_file [output_file] import sys, re if len(sys.argv) < 2: print('Usage: python madLibs.py input_file [output_file]') infile = open(sys.argv[1], 'r') if len(sys.argv) > 2: outfile = open(sys.argv[2], 'w') else: outfile = open('output.txt', 'w') wordRegex = re.compile(r'\w+') for line in infile: for word in line.split(): source = wordRegex.search(word) if source.group() == 'ADJECTIVE': print('Enter an adjective:') newWord = raw_input() line = line.replace(word, newWord) elif source.group() == 'NOUN': print('Enter a noun:') newWord = raw_input() line = line.replace(word, newWord) elif source.group() == 'ADVERB': print('Enter an adverb:') newWord = raw_input() line = line.replace(word, newWord) elif source.group() == 'VERB': print('Enter an verb:') newWord = raw_input() line = line.replace(source.group(), newWord) outfile.write(line) infile.close() outfile.close() print('Output:') outfile = open('output.txt', 'r') print outfile.read() outfile.close()
true
85d73fc37042cddd112601a2f4a8f013bf569685
s-anusha/automatetheboringstuff
/Chapter 13/brute-forcePdfPasswordBreaker.py
1,721
4.5
4
#! python3 # brute-forcePdfPasswordBreaker ''' Say you have an encrypted PDF that you have forgotten the password to, but you remember it was a single English word. Trying to guess your forgotten password is quite a boring task. Instead you can write a program that will decrypt the PDF by trying every possible English word until it finds one that works. This is called a brute-force password attack. Download the text file dictionary.txt from http://nostarch.com/automatestuff/. This dictionary file contains over 44,000 English words with one word per line. Using the file-reading skills you learned in Chapter 8, create a list of word strings by reading this file. Then loop over each word in this list, passing it to the decrypt() method. If this method returns the integer 0, the password was wrong and your program should continue to the next password. If decrypt() returns 1, then your program should break out of the loop and print the hacked password. You should try both the uppercase and lower-case form of each word. (On my laptop, going through all 88,000 uppercase and lowercase words from the dictionary file takes a couple of minutes. This is why you shouldn’t use a simple English word for your passwords.) ''' # Usage: python brute-forcePdfPasswordBreaker.py file import sys import PyPDF2 if len(sys.argv) < 3: print('Usage: python brute-forcePdfPasswordBreaker.py pdf_file dictionary') sys.exit() pdf = sys.argv[1] pdfReader = PyPDF2.PdfFileReader(open(pdf, 'rb')) dictionary = sys.argv[2] file = open(dictionary, 'r') lines = file.readlines() for line in lines: password = line.strip() if pdfReader.decrypt(password) is 1: print('Password: ' + password) break
true
e242498ad2180dd426cb2aa1b4cdbe86586e96d6
s-anusha/automatetheboringstuff
/Chapter 6/tablePrinter.py
1,784
4.71875
5
#! python3 # tablePrinter.py ''' Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this: tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] Your printTable() function would print the following: apples Alice dogs oranges Bob cats cherries Carol moose banana David goose Hint: Your code will first have to find the longest string in each of the inner lists so that the whole column can be wide enough to fit all the strings. You can store the maximum width of each column as a list of integers. The printTable() function can begin with colWidths = [0] * len(tableData), which will create a list containing the same number of 0 values as the number of inner lists in tableData. That way, colWidths[0] can store the width of the longest string in tableData[0], colWidths[1] can store the width of the longest string in tableData[1], and so on. You can then find the largest value in the colWidths list to find out what integer width to pass to the rjust() string method. ''' # Usage: python tablePrinter.py def printTable(data): colWidths = [0] * len(data) for i in range(len(data)): colWidths[i] = len(max(data[i], key=len)) amount = int(max(colWidths)) for i in range(len(data[0])): for j in range(len(data)): print(data[j][i].rjust(amount), end="") print('\n') tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] printTable(tableData)
true
e7c9434a33f704bdb6ff27104e5fd176536a338a
medifle/python_6.00.1x
/defTowerofHanoi.py
617
4.25
4
# recursive version of Towers of Hanoi # fr means 'from' # printMove print every step in order to complete the problem. def printMove(fr, to): print('Move from ' + str(fr) + ' to ' + str(to)) # 'fr', 'to', 'spare' are the three towers # 'fr' is the name of the tower you move stacks from # 'to' is the name of the tower you want to move stacks to # 'spare' is the third tower # 'n' is the number of stacks def Towers(n ,fr, to, spare): if n == 1: printMove(fr, to) else: Towers(n - 1, fr, spare, to) Towers(1, fr, to, spare) Towers(n - 1, spare, to, fr)
false
74f13e5d321d9c5195436d0a7bb8aa2011842144
Aplex2723/Introduccion-en-Python
/Scripts/Salidas.py
1,414
4.1875
4
v = "otro texto" n = 10 print("Un texto",v,"y un numero",n) c = "Un texto {} y un numro {}".format(v,n) # Lo mismo de arriba print(c) c = "Un texto {} y un numero {}".format(v,n) # Pasadno numeros print("Un texto {1} y un numero {0}".format(v,n))# Cambiando los valores donde 1 = n y 0 = v print("\tUn texto {texto} y un numero {numero}".format(texto=v,numero=n)) print("{texto}, {texto}, {texto}".format(texto=v)) print("{:>30}".format("Palabra"))# Alineamiento a la derecha en 30 caracteres print("{:30}".format("Palabra"))# Alineamiento a la izquierda en 30 caracteres print("{:^30}".format("Palabra"))# Alineamiento al centro en 30 caracteres print("{:.3}".format("Palabra"))# Truncamiento a 3 caracteres print("{:>30.3}".format("Palabra"))# Alineamiento a la derecha en 30 caracteres con truncamiento de 3 # Formateo de numero enteros, rellenados con espacios print(" ") print("{:4d}".format(10)) print("{:4d}".format(100)) print("{:4d}".format(1000)) # Formateo de numero enteros, rellenados con ceros print(" ") print("{:04d}".format(10)) print("{:04d}".format(100)) print("{:04d}".format(1000)) # Formateo de numeros flotanbtes, rellenados con espacios print(" ") print("{:7.3f}".format(3.1415983)) print("{:7.3f}".format(123.23)) # Formateo de numeros flotanbtes, rellenados con ceros print(" ") print("{:07.3f}".format(3.1415983)) print("{:07.3f}".format(123.23))
false
8bae9a502d852cc6497e804361ba331e80c0b82c
rafiulalam2112/Age-ganaretor
/age_generator.py
530
4.34375
4
print('Hello! I am Rafi Robin. This is my python project.') print('This tool genarate your age :)') now_year=2021 birth_year=int(input('Inter your birth year :')) #When a user input a number the value save as string. To make the input as number use int() . age=(now_year-birth_year) print(f'You are {age} years old :)') if age<13: print('You are a kid :)') if 13<age<16: print('You are a teen') if age==16: print('You and I are the same age') if 16<age<18: print('You are a teen') if age>18: print('You are an adult')
true
5327adf41dc51315c97e8b473b5709acc6efa7c0
elacuesta/euler
/solutions/0004.py
620
4.28125
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def is_palindrome(n): return list(str(n)) == list(reversed(str(n))) def palindrome(factor_length=2): a = 10**factor_length - 1 b = 10**factor_length - 1 while True: p = a * b if is_palindrome(p): return p, a, b a -= 1 p = a * b if is_palindrome(p): return p, a, b if __name__ == '__main__': print(palindrome(3))
true
df764bedcfad60f653ecf19dee51a799f5021603
UthejReddy/Python
/Python_Basics_Codes/datetime_fun.py
818
4.125
4
import datetime from datetime import time from datetime import datetime #example 1 date_object1 = datetime.datetime.now() print(date_object1) #example 2 date_object2 = datetime.date.today() print(date_object2) #example 3 date_object3 = datetime.date(2019,4,10) print(date_object3) #example 4 timestamp=datetime.date.fromtimestamp(5465645414) print("date=" ,timestamp) #example 5 today=datetime.date.today() print("current year:",today.year) print("current month:",today.month) print("current day:",today.day) #example 6 a = time() print("a=",a) b = time(10,22,45) print("b=",b) #Example 7 t1=datetime.date(year=2020,month=6,day=7) t2=datetime.date(year=2017,month=4,day=16) t3=t1-t2 print("t3=",t3) #Exapmle 8 now = datetime.now() datetime.strftime(now,'%y')
false
25a63aa2f53b0ffbde33f7bfc98300670294c5c1
DanteAkito/python_curse
/exercises.py
1,559
4.71875
5
#Exercise 1: Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario lo introduzca muestre por pantalla la cadena ¡Hola <nombre>!, donde <nombre> es el nombre que el usuario haya introducido. '''name = input("What's your name?: ") print("Hi! " + name)''' #Exercise 2: Escribir un programa que pregunte el nombre del usuario en la consola y un número entero e imprima por pantalla en líneas distintas el nombre del usuario tantas veces como el número introducido. '''name = input("What's your name?: ") number = input("type a integer number please: ") number_int = int(number) print (name * number_int)''' #Exercise 3: Escribir un programa que pregunte el nombre del usuario en la consola y un número entero e imprima por pantalla en líneas distintas el nombre del usuario tantas veces como el número introducido. '''name = input("What's your name?: ") number = input("type a integer number please: ") number_int = int(number) print ((name + "\n") * number_int)''' #Execise 4: Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario lo introduzca muestre por pantalla <NOMBRE> tiene <n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y <n> es el número de letras que tienen el nombre. name = input("What's your name?: ") n1 = len(name) print (name.upper() + " has " + str(n1) + " letters. ") """ colors = [11, 34.1, 98.2, 43, 45.1, 54, 54] for color in colors: if isinstance(color, int) and color > 50: print(color)
false
f89825f484213cd71df1523936d71db182f4ae6b
DanteAkito/python_curse
/matrices_suma.py
1,520
4.21875
4
# Crear programa para introducir datos en la matriz x = int(input("Digita el numero de filas: ")) # se introduce el numero de filas z = int(input("Digita el numero de columnas: ")) # se introduce el numero de columnas a = int(input("Digita el numero de filas de la matriz 2: ")) b = int(input("Digita el numero de columnas de la matriz 2: ")) matriz_cero = [] # se crea una matiz vacia for i in range(x): # para una variable i en la variable x, osea las filas, agregar una lista matriz_cero.append([]) # indica que debe agregar una lista vacia for j in range(z): # para una variable j en las columnas v = int(input("Introduce los datos para " + "fila {}, columna {} :".format (i+1, j+1))) # pide los datos que contiene la matriz formateando para que cada vez pida el dato siguiente matriz_cero[i].append(v) # agregar el dato a la lista for fila in matriz_cero: print(fila) matriz_uno = [] # se crea una matiz vacia for r in range(a): # para una variable i en la variable x, osea las filas, agregar una lista matriz_uno.append([]) # indica que debe agregar una lista vacia for t in range(b): # para una variable j en las columnas c = int(input("Introduce los datos para " + "fila {}, columna {} :".format (r+1, t+1))) # pide los datos que contiene la matriz formateando para que cada vez pida el dato siguiente matriz_uno[r].append(c) # agregar el dato a la lista for fila2 in matriz_uno: print(fila2) suma = matriz_uno + matriz_cero print(suma)
false
1dca28f5e0ca90cba859c06beb9df4ca387a9557
DanteAkito/python_curse
/primarios.py
241
4.15625
4
x = int(input("Enter a number: ")) #if x % 2 == 0 : #print("The number is pair") #if x % 2 != 0 : #print("The number is odd") if x < 1 if x % 1 != 0 and x % x != 0 #if range(2, x) % == 0 and x != 1 : print("numero primo")
false
0f804f75088a1504d0365012cd9ab5e2ec4b16b3
jsonw99/Learning-Py-Beginner
/Lec04(ListAndTuple).py
1,482
4.40625
4
# list ################################################################ classmates = ['Micheal', 'Bob', 'Tracy'] print(classmates) type(classmates) len(classmates) print(classmates[0]) print(classmates[1]) print(classmates[2]) print(classmates[3]) print(classmates[-1]) print(classmates[-2]) print(classmates[-3]) print(classmates[-4]) # add entry at the end classmates.append('Adam') print(classmates) # add entry at specific position classmates.insert(1, 'Jack') print(classmates) # delete the last entry classmates.pop() print(classmates) # delete the entry at the specific position classmates.pop(1) print(classmates) # change the entry at the specific position classmates[1] = 'Sarah' print(classmates) # the entries of a list can be different types L = ['Apple', 123, True] print(L) # the entry of a list can be another list s = ['python', 'java', ['asp', 'php'], 'scheme'] len(s) print(s) print(s[2]) p = ['asp', 'php'] s = ['python', 'java', p, 'scheme'] print(p[1]) print(s[2][1]) # the empty list L = [] len(L) print(L) # tuple ################################################################ # once defined, then cannot be changed # define the empty tuple t = () print(t) # define the empty tuple with one element t = (1,) print(t) # define the tuple with one element 1 t = (1) print(t) # define the tuple with two element 1 and 2 t = (1, 2) print(t) # define a 'changeable' tuple t = ('a', 'b', ['A', 'B']) print(t) t[2][0] = 'X' t[2][1] = 'Y' print(t)
true
3f693e3ac2a3ca646480defe121ca735abcf664e
jai-somai-lulla/Sem8
/Legacy/ML/LinearRegression/grad.py
1,201
4.1875
4
import numpy as np import pandas as pd #import matplotlib.pyplot as plt def cost_function(X, Y, B): if(type(Y) == np.int64): m=1 else: m = len(Y) J = np.sum((X.dot(B) - Y) ** 2)/(m*2) return J def gradient_descent(X, Y, B, alpha, iterations): cost_history = [0] * iterations m = len(Y) for iteration in range(iterations): # Hypothesis Values for entire set data h = X.dot(B) # Difference b/w Hypothesis and Actual Y loss = h - Y # Gradient Calculation gradient = X.T.dot(loss) / m # Changing Values of B using Gradient B = B - alpha * gradient # New Cost Value cost = cost_function(X, Y, B) cost_history[iteration] = cost return B, cost_history def main(): print("Linear Regrssion") x=np.array([1,2,3,3,4,4,5,6,8,12]) x0 = np.ones(len(x)) X = np.array([x0, x]).T Y=np.array([2,4,4,5,8,8,12,12,16,24]) B = np.array([0, 0]) print cost_function(X[0],Y[0],B) inital_cost = cost_function(X, Y, B) print("Initial Cost: "+str(inital_cost)) B,ch = gradient_descent(X, Y, B, 0.01, 10) print "Weights :"+str(B) print "Cost_History :"+str(ch) if __name__ == "__main__": main()
true
8d0778ee4429cf201fca2e368e9d8c07a1c0f25e
THE-SPARTANS10/Python-Very-Basics
/user_input.py
211
4.1875
4
#By default in python for user input we get everything as string name = input("Enter your name: ") value = input("Enter a number: ") print("your name is " + name + " and your favourite number is: " + value)
true
704954326faf5ad2e678d32dd237bf842130b52e
Gustavo1518/Python_InterfacesGraficas
/For.py
655
4.15625
4
#Metodo upper() convierte a mayusculas micadena = raw_input("ingresa un texto") for cadena in micadena: print(cadena.upper()) # metodo lower() convierte a minusculas micadena2 = raw_input("ingresa un segundo texto") for i in micadena2: print(i.lower()) #iteracion sobre un rango saludo = "HOLA MUNDO" for numero in range(len(saludo)): print(numero+1, saludo[numero]) #iteracion sobre una lista hola="hola mundo" milista = list(hola) for elemento in milista[:]: milista.append(elemento*2) print(milista) mitupla = {"hola", 1, True} for elemento in mitupla: print(elemento, "es", type(elemento)) print("*********fin del ejemplo*************")
false