blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a1963284e10bb55ee4abb2b457f31632a6b2e8a2 | ElizaLab/CFG-2020-9-Python | /108_functions.py | 892 | 4.3125 | 4 | # Functions
# should have 1 job! and do it well
# if a variable is box, then a function is like a machine!
# 1) it take in inputs AKA: arguments
# 2) , does something AKA: block of code
# 3) output the results - with return!
# it helps you not have to repeat yourself
#syntax
#def <name_funtion>(arg1, arg2):
# block of code
# block of code come after a : and are indented
# return result
# arguments exist withing the scope of the function
#1)Define a function that constructs a full name with two arguments
def full_name(first_n, last_n):
complete_name = first_n + " " +last_n
print(complete_name)
# 2) call the function with data for the argument
full_name('Li', "Stark") #calling function with two strings
student_f_name = input("what is your first name")
student_l_name = input("what is your last name")
full_name(student_f_name, student_l_name)
| true |
2157634e94a7a1311da89f3c13c16b91fff9966c | MarioViamonte/Curso_Python | /aula28/aula28.py | 1,580 | 4.65625 | 5 | '''
Funções - def em python
'''
# exemplo
def funcao():
print('Hello world!')
funcao()
funcao()
funcao()
funcao()
# exemplo aplicável prático / diferença entre as funções
def funcao2():
print('olá mundo')
funcao2()
funcao2()
funcao2()
funcao2()
print('Hello world!')
print('Hello world!')
print('Hello world!')
print('Hello world!')
# criar parametro dentro da função
def funcao3(msg):
print('Olá mundo!')
funcao3('mensagem') # criando o valor do parametro
funcao3('mensagem')
funcao3('mensagem')
funcao3(' ')
# mudando o parâmetro
def saudacao(msg2, nome):
print(msg2, nome)
saudacao('olá', 'Jéssica')
saudacao('hello', 'visitante')
# sem mandar valores
def saudacao2(msg3='olá', nome2='usuário'):
print(msg3, nome2)
saudacao2()
# trocando os nomes das variáveis
def saudacao3(msg4='Olá', nome3='Usuário'): # segue a ordem da função criada
print(msg4, nome3)
saudacao3(nome3='zezinho', msg4='hi')
# mudando a letra das variáveis
def saudacao4(msg5='Olá', nome4='Usuário'):
nome4 = nome4.replace('a', '4') # quando encontrar a letra 'a' vai mudar para '4'
msg5 = msg5.replace('a', '4')
print(msg5, nome4)
saudacao4('hi', 'Jéssica')
saudacao4('hello', 'Mário')
saudacao4('olá', 'Lucas')
saudacao4('oi', 'usuário')
# as formas anteriores não são usuais
# forma abaixo de como fazer o msm processo anterior
def saudacao5(msg6='Olá', nome5='Usuário'):
nome5 = nome5.replace('a', '4')
msg6 = msg6.replace('a', '4')
return f' {msg6} {nome5}'
variavel = saudacao5()
print(variavel)
| false |
f8dc78b5b66d79bc5a8c787dcc17f67aadfef84d | MarioViamonte/Curso_Python | /aula22/aula22.2.py | 1,260 | 4.4375 | 4 | '''
listas em python
fatiamento
append, insert, pop, del, clear, extend, +
min, max
range
'''
# juntar listas
l1 = [1,2,3]
l2 = [4,5,6]
l3 = l1 + l2
print(l1)
print(l2)
print(l3)
# juntar listas com 'extend'
l1 = [1,2,3]
l2 = [4,5,6]
l1.extend(l2)
l2.extend('A')
print(l1)
print(l2)
# adicionando valores com 'append'
l1 = [1,2,3]
l2 = [4,5,6]
l1.append('A')
l2.append('B')
print(l1)
print(l2)
# inserir valor em qualquer parte da lista usando 'insert'
l1 = [1,2,3]
l2 = [4,5,6]
l2.insert(0,'B')
print(l2[0])
#deletar elemento do final da lista com 'pop'
l1 = [1,2,3]
l2 = [4,5,6]
l2.pop()
l1.pop()
print(l1)
print(l2)
# excluir elementos de maneira rapida usando 'del'
l1 = [1,2,3,4,5,6,7,8,9]
del(l1[3:5])
print(l1)
# mostrar o maior e o menor valor da lista
l2 = [1,2,3,4,5,6,7,8,9]
print(max(l2))
print(min(l2))
# simplificar a forma de escrever listas usando range
l2 = list(range(1,10)) # porém essa função retorna um objeto range, por isso é usado a função list pra transformar o objeto em uma lista
print(l2)
l3 = list(range(0,100,8)) # de 0 a 100, pulando de 8 em 8 (multiplos de 8)
print(l3)
# usando 'for' em lista
l2 = list(range(1,10))
for elem in l2:
print(f'o tipo de elem é {type(elem)} e seu valor é {elem}')
| false |
d396c1dacf950a29b6513e953a2fdc10be90a873 | MarioViamonte/Curso_Python | /exercicio/exercicio3.py | 437 | 4.1875 | 4 | """
faça um programa que peça o primeiro nome do usuário. Se o nome tiver 4 letras ou
menos escreva "Seu nome é curto"; se tiver entre 5 e 6 letras, escreva
"Seu nome é normal"; maior que 6 escreva "Seu nome é muito grande".
"""
nome = input('Qual seu nome?: ')
tamanho = len(nome)
if tamanho <= 4:
print('seu nome é curto.')
elif tamanho <= 6:
print('seu nome é normal.')
else:
print('seu nome é muito grande.')
| false |
25cd85cad87b8236ec8911433c91c401bbafccd0 | MarioViamonte/Curso_Python | /calculadora2/calculadora2.py | 1,328 | 4.28125 | 4 |
def bem_vindo():
print('''
bem vindo à calculadora
''')
def calculo():
operacao = input('''
digite:
+ para adição
- para subtração
* para multiplicação
/ para divisão
''')
numero_1 = int(input('digite o primeiro numero: '))
numero_2 = int(input('digite o segundo numero: '))
if operacao == '+':
print('{} + {} = '. format(numero_1, numero_2))
print(numero_1 + numero_2)
elif operacao == '-':
print('{} + {} = '. format(numero_1, numero_2))
print(numero_1 - numero_2)
elif operacao == '*':
print('{} * {} = '. format(numero_1, numero_2))
print(numero_1 * numero_2)
elif operacao == '/':
def divisao(numero_1, numero_2):
if numero_2 > 0:
return numero_1 / numero_2
divide = divisao(numero_1,numero_2)
if divide:
print(divide)
else:
print('erro')
else:
print('tente novamente.')
novamente()
def novamente():
calc_novamente = input('''
Deseja fazer o calculo novamente?
Por favor digite S para sim ou N para não''')
if calc_novamente.upper() == 'S':
calculo()
elif calc_novamente.upper() == 'N':
print('Até logo.')
else:
novamente()
bem_vindo()
calculo()
| false |
371d93916c775c67c56ef5da31e77b83244e42c6 | JoshFlack/Tees | /Week_1/wk1 pt2 q4 biggest number.py | 782 | 4.1875 | 4 | #Josh Flack
#24/8/2020
#sorting
first_num = (int (input ("Please enter the first number"))) #ask for first number and cast
second_num = (int (input ("Please enter the second number"))) #ask for second number and cast
third_num = (int (input ("Please enter the third number"))) #ask for third number and cast
if first_num > second_num and first_num > third_num: #if first number is greater than second and third then print first number
print (first_num)
if second_num > first_num and second_num > third_num: #if second number is greater than first and third number then print second number
print (second_num)
elif third_num > first_num and third_num > second_num: #else if third number is greater than first and second print third number
print (third_num)
| true |
d95d169e21653c1f8acdf89369f715fd4c2f2a3e | sushantsp/Introduction-to-Computer-Science-using-Python-MITedx- | /Classes.py | 1,383 | 4.34375 | 4 | import turtle
class Polygon:
"""docstring for Polygon."""
def __init__(self, sides, name, size = 100, color = "black", line_thickness = 2):
self.sides = sides
self.name = name
self.size = size
self.color = color
self.line_thickness = line_thickness
self.interior_angle = (self.sides - 2)*180
self.angle = self.interior_angle / self.sides
def draw(self):
turtle.color(self.color)
turtle.pensize(self.line_thickness)
for i in range(self.sides):
turtle.forward(100)
turtle.right(180 - self.angle)
turtle.hideturtle()
turtle.done()
# Concept of Subclassing.
class Square(Polygon):
"""docstring for Square."""
def __init__(self, size=100, color='black', line_thickness = 2):
# super uses the initilise method of the parent class.
super().__init__(4, "square", size, color, line_thickness)
squ = Square(color = "#213acb", line_thickness = 5)
# Square = Polygon(4,'Square')
# Pentagon = Polygon(5,'Pentagon')
#
# print(Square.sides, Square.name, Square.interior_angle, Square.angle)
#
# print(Pentagon.sides, Pentagon.name, Pentagon.interior_angle, Pentagon.angle)
# Square.draw()
# Pentagon.draw()
# Hexagon = Polygon(6, 'Hexagaon', 100,"red")
# Hexagon.draw()
squ.draw()
| true |
0888a946db7cf484e2ba918b15be591e1616f6af | CaiqueAmancio/ExercPython | /exerc_5.py | 254 | 4.125 | 4 | """
Faça um programa que receba um número inteiro e verifique se este número
é par ou impar.
"""
num = int(input(f'Insira um número inteiro: '))
resto = num % 2
if resto == 0:
print(f'O número é par!')
else:
print(f'O número é impar!')
| false |
4b0e779f58ce4c5d1ae22faaabdc7a82d113dccf | tulcas/master-python | /08-funciones/tabla_funcion_ejemplo_03.py | 802 | 4.1875 | 4 | print("############# EJEMPLO 3 ############# ")
def tabla(numero): #Se decllara la funcion
print(f"Tabla de muiltiplicar del numero : {numero}" )# se ingresa numero por consola
for contador in range(1, 11): # el contador comienza a recorrer el rango de a uno
operacion = numero * contador # contador +1 en cada pasada
# imprime el numero ingresado por el valor de contador en cada pasada y muestra el resultado de operacion
print(f"{numero} x {contador} = {operacion} " )
print("\n")
tabla_input = int(input("Ingrese el numero de la tabla a calcular: ")) # Se ingresa por teclado numero
tabla(tabla_input) # Llamada a funcion tabla y se pasa variable ingresada por parametro.
tabla(8)
tabla(7)
tabla(10)
# Ejemplo 3.1
for i in range(1, 11):
tabla(i)
| false |
6a984757adf8d41d4f1384cfc9b87fd3660e46a3 | tulcas/master-python | /07-ejercicios/ejercicio_07.py | 754 | 4.125 | 4 | """
Ejercicio 07
Hacer un programa que muestre todos los numeros impares entre
dos numeros que decida el usuario.
"""
print( "INGRESE DOS VALORES PARA MOSTRAR TODOS LOS NUMEROS IMPARES ENTRE ELLOS" )
num1 = int(input("Ingresa un valor: "))
num2 = int(input("Ingresa otro valor: "))
if num1 < num2:
for i in range(num1, num2 + 1): # i recorre el rango tomando el valor diferente en cada pasada
if i%2 == 0: # En cada pasada i se divide por dos y verifica si es igual a 0
print(f"{i} -> es PAR ") # Si el resultado es 0 lo imprime
else:
print(f"{i} -> es IMPAR ") # Si el resultado es diferente de 0 lo imprime
else:
print("El primer numnero debe ser MAYOR a el segundo...find el programa")
| false |
e779f3fdf7a0169dc00447cdc7294a2f4d7ec06e | f0lie/basic_python_workshop | /part_var_1.py | 480 | 4.1875 | 4 | # We have a line and we have a single point on it
# We can represent the point's position on the line with a variable
pos = 0
# The same with velocity
velo = 1
# We write the values into the terminal
print(pos, velo)
# If we want to represent speed, we add velo and pos together
pos += velo
print(pos)
# However, that would only increase the speed once
# If we wanted to increase the speed again, we add them together again
pos += velo
print(pos)
# But this is annoying to do | true |
b56cbdcc1859aba37cc9f37e0abecb2959eadfde | makijurowski/dojo-week3 | /Python/multiples_sum_average.py | 965 | 4.3125 | 4 | """This is a Coding Dojo homework assignment."""
def multiples():
"""This function has two parts that consist of other functions."""
def odds_to_1000():
"""Prints all odd numbers up through 1000."""
for i in range(1, 1001, 2):
print i
def multiples_of_5():
"""Prints all multiples of 5 from 5 to 1,000,000."""
for i in range(5, 1000001, 5):
print i
return odds_to_1000(), multiples_of_5()
def sum_list(my_list):
"Adds all the numbers in a list, returns a number."""
total = 0
for num in my_list:
total = total + num
return total
def average_list(my_list):
"Finds the average value of numbers in a list, returns a number."""
total = 0
for num in my_list:
total = total + num
average = total / len(my_list)
return average
# Test cases
# print multiples()
print sum_list([1, 2, 5, 10, 255, 3])
print average_list([1, 2, 5, 10, 255, 3])
| true |
2232dc8f6fd70ed3de49c112394cc5239559eb4e | TouTou-python/data_structure | /1012(队列)/队列.py | 2,118 | 4.125 | 4 | class Queue:
def __init__(self):
self.entries = []
self.size = 0
def __repr__(self):
return "<" + str(self.entries)[1:-1] + ">"
def enqueue(self, data):
self.entries.append(data)
self.size += 1
def dequeue(self):
temp = self.entries[0]
self.entries = self.entries[1:]
self.size -= 1
return temp
def size(self):
return self.size
def get(self, index):
return self.entries[index]
def reverse(self):
self.entries = self.entries[::-1]
if __name__ == '__main__':
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
print(f"队列: {queue}")
print(f"删除的队列元素: {queue.dequeue()}")
print(f"删除后的队列: {queue}")
print(f"队列的大小: {queue.size}")
index = 1
print(f"查找的队列元素位置: {index}\n查找的队列元素为: {queue.get(index)}")
queue.reverse()
print(f"倒序后的队列: {queue}")
class Node:
def __init__(self, data: any, next=None):
self.data = data
self.next = next
def __repr__(self):
return f'Node({self.data})'
class LinkQueue:
def __init__(self):
self.front = None
self.tail = None
self.size = 0
def enqueue(self, item):
node = Node(item)
if self.size == 0:
self.front = node
self.tail = node
else:
self.tail.next = node
self.tail = node
self.size += 1
def dequeue(self):
if self.size == 0:
raise IndexError
else:
temp = self.front
self.front = temp.next
temp.next = None
self.size -= 1
def is_empty(self):
return self.front is None
def __repr__(self):
temp = self.front
str_repr = ""
while temp:
str_repr += f"{temp}-->"
temp = temp.next
return str_repr + "END"
q = LinkQueue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
print(q)
| false |
99708535d917beea82bb507387f3ea2e49db2ae1 | arazi47/university-projects | /1st year/1st semester/FPLab/Assignment.01/A1.py | 529 | 4.3125 | 4 | """
Generate the first prime number larger than a given natural number n
"""
from math import sqrt
def prime(n):
if n < 2:
return False
if n % 2 == 0 and n != 2:
return False
for d in range (3, int(sqrt(n) + 1), 2):
if n % d == 0:
return False
return True
def generate(n):
n = n + 1 # the number we're looking for is larger than the given one
if n % 2 == 0 and n != 2: # and n != 2 => don't skip number 2
n = n + 1
while not prime(n):
n = n + 2
return n
n = int(input("Input: "))
print (generate(n))
| false |
2bd8ee3ae8f1ad6c8b1d9ea61ce24756d87db5ed | newzpanuwat/data_structure | /data_structure/playground.py | 2,155 | 4.34375 | 4 | # Merge sort
# Divide and Conquer
# Divide: divide array by // 2
# Conquert: Sort them
# Combine: Merge them
# Split method for divide array which unsorted
# Merge method if you split small value then merge them together
list = [6,6,2,9,0,1,55,32]
def merge_sort(list):
if len(list) <= 1:
return list
left_half, right_half = split(list)
left = merge_sort(left_half)
right = merge_sort(right_half)
return merge(left, right)
def split(list):
mid = len(list) // 2
left = list[:mid]
right = list[mid:]
return left, right
def merge(left, right):
l = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
l.append(left[i])
i += 1
else:
l.append(right[j])
j += 1
while i < len(left):
l.append(left[i])
i += 1
while j < len(right):
l.append(right[j])
j += 1
return l
sorted = merge_sort(list)
print("List: ", sorted)
# Liner search
def linear_search(lst, target):
for i in range(0, len(lst)):
if lst[i] == target:
return i
return -1
result = linear_search(sorted, 32)
print("Linear search: ", result)
def recursive_binary_search(list, target):
if len(list) == 0:
return False
else:
midpoint = len(list) // 2
if list[midpoint] == target:
return True
else:
if list[midpoint] < target:
return recursive_binary_search(list[midpoint+1:], target)
else:
return recursive_binary_search(list[:midpoint], target)
result2 = recursive_binary_search(sorted, 32)
print("Recursive Binary Search: ", result2)
def binary_search(list, target):
first = 0
last = len(list) - 1
while first <= last:
midpoint = (first - last) // 2
if list[midpoint] == target:
return midpoint
elif list[midpoint] < target:
first = midpoint + 1
else:
last = midpoint - 1
return None
result3 = binary_search(sorted, 10)
print("Normal Binary Search:", result3) | false |
f18835045bc60c4aca65c37323f587b934fa1348 | jessicaice/LPTHW | /ex16.py | 1,357 | 4.6875 | 5 | #Exercise 16 from Learn Python the Hard Way
#Created by Jessica Ice
#Created on May 10, 2016
#Last Edited on May 10, 2016
#Here are some extra commands and what they do:
# close - closes the file (like file save)
# read - reads the contents of the file
# readline - reads just one line of a text file
# truncate - empties the file (careful!)
# write('stuff') - writes 'stuff' into the file
#Importing argv functions
from sys import argv
script, filename = argv
#Printing instructions for executing the script
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
#Printing how we would execute the truncation of the file
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to write these to the file."
line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")
all_lines = "%s\n%s\n%s\n" % (line1, line2, line3)
#print all_lines
print "I'm going to write these to the file."
target.write(all_lines)
#target.write("\n")
#target.write(line2)
#target.write("\n")
#target.write(line3)
#target.write("\n")
print "And finally, we close it."
target.close()
# when you open a file in a mode you can append
#things onto it - useful for the webscraping | true |
2a61215c6c36326b560e7b02f081f67ea5174518 | jessicaice/LPTHW | /ex29.py | 1,353 | 4.25 | 4 | #Exercise 29: What if
#From Learn Python the Hard Way
#Created by Jessica Ice
#Created on May 25, 2016
#Creating some variables for the if statements
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The word is saved!"
if people < dogs:
print "The word is drooled on!"
if people > dogs:
print "The world is dry!"
#This is so that you will have equal number of dogs and humans
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
#This is a new game for me to write
print "What is your name?"
name = raw_input()
if name == "Jessica":
print "Well don't you have the nicest name in the world!"
print "How many pets do you have?"
if name != "Jessica":
print "Okay how many pets do you have?"
pets = int(raw_input())
if pets == 0 and name != "Jessica":
print "Wow, I feel so sorry for you. You have a sad life."
if pets == 0 and name == "Jessica":
print "That's too bad, but at least you still have a cool name."
if pets > 0 and name != "Jessica":
print "Ohhh.. how fun! Lucky you!"
if pets > 0 and name == "Jessica":
print "I have to stop talking to you because I am too jealous of your life." | true |
2777b507d14cdeae90f501968e1060e5c41a64c2 | cliffordjorgensen/PYTHON | /simplePrograms/stateCapitals.py | 2,603 | 4.375 | 4 | #Cliff Jorgensen
#program stores states/capitals in a dictionary
#allows user to add, print, find, and delete entries
#dictionary stores {state:capital} pairs, state = key, capital = value
def menu():
print("\nMENU: \n\n"
"(1) Add a new state to the study guide. \n"
"(2) Print all state/capital pairs stored. \n"
"(3) How many states are in the study guide. \n"
"(4) Look for a specific state capital. \n"
"(5) Delete an entry from the study guide. \n"
"(6) EXIT.\n")
option = int(input("Enter menu choice: "))
while option < 1 or option > 6:
option = int(input("\nInvalid entry. Please enter (1-6) "))
return option
#allows user to add a new state:capital entry if not already stored
def addCapital():
state = input("\nPlease enter state: ")
state = state.capitalize()
if state in stateDict:
print("\nSorry, there is already an entry for ", state,"\n")
else:
capital = input("\nPlease enter the capital: ")
capital = capital.capitalize()
stateDict[state] = capital
return
#prints all state/capitals entries
def allState():
if len(stateDict) == 0:
print("\nNo states in dictionary. ")
else:
for state in stateDict:
print("\nSTATE:", state," CAPITAL:", stateDict[state])
#checks for and deletes entry
def delEntry():
state = input("\nWhat state do you want to delete? ")
state = state.capitalize()
if state in stateDict:
print("\n", state, " has been removed.\n ")
del stateDict[state]
else:
print(state, "is not in the study guide. ")
return
#finds specific state and prints the capital
def findState():
state = input("\nName of state you are looking up: ")
state = state.capitalize()
if state in stateDict:
print("\n ","Capital:", stateDict[state],"\n")
else:
print("\nState is not in the study guide. ")
#main process
stateDict = {} #dictionary intially empty
print("\n********** U.S. States and Capitals **********")
choice = menu()
while choice != 6: #true until user wishes to exit
if choice == 1: #add an entry
addCapital()
elif choice == 2: #print all states and capitals.
allState()
elif choice == 3:
print(len(stateDict),"states") # prints number of states stored
elif choice == 4: #look for a state
findState()
elif choice == 5: #delete an entry
delEntry()
choice = menu()
| true |
5357bf635ca43a1fd224bd90840580a41db49fad | cliffordjorgensen/PYTHON | /simplePrograms/mathCalculator.py | 1,352 | 4.46875 | 4 | #Cliff Jorgensen
#this program allows the user to perform a math calculation
#the user will choose the operation(+,*,-)
#the user will provide the operands
#main process
def greeting(): # function welcomes the user
print('Welcome to the Math Calculator\n')
return
def menu(): #present user with operation choices
print("\nValid Operations are: * + - ")
return
def add(num1, num2):
total = num1 + num2
print("\nSum is ", total)
return
def subtract(num1, num2):
total = num1 - num2
print("\nSubtraction is ", total)
return
def multiply(num1, num2):
total = num1 * num2
print("\nProduct is ", total)
def divide(num1, num2):
total = num1//num2
print("\nProduct is ", total)
operation = input("Enter your choice of operation (Valid Operations are: * + - / )")
# loop only executes if input is invalid
while operation != '*' and operation != '+' and operation != '-'and operation != '/':
print("Invalid operation")
menu()
operation = input("Enter your choice of operation ")
op1 = int(input("\nenter the first operand "))
op2 = int(input("\nenter the second operand "))
if operation == '+':
add(op1, op2)
elif operation == '*':
multiply(op1, op2)
elif operation == '-':
subtract(op1, op2)
else:
divide(op1, op2)
| true |
6b1d4217da4fe9d6b8f8b74aa43139f3d6376c5d | MerianeFranco/RutgersBootCamp | /Classwork/03-Python/1/Activities/02-Stu_HelloVariableWorld/Unsolved/HelloVariableWorld.py | 877 | 4.375 | 4 | # Create a variable called 'name' that holds a string
name = "X AE A-Xii"
# Create a variable called 'country' that holds a string
country = "US"
# Create a variable called 'age' that holds an integer
age =9
# Create a variable called 'hourly_wage' that holds an integer
hourly_wage = 1000.00
# Calculate the daily wage for the user
daily_wage = 8*hourly_wage
# Create a variable called 'satisfied' that holds a boolean
satisfied = True
# Print out "Hello <name>!"
print ("Hello " + name)
# Print out what country the user entered
print(name + " home country is "+country)
# Print out the user's age
print (name + " is " + str(age) + " months old")
# With an f-string, print out the daily wage that was calculated
print (f"Daily wage for {name} is {daily_wage}")
# With an f-string, print out whether the users were satisfied
print (f"{name } is satisfied: {satisfied}")
| true |
2f6a28ba96777a2c41924ea134b4a105f2b45799 | PXMYH/ds_algo | /801-900/876.py | 2,312 | 4.1875 | 4 | #!/usr/bin/env python3
import timeit
import time
import big_o
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class LinkedList:
def __init__(self):
self.head = None
class Solution:
def middleNodeHareTurtle(self, head: ListNode) -> ListNode:
# two pointers with hare turtle algo
hare, turtle = head, head
while hare and hare.next:
turtle, hare = turtle.next, hare.next.next
return turtle
def middleNodeTraversal(self,head: ListNode) -> ListNode:
node, c = head, 0
while node:
c += 1
node = node.next
mid, node = c // 2, head
for _ in range(mid):
node = node.next
return node
def construct_linked_list(linked_list) -> ListNode:
if len(linked_list) == 0: return
llist = LinkedList()
llist.head = ListNode(1)
# print(f"llist val = {ListNode(1).val}")
# print(f"llist = {llist.head.val}")
llist.next = ListNode(linked_list[1])
# print(f"llist.next = {llist.next.val}")
llist.next.next = ListNode(linked_list[2])
# print(f"llist.next.next = {llist.next.next.val}")
llist.next.next.next = ListNode(linked_list[3])
# print(f"llist.next.next.next = {llist.next.next.next.val}")
llist.next.next.next.next = ListNode(linked_list[4])
# print(f"llist.next.next.next.next = {llist.next.next.next.next.val}")
# for i in range(1,len(linked_list)):
# print(f'index = {i}')
# llist.next = ListNode(linked_list[i])
# llist.next = None
return llist
llist_vals = [1,2,3,4,5]
llist = construct_linked_list(llist_vals)
# while llist:
# print(f"current node value: {llist.head.val}")
# llist = llist.next
s = Solution()
start = time.time()
s.middleNodeHareTurtle(llist)
end = time.time()
print(f'Hare Turtle method takes time: {end - start}')
start = time.time()
s.middleNodeTraversal(llist)
end = time.time()
print(f'Traversal method takes time: {end - start}')
# best_hare_turtle, others_hare_turtle = big_o.big_o(s.middleNodeHareTurtle, llist.head, n_repeats=100)
# best_traversal, others_traversal = big_o.big_o(s.middleNodeTraversal, llist.head, n_repeats=100)
# print(best_hare_turtle)
# print(best_traversal)
| true |
c12ccd10e460280b66148e652bf1766fd4937c8d | inomani/MyProjects | /Python programs/Karan projects/Happy.py | 895 | 4.125 | 4 | # Happy Numbers - A happy number is defined by the following process.
# Starting with any positive integer, replace the number by the sum of
# the squares of its digits, and repeat the process until the number
# equals 1 (where it will stay), or it loops endlessly in a cycle which
# does not include 1. Those numbers for which this process ends in 1
# are happy numbers, while those that do not end in 1 are unhappy numbers.
# Display an example of your output here. Find first 8 happy numbers.
def getSum(n):
if n == 0:
return 0
else:
return ((n%10)**2 + getSum(n//10))
def getHappySum(n):
sum = getSum(n)
while sum != 1 and sum != 4:
sum = getSum(sum)
return sum
def getfirsteight():
happyLst = []
i = 1
while len(happyLst) < 100:
s = getHappySum(i)
if s == 1:
happyLst.append(i)
i = i + 1
return happyLst
lst = getfirsteight()
print lst
| true |
9b2e671877e0a19df9b9bc09becfa43ef987adf7 | scttohara/intro_to_python_class_labs | /lab4/triangle_lab_part1.py | 1,247 | 4.3125 | 4 | """
program reads three user inputs from 3 prompts. returns TRIANGLE or NOT TRIANGLE
"""
"""
how to detect a triangle
Three line segments, a, b, and c, can form a triangle if and only if
length(a) + length(b) > length(c) AND
length(a) + length(c) > length(b) AND
length(b) + length(c) > length(a)
"""
def triangle_detect():
"""
Identifies a triangle, given three sides by a user then tells the user
if the three sides could form a triangle
:return: nothing
"""
a = float(input("Lets see if we can make a triangle\nPlease enter a float for length 'a':\n"))
b = float(input("Please enter another float for length 'b':\n"))
c = float(input("Please enter one last float for length 'c':\n"))
if (a + b > c) and (a + c > b) and (b + c > a):
print("\nIS A TRIANGLE")
return 0
else:
print("\nIS NOT A TRIANGLE")
return 1
triangle_detect()
"""
simple TESTS
"""
# should return yes triangle
"""
triangle_detect(5, 5, 5)
triangle_detect(10, 10, 2)
triangle_detect(3, 4, 5)
triangle_detect(6, 8, 7)
print("\n")
# should return no triangle
triangle_detect(10, 10, 30)
triangle_detect(1, 3, 7)
triangle_detect(18, 27, 44.999999999999999)
"""
| true |
41e900560fd2ab3b424ea9fe1b8092eb322463fd | scttohara/intro_to_python_class_labs | /lab6/dice_simulation_lab_6.py | 2,109 | 4.40625 | 4 | """
picks two dice a given number of times. At the end the number of times each
number was rolled is output in a table format
"""
import random
def main():
get_number_of_iterations_from_user()
def get_number_of_iterations_from_user():
"""
prompts user for number of iterations to do.
:return: nothing
"""
rolls = int(input("Please enter the number of times I should roll the dice\n"))
roll_dice(rolls)
def roll_dice(rolls):
"""
Rolls the dice a given number of times. and then send the rolls completed and the rolls_count_dictionary.
rolls_count_dictionary holds the number of times each given number occurred.
:param rolls: int
:return: nothing
"""
rolls_done = 1
# holds a given number between 2 and 12 and the number of times it occurred
rolls_count_dict = {2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}
while rolls_done <= rolls:
# gets random number between 1 and 6 inclusive
roll1 = random.randint(1, 6)
# gets random number between 1 and 6 inclusive
roll2 = random.randint(1, 6)
# increases the count of the occurrence of a number by 1 when it occurs
rolls_count_dict[roll1 + roll2] += 1
# increases count of rolls completed
rolls_done += 1
# one is subtracted because the picks_done count starts at 1
print_output_in_table_format(rolls_done-1, rolls_count_dict)
def print_output_in_table_format(rolls_done, rolls_count_dict):
"""
prints output information in formatted table.
:param rolls_done: int
:param rolls_count_dict: dictionary
:return: nothing
"""
print("total iteration(s): " + str(rolls_done))
print("\nnumber picks percent")
rows_printed = 2
while rows_printed <= 12:
# formats the output of the table
print('{:6}{:8}{:10}'.format(rows_printed, rolls_count_dict[rows_printed],
round(rolls_count_dict[rows_printed]/rolls_done, 2)))
rows_printed += 1
if __name__ == '__main__':
main()
| true |
bd53b28ae4856aacd14f24c145339ffb3ec3db7c | techshiv/ml | /prgm9.py | 824 | 4.15625 | 4 | """
9. Write a program to implement K-Nearest Neighbour algorithm to classify the iris
data set. Print both correct and wrong predictions. Java/Python ML library classes can
be used for this problem.
"""
from sklearn import datasets, metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
dataset = datasets.load_iris()
X = pd.DataFrame(dataset.data)
y = pd.DataFrame(dataset.target)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train.values.ravel())
y_prediction = knn.predict(X_test)
print('K-Nearest Neighbour Accuracy : ', metrics.accuracy_score(y_test, y_prediction))
print("Confusion Matrix : \n", metrics.confusion_matrix(y_test, y_prediction))
| true |
6792554148208d01d3000c188c877d0ea340569c | jjgm666/practice | /test.py | 1,090 | 4.125 | 4 | #Just a test py
print("Welcome to python!")
print("Python is fun!")
print("Problem driven!")
print('Welcome to python!')
print('''This is the first line.
This is the second line.
This is the third line.''')
print("Problem driven!")
print((10.5+2*3)/(45-3.5))
#test turtle
import turtle #导入turtle绘图包
#绘制初始点
turtle.showturtle()
turtle.write("welcome to python")
#箭头向箭头方向移动100
turtle.forward(100)
#按照当前箭头方向向右旋转90°,颜色蓝色,长度50
turtle.right(90)
turtle.color("blue")
turtle.forward(50)
#按照当前箭头方向向右旋转90°,颜色绿色,长度100
turtle.right(90)
turtle.color("green")
turtle.forward(100)
#按照当前箭头方向向右旋转45°,颜色红色,长度50
turtle.right(45)
turtle.color("red")
turtle.forward(80)
#penup函数抬起笔
turtle.penup()
#turtle的goto语句,将箭头移至任何位置
turtle.goto(0,50)
#pendown函数放下笔
turtle.pendown()
#用circle函数绘制圆
turtle.color("purple")
turtle.circle(60)
#done函数使图像稳定输出
turtle.done()
| false |
ed41273f4c75e62e5b843eacfddcb98937b093c2 | aamlj/GitPython | /MilesToKM_MikeJones.py | 341 | 4.1875 | 4 | # Author: Mike Jones
# program that converts miles to kilometers based on input.
x = input ("Enter number of miles to convert:")#prompt user
print ("Miles\tKilometer ")
print ("-----------------")
#print ("Miles\tKilometers")
k = 0
m = 0
while (x > m) or (x>k):#while loop to do conversion
m += 1
k += 1.609
print m,'\t', k
| true |
69dcc3f1d290c4c90119fb52f6b5c3d2763501cc | aamlj/GitPython | /AveragesUpdated_MikeJones.py | 588 | 4.3125 | 4 | def average (a,b,c): # create a function for average
""" this function will take the average of three values by adding together
and dividing by three"""
return ((a+b+c)/3) #formula for computing averages
avg1 = average (9, 9, 9) #create varible avg1
x=int (input ("Enter first number: ")) #ask for input from user
y=int (input("Enter second number: ")) #ask for input from user
z=int (input("Enter third number: ")) #ask for input from user
avg2=average (x,y,z) #create varible avg2
avg3=average (x,9,z) #create varible avg3
print avg1, avg2, avg3
| true |
5dd36df337053c8db0ad3ad815697c0180b831dc | gsivabe/PythonTutorials | /tuple_set.py | 902 | 4.4375 | 4 | #Example for Tuple (NOT MUTABLE)
print ("Below are Example for Tuple (NOT MUTABLE)")
t = ()
print (type(t))
t = (1,2,3)
print (t)
t = (1, 'AcadView', 1.2, 'Dehradun')
print(t)
t = (1, 2, 3)
print(t[-1])
# Slicing
print(t[1:3])
t = (1, 2, 3, (4, 5), [6, 7, 8])
t[4][0] = 'hi'
print(t)
# Convert a list to tuple
l = [0, 1, 2]
print(tuple(l))
print(tuple('python'))
#Example for Sets
print ("\n")
print ("Below are Example for SET")
s = set()
print(type(s))
s = {1, 2, 3}
print(s)
print(type(s))
s = set ([4,5,6])
print(s)
print(type(s))
#Duplicates Removed
li = [1, 2, 3, 4, 1 , 5, 2]
s = set(li)
print(s)
# Set Operations
print ("\n")
print ("SET OPERATIONS")
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2)
print(set1.union(set2))
print(set1 & set2)
print(set1.intersection(set2))
print(set1 - set2)
print(set1.difference(set2))
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
| false |
95811f7551b3eed60352107c71d14343c2d27b1d | sukanta-here/general | /algorithm/python/merge_sort.py | 1,403 | 4.21875 | 4 | # 1) Find middle point mid = (l + h)/2
# 2) If key is present at middle point, return mid.
# 3) Else If arr[l..mid] is sorted
# a) If key to be searched lies in range from arr[l]
# to arr[mid], recur for arr[l..mid].
# b) Else recur for arr[mid+1..h]
# 4) Else (arr[mid+1..h] must be sorted)
# a) If key to be searched lies in range from arr[mid+1]
# to arr[h], recur for arr[mid+1..h].
# b) Else recur for arr[l..mid]
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print(arr)
mergeSort(arr)
print("Sorted array is: ")
print(arr)
# Complexity Analysis:
# Time Complexity: O(log n).
# Binary Search requires log n comparisons to find the element. So time complexity is O(log n).
# Space Complexity: O(1).
# As no extra space is required. | true |
1b3f21426b91d026287983ddb657c153d40c8d6c | MarlingSharp/speedDistanceTime_console | /main.py | 555 | 4.5 | 4 | print('Basic Physics Calculator')
# Read in the values from the user, the input function returns a string
distance_m_str = input('Enter the Distance (m): ')
time_s_str = input('Enter the time (s): ')
# Casting to floats
distance_m = float(distance_m_str)
time_s = float(time_s_str)
# Calculate the speed
speed_ms = distance_m / time_s
# Use formatted strings to print out the various values
print(f"You travelled {distance_m} metres in {time_s} seconds, your speed was {speed_ms} m/s")
# Just so we know that the program reached the end
print('Done') | true |
d892d9edd40c30f1210fe1eef7fdbc115b329052 | bsubedi26/python_stuff | /coding_bat/strings/double_char.py | 596 | 4.28125 | 4 | """
Given a string, return a string where for every char in the original, there are two chars.
double_char('The') → 'TThhee'
double_char('AAbb') → 'AAAAbbbb'
double_char('Hi-There') → 'HHii--TThheerree'
"""
def double_char(strings):
result = ''
for str in strings:
result += str + str
return result
def test(actual, expected):
if actual == expected:
result = 'CORRECT'
else:
result = 'WRONG'
print(result)
test(double_char('The'), 'TThhee')
test(double_char('AAbb'), 'AAAAbbbb')
test(double_char('Hi-There'), 'HHii--TThheerree')
| true |
ac9ed28b5eb0abf7cf980e2362b42f04194352e7 | saurabhdhumane/saurabh | /trianglecircle.py | 584 | 4.4375 | 4 | #for area of triangle
a=float(input('enter first side :'))
b=float(input('enter second side :'))
c=float(input('enter third side :'))
#for area of circle
radius=float(input('enter the radius of circle :'))
PI = 3.14 # circle pi value
#tringle formula
s=(a+b+c)/2
areatringle=(s*(s-a)*(s-b)*(s-c))**0.5
#circle formula
areacircle=PI*radius*radius
circumference=2*PI*radius
#for output of triangle
print("the area of the triangle is :%0.2f"%areatringle)
#for output of circle
print("area of a circle is : %2f"%areacircle)
print("circumference of circle is : %2f"%circumference) | true |
8185fbf5ef0c0e5dfd5038caa201de310a1df9a0 | amarantejoacil/estudo-python | /fundamentos/12aula_lista.py | 1,111 | 4.28125 | 4 |
lista = []
# list é dinamina e heterogenico, aceita varios tipos... string, int, float
# dir(lista) retorna o tipo
# help(list) te mostra como utilizar a list
lista.append(1) # adiciona 1
lista.append(5) # adiciona o 5
print(lista)
nova_lista = [1, 5, 'ana', 'bia'] # lista com varios tipos
print(nova_lista)
nova_lista.remove(5)
# remove o numero 5, nao confudir com posicao 5. retorna [1, 'ana', 'bia']
print(nova_lista)
nova_lista.reverse()
print(nova_lista) # reverte a posicao retorna ['bia', 'ana', 1]
# sempre começa o index(posicao) do 0
lista_exemplo = [1, 5, 'ana', 'guilherme', 3.1415]
print(lista_exemplo.index('guilherme'))
print(1 in lista) # retorna true... existe 1 na lista?
print('rebeca' in lista) # retorna false...nao existe rebeca na lista
print('Pedro' not in lista) # retorna true, pedro nao existe.
print(lista_exemplo[2]) # retorna posicao 2... contantdo apartir do 0
lista_nome = ['Ana', 'Lia', 'Rui', 'Paulo', 'Dani']
print(lista_nome[1:3]) # acessando intervalo de informacao
del lista_nome[2]
print(lista_nome) # deleta posicao 2 contando do 0
| false |
419e3520989edd333e6d1f17254cfda9224438de | xingorg1/JuFengGuo | /Python/code/punches2.py | 1,760 | 4.1875 | 4 | #你和电脑已经对自己要出的拳进行了选择,接下来,我们需要知道双方的出拳类型。
#请使用print()函数补充亮拳的结果。
import random
# 出拳
punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)
user_choice = ''
user_choice = input('请出拳:(石头、剪刀、布)') # 请用户输入选择
# if user_choice in punches:
while user_choice not in punches: # 当用户输入错误,提示错误,重新输入
print('输入有误,请重新出拳')
user_choice = input('输入有误,请重新出拳')
# 亮拳
print('————战斗过程————')
print('电脑出拳:%s' % (computer_choice))
print('你出拳:%s' % (user_choice))
# 胜负
print('—————结果—————')
if computer_choice == '石头':
if user_choice == '石头':
print('平局')
elif user_choice == '剪刀':
print('你输了')
elif user_choice == '布':
print('你赢了')
elif computer_choice == '剪刀':
if user_choice == '石头':
print('你赢了')
elif user_choice == '剪刀':
print('平局')
elif user_choice == '布':
print('你输了')
elif computer_choice == '布':
if user_choice == '石头':
print('你输了')
elif user_choice == '剪刀':
print('你赢了')
elif user_choice == '布':
print('平局')
# 参考部分代码
# print('—————结果—————')
# if user_choice == computer_choice: # 使用if进行条件判断
# print('平局!')
# elif (user_choice == '石头' and computer_choice == '剪刀') or (user_choice == '剪刀' and computer_choice == '布') or (user_choice == '布' and computer_choice == '石头'):
# print('你赢了!')
# else:
# print('你输了!') | false |
f2d856eabec86895813a9826f73c2a07e0ccabce | jamesmead/python-training | /dictionary.py | 338 | 4.34375 | 4 | """Example of a dictionary."""
words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
print(words)
print(words["Hello"]) # outputs the VALUE of the key
collection = {}
collection[0] = 123
collection[1] = 254
collection[2] = 234
print(collection)
del(collection[0]) # deletes first key/value pair from collection
print(collection)
| true |
4c666c5ce21adb166dad4af5d220e13f86f19d93 | OanaTudu/BookAnalyses | /wordCount.py | 1,652 | 4.5625 | 5 | """main function to count words in a file, with
implemented helper functions:
print_words(filename) function that counts
how often each word appears in the text and prints:
word1 count1
word2 count2
For the --topcount flag, implement a print_top(filename) which is similar
to print_words() but which prints just the top 20 most common words sorted
by frequency"""
import sys
def words_from_file(filename):
words = []
f = open(filename, 'r')
for line in f:
words = words + line.lower().split()
dict_words = {}
for w in words:
if w not in dict_words:
dict_words[w] = 1;
else:
dict_words[w] += 1;
f.close()
return dict_words
def print_words(filename):
this_dict = words_from_file(filename)
#print(this_dict)
for (word,occurance) in this_dict.items():
print('{:15}{:3}'.format(word,occurance))
def print_top(filename):
this_dict = words_from_file(filename)
new_dict = sorted(this_dict.items(), key=lambda x: x[1],reverse = True )[:20]
print(new_dict)
for (word,occurance) in new_dict:
print('{:15}{:3}'.format(word,occurance))
###
# Main function will call print_words() if the flag is --count, and
# print_top() if the flag is --topcount
def main():
if len(sys.argv) != 3:
print ('usage: ./wordcount.py {--count | --topcount} file')
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_words(filename)
elif option == '--topcount':
print_top(filename)
else:
print ('unknown option: ' + option)
sys.exit(1)
if __name__ == '__main__':
main()
| true |
e0b4c39b6880787d1ffc6894c8a4213e688b94af | Daweet/ImmersiveData | /collatz_sequence.py | 856 | 4.46875 | 4 | """
You are going to develop an application to produce numbers in a sequence.
The user will be required to enter a number, and for that number, you will:
* Divide the number by 2 if it is even
* Multiply the number by 3, and add 1 if it is odd.
* Do this until you get to 1.
Ask the user if he/she would like to input another number, and continue until he/she does not want to enter any more numbers.
Show the results as you go. For example, the number 5 should produce the following output:
> 5 16 8 4 2 1
The number 3 should produce the following output:
> 3 10 5 16 8 4 2 1
"""
def collatz_sequence(num):
if num == 1:
return num
elif num % 2 == 0:
return (num / 2)
elif num % 2 != 0:
return (3*num +1)
n = input("Enter a number: ")
while n != 1:
n = collatz_sequence(int(n))
print(int(n), end =" ") | true |
c28090038f9b535e802342cf7f18e73314c322b7 | josegreg/hello-world | /course2/numpys/ex1.py | 883 | 4.25 | 4 | import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
import math
'''
1.- Choose a valie and set the variable x to that value
2.- What is command to compute the square and cube of x
3.- Choose and angle and set the variable theta to its value
4.- What is sin0 cos0? Angles can be measured in degrees or radians
Which of these are being used?
5- Use the np.linspace function to create a row vector called meshPoints
containing exactly 500 values with values evenly spaced between -1 and 1
6.- What expression will yield the value of the 53th element of meshPoints?
What is this value?
7.- Produce a plot of a sinusoid on the interval [-1,1] using the command
plt.plot(meshPoints,np.sin(2*pi*meshPoints))
'''
x = math.pi/6
print("The square of {} is {}".format(x,x**2))
print("The square of {} is {}".format(x,x**3))
print(math.sin(x))
print(math.cos(x))
| true |
44c2a893233663ed1a6243453b0a477e55281279 | Nyyen8/Module7 | /fun_with_collections/file_IO.py | 1,907 | 4.40625 | 4 | """
Program: file_IO.py
Author: Paul Elsea
Last Modified: 06/20/2020
Program to read from and write to a file.
"""
import os as os
'''This opens student_info.txt in append mode, then writes the input tuple into the file.
:write_doc: The file being opened.
:input_info: The input tuple to be written.
:returns: Nothing.'''
def write_to_file(input_info):
with open('student_info.txt', 'a') as write_doc:
write_doc.write(str(input_info)+'\n')
write_doc.close()
'''This accepts user input of student name, number of scores, then scores themselves, writes it to a list, then
converts the list to a tuple and passes it to write_to_file().
:student_info: List to be populated by user input.
:count: counter variable
:score_num: Int variable to set to determine how many scores are needed.
:finalized_student_info: Finished populated list that is then converted to a tuple.
:returns: Nothing.'''
def get_student_info():
student_info = []
student_info.append(input('Please enter student name:\n'))
count = 0
score_num = int(input('Please enter number of scores to be entered:\n'))
while count < score_num:
student_info.append(input('Please enter score:\n'))
count += 1
finalized_student_info = tuple(student_info)
write_to_file(finalized_student_info)
'''Opens work file and reads contents.
:file_name: The file to be read
:read_file: The object being used to read from the file
:line: The individual line being pulled from the file.
:returns: Nothing.'''
def read_from_file():
file_dir = os.path.dirname(__file__)
file_name = 'student_info.txt'
read_file = open(os.path.join(file_dir, file_name), 'r')
line = read_file.read()
print(line)
read_file.close()
if __name__ == '__main__':
get_student_info()
get_student_info()
get_student_info()
get_student_info()
read_from_file()
input('Press enter to quit.') | true |
831176d7e586f68856ad531badd3b114302f860a | cintiamh/PythonCrashCourse2018 | /basics/cars.py | 273 | 4.1875 | 4 | cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(len(cars))
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)
print(sorted(cars))
print(cars)
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
| false |
4fd31453de6f158d9468d2e169a1e256f933dc98 | ashleymendia/lab7 | /lab_07/shuffling_lists.py | 1,238 | 4.625 | 5 | import random
def shuffle_create():
"""
Creates and returns a list with original_list's elements shuffled in any pseudo-random order.
:param original_list: A list of elements
:return output_list: A list of elements
"""
pass
def shuffle_in_place():
"""
Shuffles original_list's contents in-place. Can be done in infinitely amounts of ways, so it really depends on the
student here. In my case, I am just doing random replacings an len(original_list) * 2 amount of times.
:param original_list: A list of elements
:return: None
"""
pass
def main():
"""
Just some sample behavior. Feel free to try your own.
"""
list_one = ["Jean Valjean", "Javert", "Fantine", "Cosette", "Marius Pontmercy", "Eponine", "Enjolras"]
print("ORIGINAL LIST_ONE: {}".format(list_one))
# First function execution
print("LIST CREATED BY SHUFFLE_CREATE: {}\n".format(shuffle_create(list_one)))
list_two = ["A", 0, 0, 5, 1, 3, 2]
print("ORIGINAL LIST_TWO: {}".format(list_two))
# Second function execution
shuffle_in_place(list_two)
print("LIST_TWO AFTER SHUFFLE_IN_PLACE: {}".format(list_two))
# DO NOT WRITE CODE BELOW THIS LINE
if __name__ == '__main__':
main()
| true |
8eba70d24343a2f1895d2d57159720a1e9939340 | nikhilpnarang/algorithms-and-data-structures | /algorithms/string/min_edits.py | 2,488 | 4.28125 | 4 | def min_edits(astr, bstr):
"""Find the minimum edit distance between two strings
This algorithm is a solution to the minimum edit distance problem described on the
IDeserve link: http://www.ideserve.co.in/learn/edit-distance-dynamic-programming.
This problem simplifies down to a sequence alignment problem and can be solved
using dynamic programming. There are three types of edits, each with an edit
distance of one: insertions, deletions, and substitutions. As a result, in
calculating the minimum edit distance of two substrings {a0...ai} and {b0...bj}
we observe four cases:
1. ai and bj match, and no edits are required.
2. ai and bj do not match, and a substitution on ai yields an optimal solution.
3. ai and bj do not match, and an insertion on ai yields an optimal solution.
4. ai and bj do not match, and a deletion on ai yields an optimal solution.
Another critical point in solving this solution is the fact that a deletion of ai
is synonymous with an insertion on bj, and vice versa. This allows us to simplify
the four cases into two classes: one that requires a gap or a shift (an insertion
or deletion), and one that does not (a match or a substitution). Furthermore, we
can determine which case to take when a match does not occur based on previously
calculated values. That is, if ai and bj do not match, the optimal solution is the
case that results in the minimum edit distance.
Time Complexity:
O(nm). The final solution relies on the fact that we calculate solutions for every
subproblem of astr (length n) and bstr (length m).
Space Complexity:
O(nm). The OPT array is a double list of dimensions n x m.
"""
return min_edits_util(astr, bstr, len(astr), len(bstr))
def min_edits_util(astr, bstr, alen, blen):
OPT = [[0] * (alen + 1) for bchar in range(blen + 1)]
for i in range(blen + 1):
for j in range(alen + 1):
if i == 0:
# j insertions in front of bstr
OPT[0][j] = j
elif j == 0:
# i insertions in front of astr
OPT[i][0] = i
else:
# all possibilities
match = OPT[i - 1][j - 1] + int(not (bstr[i - 1] == astr[j - 1]))
ashift = OPT[i][j - 1] + 1
bshift = OPT[i - 1][j] + 1
OPT[i][j] = min(match, ashift, bshift)
return OPT[blen][alen]
| true |
eab28d7b430393fc73156a7f0ec57140d642e1e8 | Unintented/Python-basis | /for_list.py | 1,453 | 4.46875 | 4 | # 迭代列表中每个元素,通过缩进判断是否属于for循环
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ",that was a great trick!")
print("I can't wait to see your next trick," + magician.title() + '.\n')
print("Thank you, every one!")
# 顺序打印数字,不包括最后一个
for value in range(1, 5):
print(value)
# 将一连串数字转化成列表
numbers = list(range(1, 6))
print(numbers)
# 从2开始,每次加2,超过11停止
even_numbers = list(range(2, 11, 2))
print(even_numbers)
# 创建需要的数字列表
square_numbers = []
for value in range(1, 11):
squre = value ** 2
square_numbers.append(squre)
print(square_numbers)
# 最值、求和
print(max(square_numbers))
print(min(square_numbers))
print(sum(square_numbers))
# 列表解析
square_numbers_2 = [value ** 2 for value in range(11, 21)]
print(square_numbers_2)
# 列表的一部分称为切片,下标从0开始,不包括最后一个元素,可省略起始或终止索引
print(square_numbers_2[2:5])
print(square_numbers_2[-3:])
# 遍历切片
for value in square_numbers_2[-5:-3]:
print(value)
# 列表复制
my_foods = ['pizza', 'ice cream', 'noodles']
# 此种方式是将原列表的备份赋给新列表,二者独立变化;若无中括号,则表示将新列表关联到原列表上,二者一变全变
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
| false |
3fc544b2b6276b30e3c027837e55778c0ebfa593 | vitinop/BLUE-T3C6-Atividades-Modulo1 | /aula_13-Funções/Atividade_Aula_13-Ex2.py | 442 | 4.125 | 4 | # Faça um programa, com uma função que necessite de um parametro.
# A função retorna o valor de caractere ‘P’, se seu argumento for positivo, e ‘N’, se seu argumento for zero ou negativo.
def verificar_positivo():
num=int(input("Insira um numero para descobrir se ele é positivo ou negativo: "))
if num > 0:
return f'P'
elif num <= 0:
return f'N'
numero=verificar_positivo()
print(numero) | false |
e29387b036bc0dc91d15509e67598aadb4dffb75 | vitinop/BLUE-T3C6-Atividades-Modulo1 | /aula_7-atividades_while_ e_for/Atividade_Aula_7-Ex2While.py | 1,117 | 4.15625 | 4 | #02 - Crie um programa que leia a idade e o sexo de várias pessoas. A cada
#pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não
#continuar. No final, mostre:
#A) Quantas pessoas têm mais de 18 anos.
#B) Quantos homens foram cadastrados.
#C) Quantas mulheres têm menos de 20 anos.
controle=" "
contadormidade=0
contadormulher=0
contadorhomem=0
while controle!="S":
idade=int(input("Olá, insira a idade da pessoa :"))
sex=str(input("Olá, informe o sexo biologico da pessoa, digite F para feminino e M para masculino: "))
sex=sex.upper()
if idade>=18:
contadormidade=contadormidade+1
if sex=="M":
contadorhomem=contadorhomem+1
elif idade<20 and sex=="F":
contadormulher=contadormulher+1
print(f"""
O número de pessoas com mais de 18 é: {contadormidade}
O número de homens cadastrados é: {contadorhomem}
O número de mulheres com menos de 20 anos é: {contadormulher}""")
controle=("Gostaria de encerrar o programa ? [S/N]")
controle=controle.upper().strip()[0]
| false |
d974262c41436c29a4a10fd89e348857e0b9563e | vitinop/BLUE-T3C6-Atividades-Modulo1 | /aula_17-Atividades_Programacao_orientada_objeto/Atividade_Aula_17-Ex2.py | 1,345 | 4.125 | 4 | #02 - Crie um programa que gerencie o aproveitamento de um jogador de futebol.
# O programa vai ler o nome do jogador e quantas partidas ele jogou.
# Depois vai ler a quantidade de gols feitos em cada partida.
# No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.
# Vamos aprimorar o código cadastro de jogador de futebol py que foi desenvolvido no Code Lab da aula 14 Faça com que o seu código
# funcione para vários jogadores incluindo um sistema de visualização de detalhes de aproveitamento de cada jogador
class Jogador:
def __init__(self):
self.nome = input('Digite o nome do jogador: ')
self.partidas = int(input('Digite a quantidade de partidas jogadas: '))
self.golsTotal = int(input('Digite a quantidade de gols: '))
self.golsPartida = self.golsTotal / self.partidas
def aproveitamento_func(self):
return f'''
Nome: {self.nome}
Partidas: {self.partidas}
Gols no Campeonato: {self.golsTotal}
Aproveitamento: {self.golsPartida:.2f} por partida'''
time = dict()
while True:
jogador = Jogador()
time[jogador.nome] = jogador
print(jogador.aproveitamento_func())
continuar = input('Quer continuar cadastrando? [S/N] ').strip().upper()[0]
if continuar == 'N':
break | false |
f7d962fa2357a7ce79f3cdfae680c08840798aa9 | renukamani/topgear_python | /strings6.py | 343 | 4.25 | 4 | str1 = raw_input("enter the string")
for letter in str1 :
print letter
print(str1*100)
str2 = raw_input("enter a string with <:> character ")
str2_1 = str2[:str2.index(":")]
str2_2 = str2[str2.index(":")-1:]
print str2_1
print str2_2
str3 = raw_input("enter the string u want to concatenate with "+ str1)
new_str = str1+str3
print new_str
| true |
67dfb1551358ada2d2d97974b43d34c0ec16bcb0 | abhijeetpal09/Python | /advancedPython.py | 2,423 | 4.5 | 4 | my_dict = {
"youtube":"true",
"snapchat":"false",
"instagram":"true"
}
#.items() returns an array of tuples with each tuple consisting of a key/value pair from the dictionary
#.keys() method returns a list of the dictionary's keys
#.values() method returns a list of the dictionary's values.
#these methods will not return the keys or values from the dictionary in any specific order.
#You can think of a tuple as an immutable (that is, unchangeable) list. Tuples are surrounded by ()s and can contain any data type.
print(my_dict.items())
print(my_dict.keys())
print(my_dict.values())
#list_comprehension
even_squares = [x ** 2 for x in range(1,12) if x % 2 == 0]
print(even_squares)
cubes_by_four = [x ** 3 for x in range(1,11) if (x ** 3) % 4 == 0]
print(cubes_by_four)
#List slicing allows us to access elements of a list in a concise manner. The syntax looks like this:
#[start:end:stride]
#start-inclusive, stride-exclusive
#he default starting index is 0.The default ending index is the end of the list.The default stride is 1.
my_list = range(1, 11) # List of numbers 1 - 10
print(my_list[::2])
#Reverse a list with negative stride
my_list = range(1, 11)
backwards = my_list[::-1]
print(backwards)
#Lambda functions are defined using the following syntax:
#Python 3 onwards list
my_list = range(16)
print(list(filter(lambda x: x % 3 == 0, my_list)))
languages = ["HTML", "JavaScript", "Python", "Ruby"]
# Add arguments to the filter()
strn = filter(lambda lang:lang=="Python", languages)
print(list(strn))
squares = [x ** 2 for x in range(1,11)]
print(list(filter(lambda y:y >=30 and y<=70,squares)))
threes_and_fives = [x for x in range(1,16) if x % 3 == 0 or x % 5 == 0]
print(threes_and_fives)
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda x:x!='X',garbled)
print("".join(list(message)))
print(5 >> 4) # Right Shift
print(5 << 1) # Left Shift
print(8 & 5) # Bitwise AND
print(9 | 4) # Bitwise OR
print(12 ^ 42) # Bitwise XOR
print(~88) # Bitwise NOT(1's complement)
print(int("1",2))
print(int("10",2))
print(int("111",2))
print(int("0b100",2))
print(int(bin(5),2))
# Print out the decimal equivalent of the binary 11001001.
print(int("11001001",2))
def flip_bit(number,n):
result = number ^ (0b1 << n)
return bin(result)
print(flip_bit(32,2)) | true |
cd14763eb3f308150b335d09b14790c9e88a418f | nilima1791/neel-repository | /guess the number game.py | 888 | 4.21875 | 4 | # guess the number game
import random
print('Hello, Whats your name?')
name = input()
secretNumber =random.randint(1,20)
print('Well ,' + name +' I am thinking of a number between 1-20.')
for i in range (1,7):
print('Take a guess')
guess= int(input())
if guess > 20 :
print (' Please enter number between 1-20') # to make sure numbers b/w 1-20 are guessed
elif guess > secretNumber :
print('Too high . Take another guess')
elif guess < secretNumber:
print('Too low . Take another guess')
else :
break # for when the guess is right .
if guess == secretNumber:
print('Good Job!. It took you '+ str(i)+' chances to guess')
else :
print('Nope, the number I was guessing was '+ str(secretNumber) +'. Better luck next time')
guess > 20 :
print (' Please enter number between 1-20')
| true |
8eaf1c3dddfdd570e4d0eb586b68dc85401ab7ab | dalonlobo/Python-Beginner-Tutorials | /Part4/listcomprehensiondemo.py | 586 | 4.15625 | 4 | # List Comprehensions
#
# List Comprehensions is a very powerful tool,
# which creates a new list based on another list, in a single, readable line.
# sentence = "the quick brown fox jumps over the lazy dog"
# words = sentence.split()
# word_lengths = []
# for word in words:
# if word != "the":
# word_lengths.append(len(word))
# print(word_lengths)
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
lengths = [len(word) for word in words if word != "the"]
# word_lengths = [len(word) for word in words if word != "the"]
print(lengths) | true |
b3123952f90982e78aca725e2939b61da68fe64a | Vansh-Arora/SortingInPython | /mergeSort.py | 1,224 | 4.21875 | 4 | def mergeSort(arr, n):
# From here we divide.
if n>1: # Divide the array in 2 parts until the length of array is 1
arr1 = arr[:int(n/2)]
arr2 = arr[int(n/2):]
mergeSort(arr1,len(arr1))
mergeSort(arr2,len(arr2))
# In this pasrt we start conquer.
i=0
k=0
j=0
while i<len(arr1) and j<len(arr2):
if arr1[i]<=arr2[j]:
arr[k] = arr1[i]
k+=1
i+=1
elif arr2[j]<arr1[i]:
arr[k] = arr2[j]
k+=1
j+=1
# This part will make sure that if all elements of array 1 or 2 are inserted but some
# elements are left in another array.
# They are inserted in the same order as present in the remainig array.
# As both arrays are already sorted.
while i<len(arr1):
arr[k]=arr1[i]
k+=1
i+=1
while j<len(arr2):
arr[k]=arr2[j]
j+=1
k+=1
#DRIVER CODE
import random
n = int(input())
arr = []
for i in range(n):
arr.append(random.randint(1,1000))
#arr.append(int(input()))
mergeSort(arr,n)
print(arr)
| true |
b8c12b51fe4f99da1fa3b190cb8d54d3936b0a22 | gikimo/2018-2 | /hello.py | 850 | 4.21875 | 4 | print("hello world")
name=input("what is your name")
print("hello,"+name+"!")
#字符串与数字
C:\Users\dell>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> "let's say" '"hello world!"'
'let\'s say"hello world!"'
>>> temp=42
>>> print("the temperature is "+repr(temp))
the temperature is 42
#转义\
>>> path='c:\nowhere'
>>> print(path)
c:
owhere
#原始字符串
>>> print(r'c:\nowhere')
c:\nowhere
>>> print(r'hello\')
File "<stdin>", line 1
print(r'hello\')
^
SyntaxError: EOL while scanning string literal
>>> print(r'hello')
hello
>>> print(r'hello\\')
hello\\
>>> print(r'hello' '\\')
hello\
#命令行
c:\>cd #想去的地方,返回上一级cd..
| true |
2c9b5b13047dae398558669ee8314e5fe02828bc | Otavioarp/BCC-701 | /P-03-Estruturas de Decisão/p03q4.py | 554 | 4.15625 | 4 | '''
Otávio Augusto de Rezende Pinto
Email: otaviopqsi@gmail.com
'''
q=int(input('Digite a quantidade de lados: '))
if q>=3:
if 2<q<6:
l=float(input('Digite a medida do lado: '))
if q==3:
print(f'O polígono é um triângulo com área: {l**2*3**(1/2)/4:.2f}')
elif q==4:
print(f'O polígono é um quadrado com área: {l**2:.2f} ')
elif q==5:
print(f'O polígono é um pentágono com área: {3*l**2*3**(1/2)/2:.2f} ')
else:
print(f'Polígono não identificado ')
else:
print('Não é um polígono ') | false |
267fdb0329390200beb79aad8ec7b8d058beb497 | maxigarrett/cursoPYTHON | /clase 10 funcionesDeOrdenSuperior/4.funcionLambdaYFilter.py | 680 | 4.5 | 4 | """El objetivo de estas funciones anónimas, es poder simplificar la escritura cuando trabajamos con funciones de orden superior,
por ejemplo, la recientemente vista función FILTER.
Probemos modificar el código reemplazando las funciones simples con funciones LAMBDA en el ejemplo de FILTER con múltiplos de 3 y de 5.
MANERA NORMAL
lista=[23,12,4,7,33,75,2,9,10]
def m3(v):
if(v % 3==0):
return True
def m5(v):
if(v % 5==0):
return True
print(list(filter(m3,lista)))
print(list(filter(m5,lista)))
"""
# la forma de lambda
lista=[23,12,4,7,33,75,2,9,10]
print(list(filter(lambda x : x % 3==0, lista)))
print(list(filter(lambda x : x % 5==0, lista))) | false |
86e2b770ffb62454599ebea66432a4a498ea9ee0 | maxigarrett/cursoPYTHON | /1-ejercicios primera clase/4-ejercicio.py | 545 | 4.125 | 4 | #Si creamos tres listas. La primera contiene 4 números, la segunda contiene 5 letras y en la tercera le cargamos como elementos
#las dos listas anteriores.¿Cuántos elementos contendrá la tercera lista? Demostrar mediante un breve código.
lista=[1,2,3,4]
lista2=["a","b","c","d","e"]
lista3=[]
lista3.append(lista)
lista3.append(lista2)
contador=[]
for item in range(0,len(lista3)):
contador+=lista3[item]#agregamos al array contador todo el array lista3 para que sean uno solo
print("la lista tiene",len(contador),"elementos")
| false |
17a1fa1c53824f892f523f06160cee41953df98a | maxigarrett/cursoPYTHON | /2-clase2/matrices.py | 858 | 4.21875 | 4 | #MATRICES
linea1=[1,2,3]
linea2=[4,5,6]
linea3=[7,8,9]
matriz=[linea1,linea2,linea3]
print(matriz)
print(matriz[0][0])#saldra el 1 porque esta en la fila 0 colmna 0
print(matriz[1][2])
#---------------------------------------------------------
print()
print()
#recorremos la matriz
linea4=[1,2,3]
linea5=[4,5,6]
linea6=[7,8,9]
matriz=[linea4,linea5,linea6]
#esto va a ir a los for para recorrer la matriz tambien lo podemos almacenar en una variable
print(len(matriz))
print(len(matriz[0]))#mostra toda la fila 0 por lo que sabremos la cantidad de columnas que hay que son 3 con metodo len lo sabemos
for fila in range(0,len(matriz)):
for columnas in range(0,len(matriz[0])):
print(matriz[fila][columnas],end=',')#evitamos salto de lineas con end
print("\n")
# ------------------------------------------------------------
| false |
190877074a762c382a91ba6ffb7e6f4bac1d5992 | ryumaggs/ryumaggs.github.io | /downloads/vert.py | 290 | 4.40625 | 4 | # This program asks for user input and prints each word on a separate line
user_input = input("Please enter a string: ")
words = user_input.split()
for i in words:
print(i)
# Another way of doing the same thing is the following:
#
# for i in range(len(words)):
# print(words[i])
| true |
1ed9f880d797ed321a299d12d09fffcd87c50cd7 | Hamzakhalidcs/Flask-App | /snippets/recursive.py | 346 | 4.375 | 4 | """
This is a recursive function to find the factorial of an integer,
Recursive function means a defined function can call it self until the condition is satisfied """
def factorial(x):
if x == 1:
return 1
else:
return(x * factorial(x-1))
num = 8
print("The factorial of the",num, "is", factorial(num))
| true |
4220904749d4fb459718c1d088ce7a555e39b192 | shaahkar/Projects | /Numbers/mortgage/mortgage.py | 712 | 4.15625 | 4 | # Kristopher Newsome
# krisnewsome@gmail.com
# 20130915
#
# Calculate the monthly payments of a fixed term mortgage over given Nth terms at a given percent rate. Also figure out how long it will take the user to pay back the loan.
def calcMortgage(P, i, n):
'''
Calculate the monthly payments of a fixed term mortgage over given Nth terms at a given percent rate.
params: P = principal, i = percent, n = years
returns Monthy payment
'''
return P * ((i/100.0/12.0) / (1 - (1 + (i/100.0/12.0)) ** (-n*12)))
if __name__ == '__main__':
P = int(raw_input("Principal amount: "))
i = float(raw_input("Interest rate: "))
n = float(raw_input("Years to repay: "))
print "Your monthly payment will be $%.2f." % calcMortgage(P, i, n)
| true |
618a3334d73325d07c3ade65097b3dbc87deaa47 | KonstantinMyachin/HSEPython | /ru/myachin/lesson/second/main.py | 1,650 | 4.21875 | 4 | # array and iterator
numbers = [7, 8, 12, 765, 3, 8, 65.7]
result = 0
for number in numbers:
result += number
print(result)
# split function
some_str = "this is a test"
words = some_str.split()
print(words)
another_str = "Hello, world! This is a test!"
sentences = another_str.split("!")
print(sentences)
# join function
words = ["hello", "world", "test"]
line = ", ".join(words)
print(line)
# range function
for i in range(5):
print("Hello!")
print("i = ", i)
range_list = list(range(5))
print(range_list)
range_list = list(range(2, 5))
print(range_list)
range_list = list(range(2, 18, 3))
print(range_list)
# part of array
my_list = [0, 10, 20, 30, 40, 50]
print(my_list[2:4])
print(my_list[1:5:2])
print(my_list[::-1])
# creating array of integers from array of strings
numbers_as_str = ['7', '12', '3', '45']
# создать список, в котором эти числа записаны как числа
numbers_as_int = []
for number in numbers_as_str:
numbers_as_int.append(int(number))
print(numbers_as_int)
# type of value
print(type(3.))
# unmodified list (tuple)
my_tuple = (6, 12, "12")
print(my_tuple)
print(my_tuple[1])
# error
# my_tuple[1] = 1
pairs = [(1, 6), (8, 3), (2, 5), (7, 3)]
print(pairs)
print(pairs[2])
for a, b in pairs:
print("a = ", a)
print("b = ", b)
print("Next item")
# for loop with indexes (enumerate function)
some_list = ["Hello", "world", "test"]
for i, element in enumerate(some_list):
print("word", element, "position", i)
print(list(enumerate(some_list)))
numbers = [3, 8, 9, 12]
for i, x in enumerate(numbers):
numbers[i] = x + 1
print(numbers)
| true |
b3adc2790d24b8c24f873cf09cfb79e3cbcc124c | LarsenClose/python-algorithms | /algorithms/bubble_sort_recur.py | 761 | 4.1875 | 4 | """
Bubble sort recursive
- Time complexity of O(n^2)
- Space complexity of O(n) (due to call the call stack)
- No presorted exit
"""
def bubble_sort(to_sort):
if not to_sort:
return to_sort
try:
index = len(to_sort)
except TypeError:
return to_sort
return _bubble_sort(to_sort, index)
def _bubble_sort(to_sort, index):
if index == 1:
return to_sort
for item in range(0, index - 1):
if to_sort[item] > to_sort[item + 1]:
to_sort[item], to_sort[item + 1] = \
to_sort[item + 1], to_sort[item]
return _bubble_sort(to_sort, index - 1)
if __name__ == '__main__':
my_list = [9, 4, 1, 7, 3, 0, 6, 8, 2, 5]
print(bubble_sort(my_list))
| true |
5e84c1329cd955820bb5e7fee50b4b26d52e14df | andymel77/gb_base_python | /lesson5/task_3.py | 930 | 4.125 | 4 | """
3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников.
"""
from functools import reduce
def middle_salary(pr_el, el):
return pr_el + el
salary = {}
with open('my_file_task3.txt', 'r', encoding='utf-8') as file:
salary = {line.split()[0]: float(line.split()[1]) for line in file.readlines() if float(line.split()[1]) < 20000}
for key, val in salary.items():
print(f'Employee {key} has salary: {val}')
print(f'Middle salary is {reduce(middle_salary, salary.values())/len(salary.values())}')
| false |
d8b822f07a451229675f9f01a9f2c9acaa10e833 | kssanthosh-ges/sample-git-repo | /calculator.py | 487 | 4.25 | 4 | """
This file to get the basic math operation on the given inputs to it
"""
def add(n1,n2):
"""takes two number arguments and returns the addition of them"""
return n1+n2
def sub(n1,n2):
"""takes two number arguments and returns the subtraction of them"""
if n1>n2:
return n1-n2
return n2-n1
def mul(n1,n2):
"""takes two number arguments and returns the multiplication of them"""
return n1*n2
def div(n1,n2):
pass
def mod(n1,n2):
pass
| true |
a7ab6551f53c0a128eaa827ba9d27c68cd7e80ca | Sorabh-Singh/HackerRank | /Python Projects/Dice Roll Simulator.py | 1,134 | 4.625 | 5 | import random
Approach 1:
roll_again = 'yes'
# while roll_again != "end" or roll_again != "quit":
while roll_again == "yes" or roll_again == "y":
print("rollling the dice...")
print("Values are : ")
print(random.randint(1, 6))
print(random.randint(1, 6))
roll_again = input(
"Enter yes or y for rolling dice again, any other key will terminate the loop! : ")
# print("user provided input", roll_again)
print("Thanks for your participation")
Approach: 2
# importing module for random number generation
# range of the values of a dice
min_val = 1
max_val = 6
# to loop the rolling through user input
roll_again = "yes"
# loop
while roll_again == "yes" or roll_again == "y":
print("Rolling The Dices...")
print("The Values are :")
# generating and printing 1st random integer from 1 to 6
print(random.randint(min_val, max_val))
# generating and printing 2nd random integer from 1 to 6
print(random.randint(min_val, max_val))
# asking user to roll the dice again. Any input other than yes or y will terminate the loop
roll_again = input("Roll the Dices Again?")
| true |
562c9268b8923b78046e31eba81cad3db52e6ca0 | Sorabh-Singh/HackerRank | /Hackerrank problems/Word Order.py | 671 | 4.21875 | 4 | """
Input Format
The first line contains the integer, .
The next lines each contain a word.
Output Format
Output lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
Sample Input
4
bcdef
abcdefg
bcde
bcdef
Sample Output
3
2 1 1
"""
from collections import Counter
words = Counter([input() for _ in range(int(input()))])
print(len(words))
for keys, values in words.items():
print(values, end=' ')
# second approach:
words = Counter([input() for _ in range(int(input()))])
print(len(words))
print(*words.values())
| true |
db55801d768ae4d160ee1abfc0369a139f0e9cac | pavanmsvs/hackeru-python | /prime.py | 329 | 4.21875 | 4 | num = int(input("Enter a number greater than 1 \n"))
if (num==1):
print("Please Enter a number greater than 1")
else:
for i in range(2,num):
if(num%i==0):
print("The number",num,"not a prime number")
break
else:
print("The number",num, "is a prime number")
| true |
50d4a71aadc4019fbf23a975642c9b543b563adf | pavanmsvs/hackeru-python | /elif.py | 341 | 4.125 | 4 | name = input("What is your name? \n")
if (name.lower() == "alice"):
print("Hi Alice")
else:
age = int(input("what is your age"))
if age <= 12:
print("You are not Alice Kiddo")
elif 100<age<=2000:
print("You are not Alice grannie")
elif age>2000:
print("Unlike you Alice is not undead vampire")
| false |
8f2159bbc23be302f6e874ff69c5301791c472a4 | Cobrettie/intro-python-i | /src/05_lists.py | 1,683 | 4.15625 | 4 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
print(x.append(4))
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# YOUR CODE HERE
print(x.extend(y))
# Change x so that it is [1, 2, 3, 4, 9, 10]
# YOUR CODE HERE
print(x.remove(8))
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
# YOUR CODE HERE
print(x.insert(5, 99))
# Print the length of list x
# YOUR CODE HERE
print("length of x: ", len(x))
# Print all the values in x multiplied by 1000
# YOUR CODE HERE
for n in x:
print("n * 1000: ", n * 1000)
z = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40 ,41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
]
# Print the first element from each nested list in the matrix z
# YOUR CODE HERE
for n in z:
print("First el from each nested list: ", n[0])
# Print all of the elements that lie on the left-to-right
# diagonal of matrix z
# YOUR CODE HERE
# what if we also want the index of the element?
# enumerate gives us access to each list element and its index
for index, elem in enumerate(y):
print(f"element {index} is {elem}")
# how to loop certain number of times
# range() 'start, stop, increment by' | true |
d4b6cecaed8c11632c783b87fd2b59f72369de06 | jahanvisharma-dotcom/String-Reversing | /Reverse using RECURSION.py | 264 | 4.3125 | 4 | #REVERSE A STRING USING LIST REVERSE
def reverse_string(j):
if len(j) == 0:
return j
else:
return reverse_string(j[1:]) + j[0]
input_string = 'JAHANVI'
print("reverse of string using recursion is : ",reverse_string(input_string))
| true |
35b296ad8b4f14c8080e9748343f3902a35fcd0e | tazuddinleton/basic_algorithms_and_data_structures | /string_manipulation/palindrom.py | 369 | 4.125 | 4 | def reverse(str):
reverse = ""
l = len(str)
while(l > 0):
l -= 1
reverse += str[l]
return reverse
def is_palindrom(str):
if(str == reverse(str)):
return True
return False
string = 'RACECAR'
string1 = 'KUALALAMPUR'
string2 = '1991'
print(is_palindrom(string))
print(is_palindrom(string1))
print(is_palindrom(string2))
| false |
f993e3b5fb115450f780e5412a64f240b4667778 | pooja1506/AutomateTheBoringStuff_2e | /chapter2/continue_break_statements.py | 429 | 4.15625 | 4 | while True:
print("who are you?")
name = input()
if name != 'Joe':
continue
print("hello joe , please enter your password")
password = input()
if password == 'Seasword':
break
print("access granted")
#continue statement is used to jump back to the start of the loop to re-evaluate the input until its true
#break statement is used to immediately exit the while loop clause | true |
f2448bbb78ebd231ef3f846d46337b0a2d109c27 | tanle8/py3p | /4-Python_Classes_Inheritance/assignment1-Bike.py | 628 | 4.125 | 4 | """Define a class called Bike that accepts a string and a float as input, and assigns those inputs respectively to
two instance variables, color and price. Assign to the variable testOne an instance of Bike whose color is blue and
whose price is 89.99. Assign to the variable testTwo an instance of Bike whose color is purple and whose price is
25.0. """
class Bike:
def __init__(self, c, p):
self.color = c
self.price = p
def __str__(self):
return "Bike: {} and {}".format(self.color, self.price)
testOne = Bike('blue', 89.99)
testTwo = Bike('purple', 25.0)
print(testOne)
print(testTwo) | true |
c3e27cf32202894925034f3b2410016bca0beb35 | mo7amed3del/The-Anagram-strings | /The Anagram strings.py | 834 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#this function is checking if the string is in english language # stack over flow link (https://stackoverflow.com/questions/27084617/detect-strings-with-non-english-characters-in-python)
def isEnglish(s):
try:
s.encode(encoding='utf-8').decode('ascii')
except UnicodeDecodeError:
return False
else:
return True
# In[4]:
def compare(s,t):
assert len(s) >= 1,"S should not be empty"
assert len(t) <= 5*10**4, "T's length should not smaller than 5x10^4"
assert s.islower() and t.islower(), "S and T should be lower case"
assert isEnglish(s) and isEnglish(t) , "input must be in english"
#return true if t is an anagram of s
return sorted(s)== sorted(t)
print(compare(s = "rat", t = "car"))
# In[ ]:
| true |
b356977397b6c324ff9285230cc1b1477f10b945 | hatien85212/Python | /Pycharm/try_except.py | 848 | 4.3125 | 4 | """Exceptions: https://www.w3schools.com/python/python_try_except.asp
NameError: occur when a variable is not defined
try...except: handle the error...else: if no errors were raised
try...except...final: lets you execute code: will be executed regardless if the try block raises an error or not.
"""
import os
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")# run if no error
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished") #always to execute regarless errors were raised or not
try:
f = open("file.txt","r")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close() | true |
e4c7add82b8a29d7effaaee4219652769aff60a5 | DanBarredo/rock-paper-scissors | /rock_paper_scissors.py | 1,865 | 4.34375 | 4 | import random
# convert int choice to strings
def choice_to_string(choice):
if (choice > 3 or choice < 1):
choice = int(input("Enter a valid input!! rock (1), paper (2), scissors(3): "))
return choice_to_string(choice)
elif (choice == 1):
return "rock"
elif (choice == 2):
return "paper"
else:
return "scissors"
# decide who wins between user and computer
def decide_winner(player, comp):
if (player == comp):
print("draw..")
return "draw"
elif ((player == 1 and comp == 2) or (player == 2 and comp == 1)):
print("Paper beats rock..")
return "paper"
elif ((player == 1 and comp == 3) or (player == 3 and comp ==1)):
print("Rock beats scissors..")
return "rock"
else:
print("Scissors beats paper..")
return "scissors"
# Main game loop
if __name__ == "__main__":
while True:
# player input
print("Play rock, paper, scissors with the computer..")
player_input = int(input("rock (1), paper (2), scissors(3)?"))
player_choice = choice_to_string(player_input)
# comp input
comp_input = random.randint(1, 3)
comp_choice = choice_to_string(comp_input)
# print player and comp choices
print(f"You chose {player_choice}")
print(f"pc choice {comp_choice}")
# decide winner of the game
result = decide_winner(player_input, comp_input)
if (result == player_choice):
print(" YOU WIN!!")
elif (player_choice == comp_choice):
print(" IT'S A DRAW!!")
else:
print(" COMPUTER WINS!!")
# play again
ans = input("Play again? (Y/N):")
if (ans == "n" or ans == "N"):
print("thanks for playing")
break
| true |
75ac828a02b11cf4ab7a9860842e5e8739729269 | saivadkapur/AutomationProject1 | /argument_types.py | 1,067 | 4.40625 | 4 | #DIFFERENT TYPES OG ARGUMENTS
#1. Required arguments
def sum(a,b):
print("sum of the two numbers = " + str (a+b))
#2.Keyword arguments - you sepcify the argument values while calling the function
def sumInput(a,b):
print("sum of the two numbers = " + str (a+b))
#3.Default arguments - used to fix one or arguments with a default value like b=40 in the below function
#Important thing to remeber using default value as an argument if want to have another argument in the function after
#default value argument that value should also have a default value
#Example: def defaultArg(a=10, b) ***Function throws error since next value after default shouls als have a default value
#Example2: def defArg(a, b=12, c=10) Function gets executed since argument C also has a default value
def sumDefaultArg(a,b=40):
print("sum of the two numbers = " + str (a+b))
#1
sum(10, 20) #sum of the two numbers = 30
#2
sumInput(b=30, a=20) #sum of the two numbers = 50
#3
sumDefaultArg(15) #sum of the two numbers = 55
sumDefaultArg(25,55) #sum of the two numbers = 80
| true |
c20083a2f85df12671d00323db4d7b095534bea4 | inclu-media/python-primer | /control.py | 803 | 4.21875 | 4 | # coding: utf-8
# Control structures
####################
is_sunny = True # or False
print("Hi there!")
if is_sunny:
print("What a lovely day!")
# Control structures: 2 alternatives
####################################
is_sunny = False
print("Hi there!")
if is_sunny:
print("What a lovely day!")
else:
print("WTF ... !")
# Control structures: n alternatives
#######################################
name = raw_input("Enter your name: ")
if name == "Martin":
print("Welcome in!")
elif name == "Matej":
print("You are welcome too!")
else:
print("I'm not going to let you in!")
'''
Things to note:
- the condition must evaluate to True or False
- the condition does not need to be a boolean variable
- the condition can be a comparison operation
!! '=' assigns, '==' compares
''' | true |
55bbf6065341eb62c3b931a8bf311002afafc214 | Anu1996rag/Algorithms | /bubble_sort_2.py | 738 | 4.125 | 4 | def bubble_sort(arr, key=None):
n = len(arr)
for i in range(0, n - 1):
swapped = False
for j in range(0, n - i - 1):
a = arr[j][key]
b = arr[j+1][key]
if a > b:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
elements = [
{'name': 'mona', 'transaction_amount': 1000, 'device': 'iphone-10'},
{'name': 'dhaval', 'transaction_amount': 400, 'device': 'google pixel'},
{'name': 'kathy', 'transaction_amount': 200, 'device': 'vivo'},
{'name': 'aamir', 'transaction_amount': 800, 'device': 'iphone-8'},
]
bubble_sort(elements, key='transaction_amount')
print(elements)
| false |
0c0d42f0277ae21e99bce2529751e39d2c640254 | Anu1996rag/Algorithms | /linked_lists/merge_linked_list.py | 1,827 | 4.15625 | 4 | """ Merging two sorted linked lists
l1 = 1->2->3
l2 = 1->3->5
output = 1->1->2->3->3->5
"""
class Node:
def __init__(self, data, ref=None):
self.data = data
self.next = ref
class LinkedList:
# to initialize linked list object
def __init__(self):
self.head = None
# add node at the end of the list
def insert_at_end(self, new_data):
new_node = Node(new_data)
# check if the head exists, if not make the new node as the head
if self.head is None:
self.head = new_node
return
# else traverse till the end of the list
last = self.head
while last.next:
last = last.next
# change the next of the last node
last.next = new_node
# inserting the list of values
def insert_values(self, list_of_values):
for value in list_of_values:
self.insert_at_end(value)
# printing out list of nodes
def print_list(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
@staticmethod
def merge_sorted_linked_lists(l1, l2):
dummy_head = tail = Node(0)
# checking for the edge cases
if l1 is None:
return l2
if l2 is None:
return l1
while l1 and l2:
if l1.data < l2.data:
tail.next, l1 = l1, l1.next
else:
tail.next, l2 = l2, l2.next
tail = tail.next
# append the remaining elements
tail.next = l1 or l2
return dummy_head.next
l1 = LinkedList()
l2 = LinkedList()
l3 = LinkedList()
# insert values
l1.insert_values([1,2,3])
l2.insert_values([1,3,5])
l3.head = LinkedList.merge_sorted_linked_lists(l1.head,l2.head)
l3.print_list()
| true |
540807717440a17e64e869bf60b284729f9e5dad | Anu1996rag/Algorithms | /stacks/stack_1.py | 694 | 4.21875 | 4 | """ Implementing stack operations using list
Time Complexity O(n)
"""
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def push(self, data):
return self.stack.append(data)
def pop(self):
try:
return self.stack.pop()
except IndexError:
return "Stack is empty"
def print_stack(self):
return [data for data in self.stack]
if __name__ == "__main__":
stack = Stack()
list_of_values = [1, 2, 3, 4, 5]
for value in list_of_values:
stack.push(value)
print(stack.print_stack())
stack.pop()
print(stack.print_stack())
| true |
da4c65269fb7f38b1cec12f0e19a80f4ceec18f5 | mariabernard/GABI_2021_initiation_python | /init/init_correction.py | 1,942 | 4.40625 | 4 | #!/usr/bin/env python3
# simple addition
print(1 + 2)
# 2 cubed
print(2**3)
# simple division
print(17/3)
# concatenation
print("Hello" + " World!")
###################################
# variables are defined by
# - a name
# - a value
# - a type
# remember, print() function is needed in script not in the Console
PRENOM = "Maria"
print(PRENOM)
# print Maria
print(type(PRENOM))
# print <class 'str'>
AGE=35
print(AGE)
# print 35
print(type(AGE))
# print <class 'int'>
####################################
# List and Dictionnary
SOME_LIST = ["Pierre",44,True]
print(SOME_LIST[0])
# print Pierre
print(SOME_LIST[-1])
# print True
print(SOME_LIST[1:3])
# print [44,True]
print(type(SOME_LIST[1:3]))
# print <class 'list'>
SOME_DICT = {"prenoms" : ["Pierre", "Paul", "Jacques"], "age":44, "est_permanent" : True}
print(SOME_DICT["prenoms"])
# print ["Pierre", "Paul", "Jacques"]
print(type(SOME_DICT["prenoms"]))
# print <class 'list'>
print(SOME_DICT.keys())
# print dict_keys(['prenoms','age','est_permanent'])
print(SOME_DICT.values())
# print dict_values([['Pierre', 'Paul', 'Jacques'], 44, True])
####################################
# parse list (or dict) using for loop
# on a list
SCORES = [1, 0.5, 0.2]
for score in SCORES:
print(score)
print(type(score))
# 1
# 0.5
# 0.2
# on a Dictionnary
RH_dict = {
'Matricule1':'Maria Bernard',
'Matricule2':'Mathieu Charles'
}
for matricule in RH_dict:
print(matricule + ' est ' + RH_dict[matricule])
# Matricule1 est Maria Bernard
# Matricule2 est Mathieu Charles
####################################
# how to express tests
score = 14
if score < 10:
print("peut mieux faire")
elif score < 20:
print("bien")
elif score == 20:
print("parfait")
else:
print("absent")
# bien
SCORES = [6, 11, 15, 20, -1]
for score in SCORES:
if score < 10:
print("peut mieux faire")
elif score < 20:
print("bien")
elif score == 20:
print("parfait")
else:
print("absent")
| true |
1478bc5469830912effbd4ad07ba476eda71ec25 | EricNguyen1213/Program-Assignments | /HtHTeacherFiles/Program3.py | 498 | 4.15625 | 4 | myDict = {"Apple":3, "Banana": 5, "Carrot": 2}
myList = [2,5,6,8]
myTuple = (0,1,2)
mySet = {"Dog", "Cat", "Rat"}
print(myDict["Apple"], myList[-1], myTuple[0])
myDict["Apple"] = 0
del myDict["Carrot"]
myDict["Cantelope"] = 3
myList[3] = 2
myList = myList[1:3]
myList.append(3)
myList.extend(newList)
myList.insert(3,"whoa")
print(myList)
myList.pop(-2)
print(myList.pop(-2))
myList.remove("whoa")
myList.remove(2)
myList.clear()
print(myList)
tupleEntry = myTuple[2]
print(tupleEntry)
| false |
1da906c463b54d8f547e3a99e30748fc4ebb77f9 | MischaGithub/PythonExercises | /Blended1.py | 1,295 | 4.15625 | 4 | def hotel_cost(nights):
#Calculating the hotel cost per stay
hotel_cost = nights * 140
return hotel_cost
def plane_ride_cost(city):
#Calculating the plane ride cost depending on location
if city == "Cape Town":
return 2500
if city == "Durban":
return 2300
if city == "JHB":
return 2000
if city == "BFN":
return "Sorry select only FLIGHTS between Cape Town, Durban, JHB"
def rental_car_cost(days):
#Calculating the cost per day for the rental car
cost = days * 40
if days >= 7:
cost -= 50
return "Cost to rent car:" + str(cost)
elif days >= 3 and days <= 6:
cost -= 20
return cost
def trip_cost(city, days, spending_money):
#Calculating the trip cost with all its attributes
return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days) + spending_money
Hotel_charge = int(input("Enter nights to stay: \n"))
print("This is the cost to stay in hotel: ", hotel_cost(Hotel_charge))
Plane_cost = str(input("Enter the city you travelling to: \n"))
print("The plane ride cost is:",plane_ride_cost(Plane_cost))
Daily_rental = int(input("Enter days required for rental car: \n"))
print("Daily cost for rental car is:", rental_car_cost(Daily_rental))
| true |
e1dd9e6fcc10aa5d9aee2385abc873440a86ec07 | Pickausername2017/cti110 | /M3HW1DBruce.py | 648 | 4.3125 | 4 | # CTI-110
# M3HW1 - Age Classifier
# Denise Bruce
# 24 Sept 2017
# This program classifies people based on age.
#
# These are the variables for age ranges.
#Infants 0 - 1 years old
#Child 2 - 12 years old
# Teen 13-18 years old
# Adult 20 + Years old
def main():
class_1 = 1
class_2 = 12
class_3 = 19
class_4 =20
age = int (input('Enter age'))
if age <= class_1:
print ('Class is Infant')
elif age <= class_2:
print ('Class is Child')
elif age <= class_3:
print ('Class is Teen')
elif age >= class_4:
print('Class is Adult')
main()
# Start program
| false |
e6e7ea6648442553ee31dfae69651acdf91aaf13 | mlobf/oopGregory | /oop.py | 741 | 4.375 | 4 | """
classe
objetos
construtor
metodos
atributos
herança
sobrecarga
poliformismo
destrutores
herança
"""
"""
Quando vc desenha a planta de uma casa isso nao quer dizer que ela existe
Isso e uma classe.
"""
# Toda classe do Python vai herdar no minimo de Object.
# O objecto e a concretizaçao de uma classe.
# Vou criar realmente na memoria no pc uma "pessoal" oriunda da classe.
# Atributos de uma classe sao os 'adjetivos desta. No caso de uma Classe pessoa
# temos como possiveis atributos, nome, idade, sexo.
class Casa(object):
cor = "Amarela"
altura = 3
quartos = 10
# Vou criar um objeto.
minha_casa = Casa() # Agora a classe foi instanciada. Ela passou a existir.
print(minha_casa.cor, str(minha_casa.altura))
| false |
78e920c6bde39a955ed60f2091e3ea2c4cc0113d | kevinsung123/Python | /boj/dict_sort.py | 2,549 | 4.34375 | 4 | def main():
# Dictionary of strings and ints
wordsFreqDict = {
"hello": 56,
"at": 23,
"test": 43,
"teaa": 46,
"this": 43
}
'''
sort dictionary elements by key
'''
print("**** Sort Dictionary by Key *******")
'''
Iterate over a sorted list of keys and select value from dictionary for each key
and print the key value pairs in sorted order of keys
'''
print(wordsFreqDict.keys())
for key in sorted(wordsFreqDict.keys()):
print(key, " :: ", wordsFreqDict[key])
print("***************")
'''
Iterate over a list of tuple i.e. key / value pairs, sorted by default 0th index i.e. key
and print the key value pairs in sorted order of keys
'''
print(wordsFreqDict.items())
for elem in sorted(wordsFreqDict.items()):
print(elem[0], " ::", elem[1])
print("***************")
# Print the sorted key value pairs of dictionary using list comprehension
[print(key, " :: ", value) for (key, value) in sorted(wordsFreqDict.items())]
print("***************")
print("Sort dictionary contents by value in reverse Order")
'''
Iterate over the list of tuples sorted by 0th index i.e. value in reverse order
'''
for elem in sorted(wordsFreqDict.items(), reverse=True):
print(elem[0], " ::", elem[1])
print("***************")
print("Sort by Key using Custom Comparator : Sort by length of key string")
listofTuples = sorted(wordsFreqDict.items(), key=lambda x: len(x[0]))
for elem in listofTuples:
print(elem[0], " ::", elem[1])
'''
Sort dictionary elements by value
'''
print("**** SORT BY VALUE *******")
# Create a list of tuples sorted by index 1 i.e. value field
listofTuples = sorted(wordsFreqDict.items(), key=lambda x: x[1])
# Iterate over the sorted sequence
for elem in listofTuples:
print(elem[0], " ::", elem[1])
print("*************************")
# Use List comprehension to print the contents of dictionary , sorted by value
[print(key, " :: ", value) for (key, value) in sorted(wordsFreqDict.items(), key=lambda x: x[1])]
print("**** SORT BY VALUE In Reverse Order *******")
# Create a list of tuples sorted by index 1 i.e. value field
listofTuples = sorted(wordsFreqDict.items(), reverse=True, key=lambda x: x[1])
# Iterate over the sorted sequence
for elem in listofTuples:
print(elem[0], " ::", elem[1])
if __name__ == '__main__':
main()
| true |
f7b871c1fbaa3494e2a8214c365f8b24c40bd7ef | ZF-1000/GIT-repository_Leet_Code | /657. Robot Return to Origin.py | 1,871 | 4.21875 | 4 | """
There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves,
judge if this robot ends up at (0, 0) after it completes its moves.
You are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move.
Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).
Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.
Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to the right once,
'L' will always make it move left, etc.
Also, assume that the magnitude of the robot's movement is the same for each move.
Example 1:
Input: moves = "UD"
Output: true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude,
so it ended up at the origin where it started. Therefore, we return true.
Example 2:
Input: moves = "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin.
We return false because it is not at the origin at the end of its moves.
Example 3:
Input: moves = "RRDD"
Output: false
Example 4:
Input: moves = "LDRRLRUULR"
Output: false
Constraints:
1 <= moves.length <= 2 * 104
moves only contains the characters 'U', 'D', 'L' and 'R'.
"""
class Solution:
def judgeCircle(self, moves: str) -> bool:
moves = moves + "LURD"
d = {}
for move in moves:
if move not in d:
d[move] = 0
d[move] += 1
# print(d)
if d['L'] - d['R'] == 0 and d['U'] - d['D'] == 0:
return True
else:
return False
arr = ["UD", "LL", "RRDD", "LDRRLRUULR"]
sol = Solution()
for el in arr:
print(sol.judgeCircle(el))
| true |
678806cc3485f7c7e2b0c8354018d63464feff16 | ZF-1000/GIT-repository_Leet_Code | /350. Intersection of Two Arrays II.py | 1,387 | 4.15625 | 4 | """
Given two integer arrays nums1 and nums2, return an array of their intersection.
Each element in the result must appear as many times as it shows in both arrays and
you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that
you cannot load all elements into the memory at once?
"""
from typing import List
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
for el in nums1:
j = 0
while j < len(nums2):
if el == nums2[j]:
res.append(el)
nums2.remove(nums2[j])
break
j += 1
return res
# arr = [[]]
arr = [[[1, 2, 2, 1], [2, 2]], [[4, 9, 5], [9, 4, 9, 8, 4]]]
sol = Solution()
for el in arr:
print(sol.intersect(el[0], el[1]))
| true |
8c4fcbe1cd6b78fce4d1924749545b4d222c3622 | ZF-1000/GIT-repository_Leet_Code | /020. Valid Parentheses.py | 1,104 | 4.15625 | 4 | """
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
"""
class Solution:
def isValid(self, s: str) -> bool:
len_s = 1
len_s1 = 2
while len_s != len_s1:
len_s = len(s)
s = s.replace('()', '')
s = s.replace('[]', '')
s = s.replace('{}', '')
len_s1 = len(s)
if not s:
return (True)
else:
return (False)
sol = Solution()
arr_s = ["()", "()[]{}", "(]", "([)]", "{[]}"]
for s in arr_s:
print(sol.isValid(s))
| true |
472eaafc7053c53b885b809abc4ab08499bff066 | ZF-1000/GIT-repository_Leet_Code | /035. Search Insert Position.py | 1,134 | 4.28125 | 4 | """
Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Example 4:
Input: nums = [1,3,5,6], target = 0
Output: 0
Example 5:
Input: nums = [1], target = 0
Output: 0
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums contains distinct values sorted in ascending order.
-104 <= target <= 104
"""
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
i = 0
while i < len(nums) and nums[i] < target:
i += 1
return i
# arr = [[[1], 0]]
arr = [[[1, 3, 5, 6], 5], [[1, 3, 5, 6], 2], [[1, 3, 5, 6], 7], [[1, 3, 5, 6], 0], [[1], 0], [[0], 9]]
sol = Solution()
for el in arr:
print(sol.searchInsert(el[0], el[1]))
| true |
64c4aeb45c047730e46dd220b0485c5557a84829 | ZF-1000/GIT-repository_Leet_Code | /575. Distribute Candies.py | 1,655 | 4.46875 | 4 | """
Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight,
so she visited a doctor.
The doctor advised Alice to only eat n / 2 of the candies she has (n is always even).
Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still
following the doctor's advice.
Given the integer array candyType of length n, return the maximum number of different types of candies
she can eat if she only eats n / 2 of them.
Example 1:
Input: candyType = [1,1,2,2,3,3]
Output: 3
Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
Example 2:
Input: candyType = [1,1,2,3]
Output: 2
Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3],
she still can only eat 2 different types.
Example 3:
Input: candyType = [6,6,6,6]
Output: 1
Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
Constraints:
n == candyType.length
2 <= n <= 104
n is even.
-105 <= candyType[i] <= 105
"""
from typing import List
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
len_candyType = len(candyType)
set_candyType = set(candyType)
if int(len_candyType / 2) > len(set_candyType):
return len(set_candyType)
else:
return int(len_candyType / 2)
arr = [[1, 1, 2, 2, 3, 3], [1, 1, 2, 3], [6, 6, 6, 6]]
sol = Solution()
for el in arr:
print(sol.distributeCandies(el))
| true |
c7822fa36902ee6a1f23e446bf3e208c18b0aebd | ajbaldini/code_practice | /string_questions/check_anagrams.py | 460 | 4.21875 | 4 | """
How do you check if two strings are anagrams of each other?
"""
def check_anagram(wordOne, wordTwo):
one = list(wordOne)
two = list(wordTwo)
one.sort()
two.sort()
if one == two:
print(''.join(wordOne) + " and " + ''.join(wordTwo) + " are anagrams")
else:
print(''.join(wordOne) + " and " + ''.join(wordTwo) + " are not anagrams")
print(check_anagram('listen','silent'))
print(check_anagram('listens', 'silent'))
| false |
07422a2955264e2f87813bca43936053b8f02e8a | ajbaldini/code_practice | /array_questions/find_all_pairs_matching_sum.py | 309 | 4.3125 | 4 | """
How do you find all pairs of an integer array whose sum is equal to a given number?
"""
def find_pairs(numbers, sum):
for i in numbers:
for x in numbers:
if i + x == sum:
print (f"{i} and {x} equal {sum}")
numbers = [1,2,3,4,5,6,7,8,9,10]
find_pairs(numbers, 13) | true |
4330d4a0587356e019faaa9830c35906946c880e | valuntiny/leetcode_string_ii | /setZeroes_re.py | 1,872 | 4.28125 | 4 | '''
Quest:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Solution:
use the first column and row as index
but keep in mind that you need a special flag to let you know whether the first col originally contains 0 or not
'''
class Solution:
def setZeroes(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
col_zero = False
row_zero = False
if not matrix:
return None
m, n = len(matrix), len(matrix[0])
for j in range(n):
if matrix[0][j] == 0:
row_zero = True
for i in range(m):
if matrix[i][0] == 0:
col_zero = True
for j in range(n):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
for i in range(m-1, 0, -1):
for j in range(n-1, 0, -1):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if col_zero:
for i in range(m):
matrix[i][0] = 0
if row_zero:
for j in range(n):
matrix[0][j] = 0
test = Solution()
x = [
[1,1,1],
[1,0,1],
[1,1,1]
]
test.setZeroes(x)
print(x) | true |
a13c3e5b093a0cfe96c4208c6696393114c12f8a | NdagiStanley/dsa | /easy/tile_wall.py | 2,192 | 4.46875 | 4 | """
This problem was asked by Google.
You are given an M by N matrix consisting of booleans that represents a board.
Each True boolean represents a wall. Each False boolean represents a tile you can walk on.
Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps
required to reach the end coordinate from the start. If there is no possible path, then return null.
You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the
edges of the board.
For example, given the following board:
[[f, f, f, f],
[t, t, f, t],
[f, f, f, f],
[f, f, f, f]]
and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of steps required
to reach the end is 7, since we would need to go through (1, 2) because there is a wall everywhere
else on the second row.
"""
# Ref: https://www.geeksforgeeks.org/shortest-distance-two-cells-matrix-grid/
# Python code to find number of unique paths in a
# matrix with obstacles.
def uniquePathsWithObstacles(A):
# create a 2D-matrix and initializing with value 0
paths = [[0] * len(A[0]) for i in A]
# print(paths)
# initializing the left corner if no obstacle there
if A[0][0] == 0:
paths[0][0] = 1
# initializing first column of the 2D matrix
for i in range(1, len(A)):
if A[i][0] == 0:
# If not obstacle
paths[i][0] = paths[i - 1][0]
# initializing first row of the 2D matrix
for j in range(1, len(A[0])):
if A[0][j] == 0:
# If not obstacle
paths[0][j] = paths[0][j-1]
for i in range(1, len(A)):
for j in range(1, len(A[0])):
# If current cell is not obstacle
if A[i][j] == 0:
paths[i][j] = paths[i - 1][j] + paths[i][j - 1]
# returning the corner value of the matrix
return paths[-1][-1]
# Driver Code
A = [[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]
print(uniquePathsWithObstacles(A))
# B = [[f, f, f, f],
# [t, t, f, t],
# [f, f, f, f],
# [f, f, f, f]]
B = [[0, 0, 0, 0],
[1, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
print(uniquePathsWithObstacles(B))
| true |
1d8851a8ce0727c454644a249eeb0d358d51f43e | shubhamjanhere/Basic-Python-Programs | /Basic Python/exception_handling.py | 1,259 | 4.1875 | 4 | try:
2 + 's'
except TypeError:
print "There was a type Error"
except Exception as ex1:
print (ex1)
print (type(ex1))
finally:
print "This is the final statement"
###########################################################################
try:
s = 1/0
except TypeError:
print "There was a type Error"
except Exception as ex1:
print (ex1)
print (type(ex1))
finally:
print "This is the final statement"
###########################################################################
def ask_if_integer():
while True:
try:
val = int(raw_input('Please enter an integer: '))
except Exception as ex1:
print "Looks like you didnt enter an integer. The exeption encountered is %s. Its type is %s" %(ex1,type(ex1).__name__)
#You can also substitute above print statement with:
#template = "An exception of type {0} occurred. Arguments:\n{1!r}"
#message = template.format(type(ex1).__name__, ex1.args)
#print message
continue
else:
print "Correct! You have Entered an integer of value %s" %(val)
break
finally:
print "Finally, the whole block is executed"
ask_if_integer() | true |
d267ef74020f6ff8983f2c81868d1c110bfb2ada | shubhamjanhere/Basic-Python-Programs | /Basic Python/iterator and generator.py | 678 | 4.125 | 4 |
def generate_cubes(n):
for num in range(n):
yield num**3
for x in generate_cubes(10):
print x
'''
#The alternate of above code would be:
def generate_cubes(n):
out = []
for num in range(n):
out.append(num**3)
return out
for x in generate_cubes(10):
print x
But, we would run into problems of slower execution if the no was like 1000000000000000000
'''
def simple_gen():
for x in range(4):
yield x
g = simple_gen()
print next(g)
print next(g)
print next(g)
print next(g)
# One more g will give error
# We will convert an iterable object into an iterator
s = "This"
s_iter = iter(s)
print next(s_iter)
print next(s_iter) | true |
19ce858cb97ceba6b1fe5b5226c940f028b83738 | DrSSoG/pythonStudy | /calculator.py | 1,255 | 4.21875 | 4 | print('Welcome to the C.A.L.C.U.L.A.T.O.R.')
while True:
numberOne = int(input('Insert the 1st number: '))
numberTwo = int(input('Insert the 2nd number: '))
operator = input('Specify the operator: ')
if(operator == '+' or operator == 'add'):
equals = numberOne + numberTwo
print(numberOne, ' + ', numberTwo, ' = ', equals)
elif(operator == '-' or operator == 'subtract'):
equals = numberOne - numberTwo
print(equals)
elif(operator == '*' or operator == 'multiply'):
equals = numberOne * numberTwo
print(equals)
elif(operator == '/' or operator == 'divide'):
if(numberTwo == 0):
print('You cant\'t divide by 0')
else:
equals = numberOne / numberTwo
print(equals)
elif(operator == '**' or operator == 'exponantiate'):
print(numberOne ** numberTwo)
elif(operator == 'q' or operator == 'quit'):
break
else:
print('Incorrect sign of operator')
print('========================================')
decision = input('Would you like to save to memory? y/n')
if(decision == 'y'):
print('Saved!')
elif(decision == 'n'):
continue
else:
print('Incorrect sign')
| false |
92b6e8e23ab1da2df3d0a1b063b03ee83a17d4ce | Willyb15/DC_Intro | /basics.py | 2,582 | 4.15625 | 4 | # print "Robert Bunch"
print "Will Bryant"
# # Arrays... pysche. Lists.
animals = ['wolf', 'giraffe', 'hippo']
print animals
# animals = ['wolf','giraffe','hippo']
# # print animals
print animals[0]
# # print animals[0]
print animals[2]
# # How do we push to the array/list? -- APPEND!!
animals.append('croc')
# animals.append("croc")
print animals
# # What about deleting?
animals.remove('wolf')
# animals.remove("wolf")
print animals
# # Error!
# animals.prepend("wolf")
# # We can insert at any position with ... insert
animals.insert(0, 'zebra')
animals.insert(0, 'dog')
print animals
# remove via del
del animals[0]
print animals
# # Pop, is just good old Pop
# dc_class = ['Summer', 'Jackson','Danny','Dave','JT','Eric','Paige','Brett','Danielle','Alex','Dan','Shirlette']
# # will sort, but not change the actual array
# # print sorted(dc_class)
# # print dc_class
# # will sort and change the list
# # dc_class.sort()
# # print dc_class
# # will reverse and change teh list - reverse meanign by indicie
# # dc_class.reverse()
# # print dc_class
# # len method, will work like .lenght in JS
# # print len(dc_class)
# # Indentation matters to Python!
# for student in dc_class:
# print student
# for i in range(1,10):
# print i
# for i in range(1,len(dc_class)):
# print i
# # a function is not called a funciton. It's defined by: def
# def sayHello():
# print "Hello"
# # will fail because wrong arguments
# # sayHello("Hi")
# def say_hello_with_name(name):
# print "Hello, " + name
# say_hello_with_name("Robert")
# # Make squares
# squares = []
# for i in range(1,11):
# # Two * is square
# square = i**2
# # Push that square onto the list
# squares.append(square)
# print squares
# # Random list of digits
# digits = [12,235,15,213,42,23,3215,245,342,1234,23,41234231,123,2]
# # Max and min
# print min(digits)
# print max(digits)
# print sum(digits)
# squares = [i**2 for i in range(1,11)]
# print squares
# # Step = the incrament
# print range(1,11,2)
# # slice in python is all about the :
# dc_team = ["Max","Jake","Rob","Toby","Natalie"]
# team_part = dc_team[1:3]
# print team_part
# team_part = dc_team[1:-1]
# print team_part
# team_part = dc_team[:1]
# print team_part
# team_part = dc_team[2:]
# print team_part
# # Will keep a connection so both will change when one does
# team_copy = dc_team
# print team_copy
# print dc_team
# # make a new list, independent.
# team_copy = list(dc_team)
# team_copy.append("DeAnn")
# print team_copy
# print dc_team
# team_copy = dc_team[:]
# team_copy.append("DeAnn")
# print team_copy
# print dc_team
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.