blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a4f442bb305502655fe0a52c74837d78223928ed | asinghamgoodwin/daily-programmer | /dailyprogrammer8-17.py | 842 | 4.15625 | 4 | #daily programmer easy challenge - alphabetical words
import sys
def checkOrder(word):
current = 'a'
for letter in word:
if letter < current:
return checkReverse(word) #we know its not in order, it could either be reverse or not in order from this point.
else:
current = letter
return "IN ORDER"
def checkReverse(word):
current = 'z'
for letter in word:
if letter > current:
return "NOT IN ORDER"
else:
current = letter
return "REVERSE ORDER"
#input = ['billowy', 'biopsy', 'chinos', 'defaced', 'chintz', 'sponged', 'bijoux', 'abhors', 'fiddle', 'begins', 'chimps', 'wronged']
#for word in input:
# print word + " " + checkOrder(word)
for line in sys.stdin:
word = str(line).rstrip()
print word + " " + checkOrder(word)
| true |
32a757141a813892e46d3e1a0ad537c5a2d677a6 | Yao-Ch/OctPYFunDay1AM | /Exercise3.py | 1,432 | 4.4375 | 4 | """
Exercise 3: (ExercisePy1.pdf)
1) Generate a secret random integral number ([1,100]) (see the module random)
2) With the help of a loop:
a) prompt the user for an integral number
b) increment a variable that count the current number of attempts to guess
the secret number
c) compare the number entered with the secret number
d) print an appropriate message: "Too small", "Too large", "Bingo!!"
e) if the secret number is found: leave the loop and stop the script
You should also leave the loop after 6 attempts to guess the secret number
3) If, at the end of the loop, the secret number is not found print a message
with the value of the secret number
"""
import random
secret=random.randint(1,100)
print(secret)
currentNumberOfAttempts=0
currentValue=0
while secret != currentValue and currentNumberOfAttempts < 6:
currentValue=input(f"Enter an int in the range [1,100] ({currentNumberOfAttempts+1}/6): ")
currentValue=int(currentValue)
if currentValue == secret:
print ("Bingo ! You've found the secret number")
elif currentValue > secret:
print("Too large !")
elif currentValue < secret:
print("Too small")
# currentNumberOfAttempts = currentNumberOfAttempts + 1
currentNumberOfAttempts += 1
if secret != currentValue:
print("The secret number was:", secret)
| true |
69e0c2f748ba4d72b9c4db4ba871c3d080765038 | AIALRA-0/RPI-csci1100-Python | /HW/hw04/hw4Part1.py | 1,484 | 4.40625 | 4 | # function that used to check whether this word is alternative or not
def is_alternating(word):
letters = 'abcdefghijklmnopqrstuvwxyz'
consonants = 'bcdfghjklmnpqrstvwxyz'
vowels = 'aeiou'
# the word should be at least 8 letters
if len(word) < 8:
return False
# the word should have no numbers
for index in range(len(word)):
if word[index] not in letters:
return False
# the word should not have two adjacent vowels or two adjacent consonants
for index in range(len(word)-1):
if word[index] in consonants and word[index+1] in consonants:
return False
if word[index] in vowels and word[index+1] in vowels:
return False
# the vowels in this word should not be in decrease order
for index in range(len(word)-2):
if word[index] in vowels and word[index] > word[index+2]:
return False
return True
# print out whether it is alternative or not
i = 0
while True:
# input the word
word = input('Enter a word: ')
print(word)
# if input nothing, it will stop asking for a word
if len(word) == 0:
break
else:
# if it alternative
if is_alternating(word.lower()):
print("The word '{}' is alternating".format(word))
print('')
# if it is not alternative
else:
print("The word '{}' is not alternating".format(word))
print('')
| true |
4798707ce553bd14ebe379ee8df0021b473050f9 | AIALRA-0/RPI-csci1100-Python | /HW/hw03/hw3Part2.py | 1,679 | 4.25 | 4 | #Jiaxi Mei
#import the required funcion
import hw3_util
#calculate the required coins that used to change
def can_or_cannot(current, coins, i, final_list):
if i < 0 or current == 0:
return final_list
if current >= coins[i]:
current = current - coins[i]
final_list.append(coins[i])
return can_or_cannot(current, coins, i-1, final_list)
else:
return can_or_cannot(current, coins, i-1, final_list)
#input the file's name and the cost in cents
file_name = input('Enter the coin file name => ')
print(file_name)
cost = int(input('Enter the item cost in cents (0-100) => '))
print(cost)
coins = hw3_util.read_change(file_name)
print('')
print('I have the following coins:')
print(coins)
#state the required information for the function
current = int(100 - cost)
coins.append(current)
coins.sort()
index = coins.index(current)
index = index - 1
final_list = []
print('Change from ${:.2f} is {} cents'.format(1, current))
#call the function
final_list = can_or_cannot(current, coins, index, final_list)
#if cannot change, print how many cents additionaly required to change
if int(sum(final_list)) != current :
print('I cannot make change with my current coins.')
print('I need an additional {0} cents.'.format(current-sum(final_list)))
#if can change, print out the number for each kind of coins required
else :
half_dollars = final_list.count(50)
quarters = final_list.count(25)
dimes = final_list.count(10)
nickels = final_list.count(5)
pennies = final_list.count(1)
print('{} Half Dollars, {} Quarters, {} Dimes, {} Nickels, {} Pennies'.format(half_dollars, quarters, dimes, nickels, pennies)) | true |
ef0a3affb76a693df4ea8e1d8dc699684a330595 | cr00bert/PyTraining | /scikitLearnTutorial05.py | 734 | 4.125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import seaborn
seaborn.set()
# Every algorithm in scikit-learn is exposed via Estimator object
from sklearn.linear_model import LinearRegression
model = LinearRegression(normalize=True)
print(model.normalize)
print(model)
# Simulate some data for a Regression exercise
x = np.arange(10)
y = 2 * x + 1
# Represent the data
print(x)
print(y)
plt.plot(x, y, 'r*')
plt.show()
# The input data for sklearn is 2D: (samples == 10 x features == 1)
# X = np.array(x).reshape(len(x), 1)
X = x[:, np.newaxis]
print(X)
print(y)
# fit the model on the data
model.fit(X, y)
# underscore at the end indicate a fit parameter
print(model.coef_)
print(model.intercept_)
print(model.residues_)
| true |
d2c2daf59ee36ca8db7cbc80b3f0f301d0075a4d | elenaborisova/Python-Fundamentals | /15. Text Processing - Lab/01.reverse_strings.py | 324 | 4.28125 | 4 | def reverse_string(string):
reversed_string = ""
for char in reversed(string):
reversed_string += char
return reversed_string
words = []
while True:
command = input()
if command == "end":
break
words.append(command)
for word in words:
print(f"{word} = {reverse_string(word)}")
| true |
03db32609a43beccea424d6dec4170dd13de2a10 | elenaborisova/Python-Fundamentals | /07. Functions - Lab/04_orders.py | 579 | 4.15625 | 4 | COFFEE_PRICE = 1.5
WATER_PRICE = 1.0
COKE_PRICE = 1.4
SNACKS_PRICE = 2.0
def calculate_price(product: str, quantity: int):
result = None
if product == "coffee":
result = COFFEE_PRICE * quantity
elif product == "water":
result = WATER_PRICE * quantity
elif product == "coke":
result = COKE_PRICE * quantity
elif product == "snacks":
result = SNACKS_PRICE * quantity
return f"{result:.2f}"
product_to_order: str = input()
quantity_to_order: int = int(input())
print(calculate_price(product_to_order, quantity_to_order))
| true |
b9dc26f147daea756dcab4bf739d109e59263622 | romutaba/ANDELA-BC-14 | /data_type.py | 832 | 4.5 | 4 | # A Function that identifies Data Types
def data_type(n):
#data type String check
if (type(n) == type("")):
msg = len(n) #returns the string's length
#data type Boolean check
elif (type(n) == type(True)):
msg = n #returns the boolean value
#data type integer check
elif (type(n) == type(3)):
#checks if integer input is less than 100
if (n < 100):
msg = "less than 100"
#checks if integer input is equal to 100
elif (n == 100):
msg = "equal to 100"
#checks if integer input is more than 100
else:
msg = "more than 100"
#data type list check
elif (type(n) == type([])):
#checks if list length is more than or equal to 3
if (len(n) >= 3):
msg = n[2]
#checks if list length is less than 3
else:
msg = None
#no data type check
else:
msg = "no value"
return msg
| true |
e22c4b7a80bcc389d36ef29d30df4022a5f9d37a | mstfalkn/D.E.Z.I | /Dezi_Eklentiler/Sayı Tahmin Oyunu.py | 1,154 | 4.1875 | 4 | #Bu oyun Mustafa ALKAN Tarafından Yazılmıştır.
#Programı bilgisayarınızda çalıştırmak için Python Yüklü olmalıdır ve Gerekli Kütüphaneleri kurmanız gerekmektedir.
soru="evet"
while soru=="evet" or soru=="EVET" or soru=="Evet":
import random
import time
bilgisayarınSeçtiğiSayı=random.randint(1,100)
print("------------Sayı Tahmin Oyunu------------")
benimTahminEtiğimSayı=int(input("Tuttuğum sayıyı tahmin et: "))
print("-----------------------------------------")
while True:
if bilgisayarınSeçtiğiSayı==benimTahminEtiğimSayı:
print("Doğru Bildin. Tebrikler")
soru=input("Tekrar Oynamak İster misin ? ")
time.sleep(5)
break
elif benimTahminEtiğimSayı>bilgisayarınSeçtiğiSayı:
benimTahminEtiğimSayı=int(input("Daha küçük bir sayı dene: "))
print("-----------------------------------------")
else:
benimTahminEtiğimSayı=int(input("Daha büyük bir sayı dene: "))
print("-----------------------------------------")
| false |
2b98199b747e4e03e521f7d774b45eb48922e3ac | DarkShadow4/Python | /Python 3/Crash course/pruebas de slicing.py | 2,257 | 4.25 | 4 | # creo el string
letters = "abcdefghij"
numbers = "0123456789"
# La sintáxis del slicing es la siguiente string[start:end:step]
# start = start || start es el indice en el que empieza el slice
# end = end-1 || end es el elemento en el que termina el slice
# step = step || step es el avance del slice (por defecto es 1, es decir, si no se introduce, es como si se introdujese un 1)
# Un slice es como un bucle (pero no es un bucle) que se usa solo para obtener fragmentos de objetos iterables. Al igual que en los bucles convencionales que usan un contador
# y su condición de salida es el valor maximo que debe tomar el contador
# Para hacer una correcta comparación con un bucle convencional voy a hacer un bucle con un estructura parecida a la que tendria un slice si fuera realmente un bucle:
iterador = start = 0
end = 5
step = 2
while iterador < end:
# do something
print("iterador: " + str(iterador))#yo imprimo el iterador para mostrar el funcionamiento con el step distinto a 1, pero el objetivo de un splice no es imprimir el slice,
# sino devolverlo para poder usarlo
print("letra: " + letters[iterador])#en el caso del slice de las letras
print("numero: " + numbers[iterador])#en el caso del slice de los numeros
iterador += step
#imprimo del primero al 5
print(string[0:5]) # imprime del indice 0 al quinto elemento (indice 4)
print(string[1:5]) # imprime del indice 1 al quinto elemento (indice 4)
print(string[5:]) # imprime del indice 5 hasta el final
print(numbers[0:5]) # imprime del indice 0 al quinto elemento (indice 4)
print(numbers[1:5]) # imprime del indice 1 al quinto elemento (indice 4)
print(numbers[5:]) # imprime del indice 5 hasta el final
# Viendo el output genedado decuzco que al hacer un slice, el primer indice indica el indice donde empieza el slice, mientras que el segundo indice indica el elemento donde acaba
# Esto seria lo mismo que decir que el primer indice introducido lo trata tal cuál se introduce, sin embargo, al segundo indice se le resta una unidad
# Para copiar una lista sin que se vinculen la nueva y la copiada se copia usando un slice de toda la lista
lista1 = list(range(10))
lista2 = lista1[:] #no hace falta poner el step
lista1.append(10)
print(lista1)
print(lista2)
| false |
f17f499b6337b925d14dae1ebcd8c4edbf181b22 | DarkShadow4/Python | /Python 3/Crash course/operadores que se se suelen usar en condicionales.py | 631 | 4.1875 | 4 | variable1 = "texto"
variable2 = "Texto"
variable3 = "no texto"
print(variable1 == variable2)
print(variable2.lower() == variable1)
print(variable2 == variable3)
print(variable2 != variable3)
print(variable2 is not variable3)
print(variable1 is variable2.lower())
# == igualdad
# != desigualdad
# > mayor || >= mayor o igual
# < menor || <= menor o igual
# and operador logico and
# or operador logico or
# in operador o palabra clave para comprobar si un elemento existe dentro de un objeto iterable
# not operador o palaba clave para invertir el resultado de la siguiente palabra clave
# Los valores booleanos son True y False
| false |
a02f0eb9904375f5dd3346931cfc1c4f15bd0e0e | tojimahammatov/sorting_algorithms | /heap_sort/python/max_heap.py | 1,598 | 4.25 | 4 | # Time complexity, Big O ==>> O(n*logn)
# Space complexity, Big O ==>> O(1)
# Max heap - a heap in which any parent is greater or equal to its children
# Note: max heap implementation means sorting elements in ascending order
HEAP_SIZE = 10
def left_child(index):
"""
returns left child's index in the list
"""
return 2*index
def right_child(index):
"""
returns right child's index in the list
"""
return (2*index+1)
def parent(index):
"""
returns index of a parent in the list
"""
return index//2
def max_heapify(A, index):
"""
applies (max) heapify operation to the given list starting from the index
"""
global HEAP_SIZE
left = left_child(index)
right = right_child(index)
largest = index
if left<=HEAP_SIZE and A[index]<A[left]:
largest = left
if right<=HEAP_SIZE and A[largest]<A[right]:
largest = right
if largest != index:
A[index], A[largest] = A[largest], A[index]
max_heapify(A, largest)
def build_max_heap(A):
"""
builds (max) heap from the given list
"""
global HEAP_SIZE
for index in range(HEAP_SIZE//2, 0, -1):
max_heapify(A, index)
def heapsort(A):
"""
applies heapsort to the given heap
"""
global HEAP_SIZE
for _ in range(HEAP_SIZE-1):
A[1], A[HEAP_SIZE] = A[HEAP_SIZE], A[1]
HEAP_SIZE -= 1
max_heapify(A, 1)
# example
A = ["TEST", 4, 6, 1, 9, 7, 2,0, -2, 8, 5]
build_max_heap(A) # build heap
print(A) # see the heap
heapsort(A) # sort heap
print(A) | true |
e0c85ea2b40979699ad07afe7049f6a5f923f527 | dayo1/dayo123 | /Week 5.py | 2,480 | 4.125 | 4 |
"""
word = input('please enter your word')
if word
"""
"""
Myfruit
= 'apple'
print(len(Myfruit))
"""
"""
wrd = input ("Please enter a word: ")
rvs= wrd[::-1]
if wrd == rvs:
print( "Your word ",wrd, " is a palindrome")
else:
print("Your word ", wrd, " is not a palindrome")
str1 = "programming"
str2 = input(" Please enter a number: ")
# slice programing to get program
str3 = str1[0:7]
print("str1[0:7] = ", str3)
# str4 = str2 - 25
str4 = int(str2) - 25
print(" int(str2) - 25: = ", str4)
"""
"""
str1 ="please do not throw sausage pizza away, please do not , please !!"
str2 = "the quick brown fox jumps over the lazy "
str1= str1.split()
str2= str2.split()
counts = dict()
for word in str1: #str2:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print (counts)
greet = 'Hello Bob'
new = greet.replace('Bob','Jane')
print (new)
print (new)
lw = greet.lower()
print (lw)
lw = greet.lower()
print (lw)
greet = 'Hello Bob'
new = greet.replace('o','X')
print (new)
print (new)
lw = greet.lower()
print (lw)
lw = greet.lower()
print (lw)
"""
"""
greet = ' Hello Bob '
new = greet.lstrip()
print(new)
greet = ' Hello Bob '
new = greet.rstrip()
print(new)
new = greet.strip()
print(new)
"""
"""
Mystr = "Python is awesome....yeah!!!"
print("Padded string : ",Mystr.zfill(40))
print ("Padded String : ",Mystr.zfill(50))
"""
"""
str = "this is 2018"
print (str.isdecimal())
str = "23443434"
print (str.isdecimal())
line = 'Do have a nice day'
line.startswith('Do')
"""
"""
line = 'Do have a nice day'
line.startswith('Do')
"""
"""
dogs = 42
print('I have spotted %d dogs.' % dogs)
"""
"""
marks = int(input("Enter the score: "))
if (marks>80):
print("Grade A")
elif (marks >60) and (marks<=80):
print ("Grade B")
elif (marks>40) and (marks <=60):
print ("Grade C")
else:
print ("Grade D")
x = int(input("Enter the first number: "))
y = int(input("Please enter the second number: - "))
if (x==y) or abs(x-y) == 10:
print("true")
else:
print("false")
"""
"""
x = input("Enter a number: ")
if x.isdigit():
print("processing. Please wait...")
else:
print("Wrong input")
x = input("Enter a number: ")
if x.isdigit():
print("Inputs are numbers...")
else:
print("Wrong input")
"""
# line.startswith('Please')
dogs =42
print('I have spotted %d dogs.' % dogs)
str ='In %d years, I have spotted %g %s.' % (3, 0.1, 'dogs')
print(str)
| false |
7c20406d5ec3275a376adeb83b291f3ce7ef249a | HombreConNombre/Ejercicios_Python | /pFlujosyCombersiones.py | 1,643 | 4.15625 | 4 | #Ejercicio 1 Flujo y conversiones (La comento para que no se active en las pruebas)
'''
multiples=[]
numero=-1
while numero<0 or numero>9:
numero=int(input("Introduce un número entre 0 y 9:"))
multiples=list(range(0,101,numero))
print(multiples)
'''
#Ejercicio 2 (La comento para que no se active en las pruebas)
'''
Comentario multiple linea
n1=int(input("Introduce el primer valor: "))
n2=int(input("Introduce el segundo valor: "))
while True:
opcion=int(input("""Introduce qué quieres hacer
1-> suma los números
2-> resta los números
3-> multiplica los números
4-> salir
"""))
if opcion==1:
print(n1+n2)
elif opcion==2:
print(n1-n2)
elif opcion==3:
print(n1*n2)
elif opcion==4:
break
else:
print("La opción no es correcta")
'''
#Ejercicio 3 (La comento para que no se active en las pruebas)
'''
while True:
n=int(input("Introduce un número impar para acabar el programa: "))
if n%2!=0:
break
'''
#Ejercicio 4 (La comento para que no se active en las pruebas)
'''
pares=list(range(0,11,2))
sumatorio=0
for x in pares:
sumatorio+=x
print(sumatorio)
'''
#Ejercicio 5 (La comento para que no se active en las pruebas)
'''
opcion=-1
acumulado=0
nveces=0
while opcion!=0:
opcion=int(input("Introduce un numero: "))
if opcion!=0:
acumulado+=opcion
nveces+=1
media=acumulado/nveces
print(media)
'''
#Ejercicio 6
list1=['H','o','l','a','','m','u','n','d','o']
list2=['H','o','l','a','','m','u','n','d','o']
list3=[]
for x in list1:
if x in list2 and x not in list3:
list3.append(x)
print(list3)
| false |
dd65823cb957e35ab92aeae6f7c70a6e9489f545 | Archit9394/Python_OOPS | /task1.py | 425 | 4.3125 | 4 | # 1. Write a program that calculates and prints the value according to the given formula:
# Q= Square root of [(2*C*D)/H]
# Following are the fixed values of C and H:
# C is 50. H is 30.
# D is the variable whose values should be input to your program in a comma-separated sequence.
from math import sqrt
def square_root(D):
C=50
H=30
return sqrt(2*C*D/H)
D=int(input("Enter a D value:"))
print (square_root(D))
| true |
a3dfe5bc6c5ffb3d1023334fabd3d2f0a5f090cd | lauguma/text_files | /list_del_replace.py | 2,804 | 4.125 | 4 | #!/usr/bin/python
__author__ = "Laura G. Macias"
from argparse import ArgumentParser
import csv
'''
Program to remove or replace elements contained a txt file.
Input text file provide by the < -list_in > option: elements separated by \n
USAGE options:
- Delete: elements provided by -replace option will be removed from input text file
python list_del_replace.py -list_in input_list.txt -del -changes elements_to_change.txt
elements_to_change.txt --> elements separated by \n
Example:
gene345
G87
tag76
Elements gene345, G87 and tag76 will be removed from input text file
- Replace:
python list_del_replace.py -list_in input_list.txt -repl -changes elements_to_change_and_replacements.txt
elements_to_change_and_replacements.txt --> elements separated by: element2find \t replacement
Example:
gene345 G0140
G87 G0150
tag76 G0160
Elements gene345, G87 and tag76 will be replaced by G0140, G0150, G0160 respectively.
OUTPUT:
Final list will be written in the standard output. To save new list:
Example:
python list_del_replace.py -list_in input_list.txt -del -changes elements_to_change.txt > new_list.txt
'''
def main():
parser = ArgumentParser()
parser.add_argument("-list_in", dest="file_list", help="input file containing list of elements", type=str)
parser.add_argument("-changes", dest="list_changes", help="text file with elements to be removed or change", type=str)
parser.add_argument("-repl", dest="replace", help="replace elemnts in input list", action="store_true", default=False)
parser.add_argument("-del", dest="delete",help="remove elements in input list", action="store_true", default=True)
args = parser.parse_args()
# Option: replace
if args.replace:
replacements = {}
with open(args.list_changes, "r") as input_handle:
csvreader = csv.reader(input_handle,delimiter="\t")
for row in csvreader:
replacements[row[0]] = row[1]
elements = []
with open(args.file_list, "r") as list_in:
for line in list_in:
e = line.strip()
if e in replacements.keys():
elements.append(replacements[e])
else:
elements.append(e)
for x in elements:
print(x)
# Option: delete
if args.delete:
del_elements = []
with open(args.list_changes, "r") as input_handle:
for line in input_handle:
e = line.strip()
del_elements.append(e)
with open(args.file_list, "r") as list_in:
for line in list_in:
e = line.strip()
if e not in del_elements:
print(e)
if __name__ == "__main__":
main()
| true |
39f8ec7aefcd79d06962ac5cceed058aa5c2f26c | cod3rs-ns/4-ml-siit-2017 | /ex-01-linear-regression/lin_reg.py | 1,115 | 4.25 | 4 | import numpy as np
def linear_regression(x, y):
"""
Function which evaluate 'slope' and 'intercept' coefficients for linear regression:
y_hat = intercept + slope * x;
where:
x input value
y_hat predicted value
:param x: input data
:param y: output data
:return: tuple of coefficients (slope, intercept)
"""
assert (len(x) == len(y))
x_mean = np.mean(x)
y_mean = np.mean(y)
numerator = sum([xi * yi for xi, yi in zip(x, y)])
denominator = sum([xi ** 2 for xi in x])
slope = numerator / denominator
intercept = y_mean - slope * x_mean
return slope, intercept
def rmse(x, y, y_hat):
"""
Function which evaluate RMSE regarding to this formula:
@link http://www.saedsayad.com/images/RMSE.png
:param x: input values
:param y: real output values
:param y_hat: function we use for predicate output
:return: evaluated Root Mean Square Error
"""
assert (len(x) == len(y))
n = len(x)
return np.sqrt(sum(map(lambda (xi, yi): (yi - y_hat(xi))**2, zip(x, y)))/n)
| true |
ab6b224ee92ab9ba69a3be80ad881112bed1ae26 | lakshmisowmya29/python-learnings | /HackerRanker/straicase#.py | 259 | 4.15625 | 4 |
def staircase(n):
for i in range (1,n+1):
for j in range (1,n-i+1):
print (" ",end="")
for j in range (1,i+1):
print ("#",end="")
print("")
if __name__ == '__main__':
n = 5
staircase(n)
| false |
4ff98200651b983abbb15f7667deca5f15eb89a2 | Jie-A/EasyClassification | /easycls/helpers/times.py | 2,380 | 4.15625 | 4 | import time
import datetime
def format_time(timestamp=None, format=r"%Y%m%d-%H%M%S"):
"""
Return a formatted time string
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
"""
time_str = time.strftime(format, time.localtime(timestamp if timestamp else time.time()))
return time_str
def readable_time(timestamp=None):
"""
Return a human-friendly string of a timestamp
e.g.
timestamp: 1582029001.6709404
readable time: Tue Feb 18 20:30:01 2020
Args:
timestamp: a UNIX timestamp
Returns:
str, a human-friendly readable string of the argument timestamp
"""
time_readable_str = str(time.asctime(time.localtime(timestamp if timestamp else time.time())))
return time_readable_str
def readable_eta(seconds_left):
"""
Return a human-friendly string of ETA time and left time
e.g.
seconds_left: 90090
ETA: Wed Feb 19 21:42:19 2020
Time-left: 1 day, 1:01:30
Args:
seconds_left: int or float, seconds left
Returns:
tuple of str, ETA string and Time-left string, both in human readable form
"""
eta_time = readable_time(time.time() + seconds_left)
time_left = datetime.timedelta(seconds=int(seconds_left))
return str(eta_time), str(time_left)
# # Unit Test
# if __name__ == "__main__":
# ts = time.time()
# print(f'Timestamp: {ts} -> {readable_time(ts)}')
# print(f'format time: {format_time(ts)}')
# seconds_left = 3600 * 25 + 90
# eta, Tleft = readable_eta(seconds_left)
# print(f'seconds_left: {seconds_left}, ETA: {eta}, in {Tleft}')
# print(readable_time(), format_time())
# time.sleep(3)
# print(readable_time(), format_time()) | true |
809366d5197673b054444b40f057d84f679ccc43 | anjan111/charan | /004_datatype conversion.py | 594 | 4.34375 | 4 | # datatype conversion functions
'''
===>> to convert raw_inpt str datatype to specific datatype
'''
# there are 9 functions
'''
==>> int( ) ===>> to convert int
==>> float() ==>> to convert float
==>> complex() ==>> to convert complex
==>> bool() ====>> to convert to bool
==>> str ()======> to convert to str
==>> list() =====>> to convert to list
==>> tuple () ===>> to convert to tuple
===> set()
===> dict()
'''
var = int(raw_input("enter int :"))
print "data in var :",var
print (type(var))
print "memory : ",id(var)
# write 9 programs for 9 differnt functions
| false |
716d735e87e20092f05777c32ff7e6d91b798df2 | dldamian/ProgramasPython | /06-Calificaciones.py | 2,699 | 4.125 | 4 | print('Bienvenido al clasificador de Calificaciones')
iniciador = True
calificaciones = []
while iniciador:
calif = input('Escribe tu primera calificación (0-100): ')
try:
calif = int(calif)
if calif >= 0 and calif < 101:
calificaciones.append(calif)
while True:
calif = input('Escribe tu segunda segunda calificación (0-100): ')
try:
calif = int(calif)
if calif >= 0 and calif <101:
calificaciones.append(calif)
while True:
calif = input('Escribe tu tercera calificación (0-100): ')
try:
calif = int(calif)
if calif >= 0 and calif < 101:
calificaciones.append(calif)
while True:
calif = input('Escribe tu cuarta calificación (0-100): ')
try:
calif = int(calif)
if calif >= 0 and calif <101:
calificaciones.append(calif)
iniciador = False
break
else:
print('Solo números de 1-100')
except:
print('Escribe solo números')
break
else:
print('Solo números de entre 0-100')
except:
print('Escribe solo números')
break
else:
print('Solo números de entre 0-100')
except:
print('Escribe solo números')
break
else:
print('Solo números de entre 0-100')
except:
print('Solo números')
print(f'\nTus calificaciones son: {calificaciones}')
print('\nTus 2 calificaciones más bajas serán eliminadas:')
calificaciones.sort()
calif_fuera = calificaciones.pop(0)
print(f'Calificación eliminada: {calif_fuera}')
calif_fuera = calificaciones.pop(0)
print(f'Calificación eliminada: {calif_fuera}')
print(f'\nTus calificaciones restantes son: {calificaciones}')
print(f'¡Bien hecho! tu calificación más alta es {calificaciones[1]}') | false |
a0e4072781ee3466c62fd1593ab45b7dcca8d346 | lcgly123/leetcode | /623. Add One Row to Tree.py | 1,854 | 4.125 | 4 | 623. Add One Row to Tree
Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.
The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.
Example 1:
Input:
A binary tree as following:
4
/ \
2 6
/ \ /
3 1 5
v = 1
d = 2
Output:
4
/ \
1 1
/ \
2 6
/ \ /
3 1 5
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
row=[]
dummy,dummy.left=TreeNode(None),root
queen=[dummy]
k=0
while k<(d-1):
new_layer=[]
for new_root in queen:
if new_root.left!=None:
new_layer.append(new_root.left)
if new_root.right!=None:
new_layer.append(new_root.right)
queen=new_layer
k+=1
for node in queen:
node.left,node.left.left=TreeNode(v),node.left
node.right,node.right.right=TreeNode(v),node.right
return dummy.left
| true |
2f275116dd24b6d2799147b7eea0929640588736 | lcgly123/leetcode | /739. Daily Temperatures.py | 832 | 4.1875 | 4 | 739. Daily Temperatures
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack=[]
res=[0]*len(T)
# 其实就是找下一个比该点大的数,求他俩的距离
# 栈NB,之前见过这种用法
for i,t in enumerate(T):
while(stack and T[stack[-1]]<t):
last_i=stack.pop()
res[last_i]=i-last_i
stack.append(i)
return res
| true |
36245d450590c0b36b841a3b6128c1b581094e44 | SaretMagnoslove/Udacity-CS101 | /Unit12/Unit12Code.py | 2,119 | 4.40625 | 4 | # Define a procedure, product_list,
# that takes as input a list of numbers,
# and returns a number that is
# the result of multiplying all
# those numbers together.
def product_list(list_of_numbers):
product = 1
for number in list_of_numbers:
product *= number
return product
print (product_list([9]))
#>>> 9
print (product_list([1,2,3,4]))
#>>> 24
print (product_list([]))
#>>> 1
# Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.
def greatest(list_of_numbers):
return max(list_of_numbers) if list_of_numbers else 0
#print greatest([4,23,1])
#>>> 23
#print greatest([])
#>>> 0
# Define a procedure, total_enrollment,
# that takes as an input a list of elements,
# where each element is a list containing
# three elements: a university name,
# the total number of students enrolled,
# and the annual tuition fees.
# The procedure should return two numbers,
# not a string,
# giving the total number of students
# enrolled at all of the universities
# in the list, and the total tuition fees
# (which is the sum of the number
# of students enrolled times the
# tuition fees for each university).
udacious_univs = [['Udacity',90000,0]]
usa_univs = [ ['California Institute of Technology',2175,37704],
['Harvard',19627,39849],
['Massachusetts Institute of Technology',10566,40732],
['Princeton',7802,37000],
['Rice',5879,35551],
['Stanford',19535,40569],
['Yale',11701,40500] ]
def total_enrollment(universities):
students, fee = 0,0
for name, numStudents, price in universities:
students += numStudents
fee += (numStudents * price)
return students, fee
print (total_enrollment(udacious_univs))
#>>> (90000,0)
# The L is automatically added by Python to indicate a long
# number. If you are trying the question in an outside
# interpreter you might not see it.
print (total_enrollment(usa_univs))
#>>> (77285,3058581079) | true |
43fb406d3ff9af7b7356d796ffc1a306fdb42efc | AleeWeb/python-codingdojo | /math.py | 847 | 4.46875 | 4 |
# Multiples
'''Part I - Write code that prints all the odd numbers from 1 to 1000.
Use the for loop and don't use a list to do this exercise.
'''
#loop from 0 to 1000
def oddNumpicker():
for i in range(1,1001):
if i % 2 != 0: # Checks if remainder is divisible by 2, if not = to 0, the number is odd!
print i
oddNumpicker()
'''
Part II - Create another program that prints all the multiples of 5
from 5 to 1,000,000.
'''
def chooseFive():
for i in range(5,1000001):
if i % 5 == 0:
print i
chooseFive()
# Sum List
'''
Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3]
'''
a = [1, 2, 5, 10, 255, 3]
b = sum(a)
print b
# Average List
'''
Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3]
'''
a = [1, 2, 5, 10, 255, 3]
def avgList():
| true |
3741624db7f2851258a40be736727fcea5005987 | dlanghorne0428/Ballroom | /Position.py | 1,734 | 4.3125 | 4 | """ The Position Module contains a Position() class and NO_MOVEMENT constant"""
import copy
import math
class Position():
"""
The Position() class implements a position in 2-D space, representing
an x-coordinate, y-coordinate, and an angle.
"""
def __init__(self):
self.x = 0
self.y = 0
self.angle = 0
def copy(self):
return copy.deepcopy(self)
def set(self, x, y, angle):
self.x = x
self.y = y
self.angle = angle
def adjust(self, x, y, angle):
""" modify the current position by the given amounts """
self.x += x
self.y += y
self.angle += angle
if self.angle > 360:
self.angle -= 360
elif self.angle <= -360:
self.angle += 360
def offset_by(self, x_dist, y_dist, rotation):
"""
Create a new position based on the current position.
The x_dist and y_dist offsets are assuming the current position is
at 0 degrees of rotation.
"""
new_pos = Position()
new_pos.x = (self.x
+ x_dist * math.sin(math.radians(self.angle+90))
+ y_dist * math.cos(math.radians(self.angle+90)))
new_pos.y = (self.y
+ x_dist * math.sin(math.radians(self.angle))
+ y_dist * math.cos(math.radians(self.angle)))
new_pos.angle = self.angle + rotation
if new_pos.angle > 360:
new_pos.angle -= 360
elif new_pos.angle < -360:
new_pos_angle += 360
return new_pos
def print(self):
print("(", round(self.x,2),",", round(self.y,2),",", round(self.angle,2),")",end="\t")
NO_MOVEMENT = Position()
| true |
981a6ed81272de6d7b5c5082d19371e1d2b1288e | SatishReddy006/Artificial-Intelligence | /data-structures-algorithms/problems-vs-algorithms/Problem_1.py | 937 | 4.34375 | 4 | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number is None or number <0:
return None
if (number == 0 or number == 1) :
return number
start = 1
end = number
while (start <= end) :
mid = (start + end) // 2
if (mid*mid == number) :
return mid
if (mid * mid < number) :
start = mid + 1
answer = mid
else :
end = mid-1
return answer
print ("Pass" if (3 == sqrt(9)) else "Fail") #return 3
print ("Pass" if (0 == sqrt(0)) else "Fail") #return 0
print ("Pass" if (4 == sqrt(16)) else "Fail") #return 4
print ("Pass" if (None == sqrt(-1)) else "Fail") #return None
print ("Pass" if (None == sqrt(None)) else "Fail") #return None | true |
25cbcb0769d6e55df8258158db44425fee9f7fca | TorNim0s/Python | /Learning/5.4.py | 2,224 | 4.21875 | 4 | import functools
def convertoint(list_str):
"""
:param list_str: list of number in str format
:return: list of number in int format
"""
newlist = []
for number in list_str: # loop on all of the number in the list
newlist.append(int(number)) # convert them into int format
return newlist # return list of numbers in int format
def multiplynum(list_numbers):
"""
:param list_numbers: list of numbers to multiply
:return: the numbers multiply following the rules
;command: the request is to multiply even positions, start from 0 so multiply the not even positions
"""
for position in range(len(list_numbers)): # loop on all of the position in list_numbers
if position % 2 != 0: # check if number is not in the even position
list_numbers[position] *= 2 # multiply the number if not in the even position
return list_numbers # return list of numbers multiplied
def checknumber(list_numbers):
"""
:param list_numbers: check for numbers greater then 9
:return: return list of number - if number was greater than 9 it sum the number -- 14 - 1 + 4 = 5
"""
newlist = []
for number in list_numbers:
if number > 9: # check if number is even
number = functools.reduce(lambda x,y: int(x)+int(y), str(number)) # sum the number if greater than 9
newlist.append(number) # adding the number to the new list
return newlist # return new list with number not greater than 9
def combinenumber(list_numbers):
return functools.reduce(lambda x, y: x + y, list_numbers) # combine all the numbers in the list
def check_id_valid(id):
"""
:param id: ID is the id to check if is valid
:return: True if id is valid, False if not
"""
list_numbers = list(str(id)) # make a list of the id numbers (in str format)
sumofnumbers = combinenumber(checknumber(multiplynum(convertoint(list_numbers)))) # make the math on the id to check if valid
if sumofnumbers % 10 == 0: # check if the sum of the numbers after the math is divided by 10 with no remander
return True
return False
print(check_id_valid(123456782)) # print if id is valid -- True if valid -- False if not
| true |
2a3898f9017e5b99202bcfc545e6f6fd71a9f3b1 | Nikunj-Ramani/BootCamp | /practice.py | 1,207 | 4.25 | 4 | #!/usr/bin/python
print("1. Looping Through a String")
for i in "0123":
print(i)
print('===============================\n')
print("2. The break Statement")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
print('===============================\n')
print("3. The break Statement")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
print('===============================\n')
print("4. The continue Statement")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
print('===============================\n')
print("5. The range() Function")
for x in range(3):
print(x)
print('===============================\n')
for x in range(4, 6):
print(x)
print('===============================\n')
for x in range(2, 13, 4):
print(x)
print('===============================\n')
print("6. The function")
def my_function():
print("Hello from a function")
my_function()
print('===============================\n')
print("7. The function")
def my_function(fname):
print(fname + " --> My collegues")
my_function("Emil")
my_function("Tobias")
my_function("Linus") | false |
266819c9be064bcea8250241419ffdb332618958 | Venkata09578/Design-1 | /minstack.py | 1,576 | 4.15625 | 4 | class MinStack:
def __init__(self): #Intializing main stack and min stack to store incoming and minimum elements.
self.mainst = []
self.minst = []
self.min = float("inf") #Intializing infinity to Minimum
def push(self, x):
if x < self.min: #Checks if the incoming element is less than min.If it is less than min that update min
self.min = x
self.mainst.append(x) #Append incoming element to main stack
self.minst.append(self.min) ##Append min element to min stack
def pop(self):##Checks if the main and min stacks are empty if not pop the element from both the stacks and update min
if len(self.mainst) == 0:
return None
else:
self.mainst.pop()
self.minst.pop()
if len(self.minst) == 0:
return None
else:
self.min = self.minst[-1]
def top(self):##retur the top element of main stack
if len(self.mainst) == 0:
return None
return self.mainst[-1]
def getMin(self):#returns the top element in min stack
if len(self.minst) == 0:
return None
else:
return self.minst[-1]
def isEmpty(self):
return self.mainst == []
# Your MinStack object will be instantiated and called as such:
obj = MinStack()
obj.push(3)
obj.pop()
param_3 = obj.top()
param_4 = obj.getMin()
| true |
56928394d3865792c7578b16aa94e3f5e7682bbc | arunh/python-by-example-150-challenges | /challenges80-87/challenge-083.py | 263 | 4.34375 | 4 | string = str(input('Please enter word in upper case ? '))
is_upper = False
while not is_upper:
if string.isupper():
is_upper = True
else:
string = str(input('Sorry not all in upper case, please enter word in upper case ? '))
print(string)
| true |
afa76f2d5b721d34d6387e860b1228a890601e89 | RaphaelMolina/Curso_em_video_Python3 | /Desafio_72.py | 1,099 | 4.15625 | 4 | from Titulo import Titulo
d = Titulo(72, 'Número por Extenso!!!')
d.Desafio()
contagem = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis',
'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze',
'catorze', 'qquize', 'dezesseis', 'dezessete', 'dezoito',
'dezenove', 'vinte')
# Sem o quer continuar:
while True:
numero = int(input('Digite um número entre 0 e 20: '))
if 0 <= numero <= 20:
break
print('Tente novamente. ', end='')
print(f'\nVocê digitou o número {contagem[numero]}.\n')
# Com o quer continuar:
while True:
numero = int(input('Digite um número entre 0 e 20: '))
if 0 <= numero <= 20:
print(f'\nVocê digitou o número {contagem[numero]}.\n')
resposta = str(input('Você quer continuar? [S/N] ')).strip().upper()[0]
while resposta not in 'SN':
resposta = str(input('Desculpe não entendi. Você quer continuar? [S/N] ')).strip().upper()[0]
if resposta == 'N':
break
else:
print('Tente novamente. ', end='')
print('\nFim do Programa!')
| false |
3318414d699a1aeb34cdec4746ad78bc59b49789 | luccaaltomani/Python | /aula_09.01.py | 653 | 4.28125 | 4 | nome = 'Chaves'
mensagem = 'ninguém tem paciência comigo'
# Concatenar textos e variáveis: separando por vírgula
print(nome, 'diz', mensagem) # não precisa usar espaços
# Concatenar textos e variáveis: separando por +
print(nome + 'diz:' + mensagem)
print(nome + ' diz: ' + mensagem) # precisa usar espaços
#######################
# A entrada de dados é realizada pela função input(), porém é necessário solicitar qual dado será digitado. O input()
# já permite escrever um texto, cuja resposta será atribuída à variável
nome = input('Olá, qual o seu nome? ')
print('Seja bem-vindo,', nome)
| false |
cd0f37e37245f18c9b439203540d00d3ba4ef1a9 | CharlotteBones/Msc-Coursework | /ISD/ISD-CW1.py | 2,299 | 4.21875 | 4 | #1) Refactor the following conditional without using any boolean operators (note: this will increase the number of branches)
# units = input("Please input units, either miles or km ")
# speed = int(input("Now input your speed as a whole number "))
# if (units == "miles" and distance > 100) or (units == "km" and distance > 161):
# print("Too Far")
# else:
# print("OK")
units = input("please input units, either miles or km ")
distance = int(input("please input the distance you wish to travel as a whole number "))
if units == 'miles':
if distance > 100:
print('Too Far')
else:
print('OK')
elif units == 'km':
if distance > 161:
print('Too Far')
else:
print('OK')
#2) Refactor the following code to reduce the number of branches.
# a = input("please input y or n or c")
# b = input("please input y or n or c")
# if a=="y":
# if b == "y":
# output = "OK"
# elif b == "n":
# output = "OK"
# else:
# output = "OK"
# elif a == "n":
# if b == "c":
# output = "OK"
# else:
# output = "Not OK"
# else:
# output = "Not OK"
# print(output)
a = input("please input y or n or c: ")
b = input("please input y or n or c: ")
if a == "y":
output = "OK"
elif a == "n" and b == "c":
output = "OK"
else:
output = "Not OK"
print(output)
#3) Write a program that asks for a mammal, either dog or human, and then
# an age in months.
# A basic program to determine the life stages of either a dog or a
# human using if-else statments and implements basic error checking.
mammal = input('Please input the either (d)og or (h)uman: ')
age = input('Please input the age in whole months: ')
lifeStage = ''
if mammal != 'd' and mammal != 'h':
print('You have entered at least one input incorrectly')
elif age.isdigit() == False:
print('You have entered at least one input incorrectly')
else:
age = int(age)
if mammal == 'h':
if age < 132:
lifeStage = 'Juvenile'
elif age < 300:
lifeStage = 'Adolescent'
elif age < 588:
lifeStage = 'Mature'
else:
lifeStage = 'Senior'
elif mammal == 'd':
if age < 6:
lifeStage = 'Juvenile'
elif age < 24:
lifeStage = 'Adolescent'
elif age < 84:
lifeStage = 'Mature'
else:
lifeStage = 'Senior'
print(lifeStage)
| true |
b010c50e84115ee9d4640e895a814f4f384aeb77 | lauranewland/hb-homework | /accounting-scripts/melon_info.py | 494 | 4.1875 | 4 | """Print out all the melons in our inventory."""
from melons import melon
def print_melon(melon):
"""Print each melon with corresponding attribute information."""
for key, values in melon.items(): #loops through the Key(Melon Names) with the values listed in a dictionary
print(key)
for attribute, value in values.items(): #loops each attribute(price, weight, flesh color, etc...)
print(f" {attribute} : {value}")
print_melon(melon)
| true |
21ba7c44130ac0b8cf9166738c005d6a37936fb3 | MurtazaBadshah121/python_LoginSystemDbStorage | /Database_helper.py | 736 | 4.5625 | 5 | import sqlite3
with sqlite3.connect("user.db") as db:
cursor = db.cursor()
# This statement creates the database tables
# cursor.execute('''
# CREATE TABLE IF NOT EXISTS user(
# user_ID INTEGER PRIMARY KEY,
# Email VARCHAR(20) NOT NULL,
# password VARCHAR(20) NOT NULL,
# access_Count INTEGER DEFAULT 0)
# ''')
# This statement is used to enter values into the table for testing
# cursor.execute('''
# INSERT INTO user(Email, password)
# VALUES("mb", "12345")
# ''')
# This statement deletes the table
# cursor.execute('''
# DROP table user
# ''')
# This statement deletes all data from user table
# cursor.execute('''DELETE FROM user''')
db.commit()
cursor.execute('''
SELECT * FROM user
''')
print(cursor.fetchall()) | true |
75d9efa0cea5169a63ca374bedf73b982d64681e | aquatiger/LaunchCode | /class point.py | 1,101 | 4.15625 | 4 | import math
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
""" Create a new point at the given coordinates. """
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return math.sqrt((self.x ** 2) + (self.y ** 2))
def reflect(self, v, w):
return (v, -w)
def slope(self, otherP):
try:
return (otherP.getY() / otherP.getX())
except:
return None
def move(self, z, a): #These are units of measurement, not coordinates
self.x += z
self.y += a
return (self.x, self.y)
def distanceFromPoint(self, otherP):
dx = (otherP.getX() - self.x)
dy = (otherP.getY() - self.y)
return math.sqrt(dy**2 + dx**2)
p = Point(3, 3)
q = Point(0, 7)
print(p.getX())
print(p.getY())
print(q.reflect(3, -5))
print(q.slope(q))
print(p.distanceFromPoint(q))
print(p.move(0, 7))
| true |
0abd1ef228a141096fee47f6e0f843ef0186a7a9 | Wasacuti/telnet-python | /holamundo/hola.py | 1,617 | 4.15625 | 4 | print("************************************")
print("*************Calculadora************")
print("************************************")
continuar="s";
while continuar == "s":
menu = """
1 - Suma
2 - Resta
3 - Multiplicación
4 - División
5 - Salir
"""
print(menu)
res=0;
opc=int(input("Ingrese su opción: "))
if opc == 1:
print("SUMA")
num1=int(input("Ingrese el número 1:"))
num2=int(input("Ingrese el número 2:"))
res=num1+num2
print("La suma de los dos números es: ", res)
continuar=input("Desea continuar S/N: ")
continuar=continuar.lower()
elif opc == 2:
print("Resta")
num1=int(input("Ingrese el número 1:"))
num2=int(input("Ingrese el número 2:"))
res=num1-num2
print("La resta de los dos números es: ", res)
continuar=input("Desea continuar S/N: ")
continuar=continuar.lower()
elif opc == 3:
num1=int(input("Ingrese el número 1:"))
num2=int(input("Ingrese el número 2:"))
print("Multiplicación")
res=num1*num2
print("La multiplicación de los dos números es: ", res)
continuar=input("Desea continuar S/N: ")
continuar=continuar.lower()
elif opc == 4:
num1=int(input("Ingrese el número 1:"))
num2=int(input("Ingrese el número 2:"))
print("División")
res=num1/num2
print("La División de los dos números es: ", res)
continuar=input("Desea continuar S/N: ")
continuar=continuar.lower()
elif opc == 5:
continuar="N"
else:
print("opción invalida")
print ("Hasta luego")
| false |
d3181dc6be1f910401c73eb3691f11316d84d259 | simisola88/my-pyhtoncodes | /ex39.py | 1,402 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 3 10:05:09 2019
@author: smile
"""
#create a mapping of state to abbrevaition
states ={
'Oregon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI'
}
#create a basic set of states cities
cities={
'CA':'Francisco',
'MI':'Detroit',
'FL':'Jacksonville'
}
#add some more cities
cities['NY']='New York'
cities['OR']='Portland'
#print out some cities
print('*'*11)
print ("NY states has: "+cities['NY'] )
print ("OR states has: "+cities['OR'] )
#print out cities by using states
print('*'*11)
print ("Michigan has: "+cities[states['Michigan']] )
print ("Florida has: "+cities[states['Florida']] )
#print every states in states
print('*'*11)
for state,abr in states.items():
print("%s is abreviaites %s"%(state,abr))
#print every cities in cities
print('*'*11)
for city,abr in cities.items():
print("%s is abreviaites %s"%(abr,city))
#print boths states and
print('*'*11)
for state,abr in states.items():
print("%s is abreviaites %s with city %s"%(state,abr,cities[abr]))
#print every states in states
print('*'*11)
state = states.get('Texas')
#print(state)
#check if a state is in the dictionary
if not state:
print("Sorry, no Texas")
city = cities.get('Texas','Does not exist')
print("Texas city is %s"%city)
| false |
e0c5666cebe820c2a517fbad74c7a0d5644e8341 | PJC-1/data_structures_and_algorithms_in_python | /Data_Structures/Strings/anagram_checker.py | 509 | 4.3125 | 4 | def anagram_checker(str1, str2):
"""
Check if the input strings are anagrams of each other
Args:
str1(string),str2(string): Strings to be checked
Returns:
bool: Indicates whether strings are anagrams
"""
# TODO: Write your solution here
if len(str1) != len(str2):
clean_str_1 = str1.replace(" ", "").lower()
clean_str_2 = str2.replace(" ", "").lower()
if sorted(clean_str_1) == sorted(clean_str_2):
return True
return False
| true |
c0f93f7704e6b39529ab9c53598fc0c5af0c3d90 | FlorianFeka/LinuxStuffCodingChallenge | /8_uniqueSteps.py | 746 | 4.34375 | 4 | # This problem was asked by Amazon.
# There exists a staircase with N steps, and you can climb up either 1 or 2
# steps at a time. Given N, write a function that returns the number of
# unique ways you can climb the staircase. The order of the steps matters.
# For example, if N is 4, then there are 5 unique ways:
# 1, 1, 1, 1
# 2, 1, 1
# 1, 2, 1
# 1, 1, 2
# 2, 2
# What if, instead of being able to climb 1 or 2 steps at a time,
# you could climb any number from a set of positive integers X? For example,
# if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
def getNumberOfUniqueWays(numberOfStairs, stepsAtATime):
pass
def makeSum(wantedSum, numbers):
return sum(numbers) == wantedSum
print(makeSum(3,[1,2]))
| true |
11b0ff799e8e03eb84b4e1f2ab94f11ffb44d95f | FabioniMacaroni/ASTR-119 | /astr-119-hw-2/variables_and_loops.py | 601 | 4.34375 | 4 | import numpy as np #we use numpy for many things
def main():
i = 0 # i is an integer, declared with a number 0
n = 10 # n is another integer
x = 119.0 #floating point numbers are declared with a .
# we can use numpy to declare arrays quickly
y = np.zeros(n, dtype=float)
# we can use for loops to iterate with a variable
for i in range(n): # i in range [0,n-1]
y[i] = 2.0 * float(i) + 1.0 #set y =2*i+1 as floats
#we can simply iterate through a variable array
for y_element in y:
print(y_element)
#execute the main function
if __name__=="__main__":
main() | true |
4e3dcf213d5e781f2b0eee5accdc2c7cfb049ae8 | roy19-meet/meet2017y1lab4 | /fruit_storer.py | 226 | 4.125 | 4 | fruit=input('what fruit am i sorting?')
if fruit == "apples":
print('bin 1')
elif fruit=='oranges':
print('bin 2')
elif fruit=='olives':
print('bin 3')
else:
print('error! i do not recognise that fruit')
| true |
b6e56036b7dad5334426a68f032315f7e4fa015d | sumankumar01/PythonProgramme | /mapp/map_intro.py | 292 | 4.21875 | 4 | text="what have the romens ever done for us"
capitals=[char.upper() for char in text]
print(capitals)
map_capitals=list(map(str.upper,text))
print(map_capitals)
words=[word.upper() for word in text.split(' ')]
print(words)
map_words=list(map(str.upper,text.split(' ')))
print(map_words)
| false |
30dd5c9bd0b776b8133f3c89cf9008bbe3dd1ba5 | s1ssagar/number_of_factors | /num_factors.py | 1,143 | 4.15625 | 4 | import math
def factors(num):
prime_fac = []
num_of_fac = []
# A number has factors only upto its Sqrt
max_fac = int(math.sqrt(num)+1)
for x in xrange(1, max_fac+1):
count = 0
if num % x == 0:
for y in xrange(1, x):
if x % y == 0:
count += 1
if count > 1:
break
if count == 1:
prime_fac.append(x)
for factor in prime_fac:
count = 0
while num % factor == 0:
count += 1
num = num / factor
num_of_fac.append(count)
# print prime_fac, num_of_fac
if prime_fac == [] and num == 0:
print "zero is the only integer that has infinitely many factors, and zero is the only integer that has zero for a factor."
elif prime_fac == [] and num != 1:
print "Number of factors are:", 2
else:
product = 1
for prod in num_of_fac:
product *= (prod+1)
print "Number of factors are:", product
def main():
factors(abs(input("Enter the number ")))
if __name__ == "__main__":
main() | true |
4f3537bbe97220a0536edc79801c4c10bc92f7ef | Dkilpatrick31/python_challenges | /fizzbuzz/fizzbuzz.py | 433 | 4.15625 | 4 | #""" This is my fizzbuzz program """
count = int(input('Gimme the top number: '))
def fizzbuzz(max_number):
# """ this is the fizzbuzz algorithm applied to the value x """
for x in range(1,max_number):
if x % 3 == 0:
print('fizz')
elif x % 5 == 0:
print('buzz')
elif x % 3 == 0 and x % 5 == 0:
print('fizzbuzz')
else:
print(x)
fizzbuzz(count)
| false |
78658a341e55e8e716c5baa9403b503eef90cc13 | anahiquintero99/Ejercicios-de-python | /estructura_datos.py | 2,551 | 4.46875 | 4 | # Hacer un programa para administrar una Lista de datos :
# 1. Insertar un elemento a la lista
# 2. Mostrar la lista
# 3. Buscar un elemento en la lista por nombre indicando la posición en la que lo encontró
# 4. Actualizar los datos de un elemento lista
# 5. Borrar un elemento de la lista .
# 6. Ordenar los datos de la Lista
# 7. Salir
def insert_element(element):
list_elements.append(element)
return list_elements
if __name__ == "__main__":
print('L I S T A S D E D A T O S ')
while True:
option = int(input('''
1. Insertar un elemento a la lista
2. Mostrar la lista
3. Buscar un elemento en la lista por nombre indicando la posición en la que lo encontró
4. Actualizar los datos de un elemento lista
5. Borrar un elemento de la lista .
6. Ordenar los datos de la Lista
7. Salir
'''))
if option == 1:
list_elements = []
while True:
element = input('Inserta un numero: ')
insert_element(element)
other_element = int(input('''
¿Deseas agregar otro elemnto a la lista?
[1] Si
[2] No
'''))
if other_element == 2:
break
elif option == 2:
try:
print('L I S T A C R E A D A')
print_list = (list_elements)
print(list_elements)
except NameError:
print('Aun no creas una lista, ingresa al punto uno para crearla sonso')
elif option == 3:
print('B U S C A R E L E M E N T O E N L I S T A ')
try:
element_found = input('Ingresa elemento a buscar: ')
position_element = list_elements.index(element_found)
print(f'El elemento {element_found} se encuentra en la posicion: {position_element}')
except ValueError:
print('Elemneto no encontrado en la lista')
# elif option == 4:
elif option == 5:
print('E L I M I N A R E L E M E N T O')
element_found = input('Ingresa elemento a eliminar: ')
position_element = list_elements.index(element_found)
list_elements.pop(position_element)
print(list_elements)
elif option == 6:
list_elements.sort()
print(list_elements)
| false |
a81eaa9894753b7e8ebd20fb72dcd2bfe49c7d0d | tualatint/abstract_gym | /utils/geometry.py | 1,108 | 4.125 | 4 | class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Line:
def __init__(self, p0, p1):
self.p0 = p0
self.p1 = p1
def compute_line_function(self):
"""
The function of the line should be in this form: ax + by + c = 0
:return: a, b, c
"""
if self.p0.x == self.p1.x: # vertical line
b = 0
a = 1
c = -self.p0.x
return a, b, c
if self.p0.y == self.p1.y: # horizontal line
a = 0
b = 1
c = -self.p0.y
return a, b, c
a = 1.0 / (self.p1.x - self.p0.x)
b = -1.0 / (self.p1.y - self.p0.y)
c = self.p0.y / (self.p1.y - self.p0.y) - self.p0.x / (self.p1.x - self.p0.x)
return a, b, c
class Square:
def __init__(self, pbl, pur):
"""
Define the square using two corner points
:param pbl: bottom left
:param pur: upper right
"""
self.min_x = pbl.x
self.min_y = pbl.y
self.max_x = pur.x
self.max_y = pur.y
| false |
abae66ef38a8e1111c4da64d1056b4525c396be1 | JessicaGarson/PBJ | /pbjwhilepart2.py | 1,738 | 4.1875 | 4 | # Goal #1: Write a new version of the PB&J program that uses a while loop. Print "Making sandwich #" and the number of the sandwich until you are out of bread, peanut butter, or jelly.
# Example:
#bread = 4
#peanut_butter = 3
#jelly = 10
# Example 2:
bread = 10
peanut_butter = 10
jelly = 4
bread_for_pbj = bread / 2
pbj_sandwiches = min(bread_for_pbj, peanut_butter, jelly)
sandwich_number = 0
jelly_remianing = 0
bread_reamining = 0
peanut_butter_remaining = 0
#Solution to Goal 1
#while (sandwich_number < pbj_sandwiches):
#sandwich_number +=1
#print "I'm making sandwich number {0}".format(sandwich_number)
#print "All done only had enough for {0} sandwiches".format(pbj_sandwiches)
# Output:
# Making sandwich #1
# Making sandwich #2
# All done; only had enough bread for 2 sandwiches.
# Goal #2: Modify that program to say how many sandwiches-worth of each ingredient remains.
#Solution to Goal 2
while (sandwich_number < pbj_sandwiches):
sandwich_number +=1
bread_reamining +=1
jelly_remianing +=1
peanut_butter_remaining +=1
print "I'm making sandwich number {0} \n I have bread for {1} sandwiches, enough peanut butter for {2} sandwiches and enough jelly for {3} sandwiches".format(sandwich_number, bread_reamining, peanut_butter_remaining, jelly_remianing)
# Output:
# Making sandwich #1
# I have enough bread for 4 more sandwiches, enough peanut butter for 9 more, and enough jelly for 3 more.
# Making sandwich #2
# I have enough bread for 3 more sandwiches, enough peanut butter for 8 more, and enough jelly for 2 more.
# Making sandwich #3
# I have enough bread for 2 more sandwiches, enough peanut butter for 7 more, and enough jelly for 1 more.
# Making sandwich #4
# All done; I ran out of jelly. | true |
46cb809a82cd18841e73cfbcd1107dd510544240 | AdiYap/Programming_I | /Prac_02/ascii_table.py | 266 | 4.15625 | 4 | character = str(input("Enter a character: "))
code = ord(character)
print("The ASCII code for {} is {}".format(character,code))
number = int(input("Enter a number between 33 to 127: "))
convert = chr(number)
print("The character for {} is {}".format(number,convert)) | true |
9c71fdcc528d2b294d2ddde63357daef0eb2d23c | hojunee/20-fall-adv-stat-programming | /sol5/ex11-4.py | 247 | 4.25 | 4 | def reverse_lookup(my_dict, value):
my_key = []
for elem in my_dict:
if my_dict[elem] == value:
my_key.append(elem)
return my_key
print(reverse_lookup({1:1, 2:1, 3:1}, 1))
print(reverse_lookup({1:1, 2:1, 3:1}, 2))
| true |
f9322d81c72d2ae4c7b621ce7c08e6b405fc18f7 | Chadzero/Python_Tuturials | /EDx6001/L5P2.py | 610 | 4.34375 | 4 | __author__ = 'Chad_Ramey'
# In Problem 1, we computed an exponential by iteratively executing successive multiplications. We can use the same
# idea, but in a recursive function.
# Write a function recurPower(base, exp) which computes baseexp by recursively calling itself to solve a smaller
# version of the same problem, and then multiplying the result by base to solve the initial problem.
def recurPower(base, exp):
'''
:param base: int or float
:param exp: int >= 0
:return: int or float, base^exp
'''
if exp == 0:
return 1
return(base * recurPower(base, exp - 1)) | true |
8ad3287c80602765e28b998931a2f3eba73876b8 | Chadzero/Python_Tuturials | /Project_Euler/001-Multiples_of_3_and_5.py | 1,069 | 4.28125 | 4 | #!/usr/bin/env python
# Name: 001-Multiples_of_3_and_5.py
#
# Problem
####################################################
# If we list all the natural numbers
# below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
####################################################
__author__ = 'Chad_Ramey'
import sys
def main():
args = sys.argv[1:]
if len(args) < 2:
print 'Usage: range divisor0 [divisor1, ...]'
sys.exit(1)
limit = int(args[0])
divisors = map(int, args[1:])
total = 0
numbers = []
for x in range(0, limit):
for y in divisors:
if x % y == 0:
numbers.append(x)
total += x
else:
continue
break
print "From 0 to %s the sum of numbers divisible by %s: is %d" % (limit, ", ".join(args[1:]), total)
print "These are the numbers: %s" % " ".join(map(str, numbers))
return
if __name__ == '__main__':
main()
# Consider switching over to using argparse | true |
a5e92ce834e67ffd91610da7ece758726ecfff5a | nikitaizmailov/Binary-and-Linear-Search-Algos | /binlinsearch.py | 985 | 4.21875 | 4 | # Practise try without looking! binary search and linear search models
# Both are iterative methods
# Binary search algorithm is faster and more efficient
list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
searched_number = 0
def binSearch(array, number):
lower_b = 0
upper_b = len(array) - 1
while lower_b <= upper_b:
mid_pos = (lower_b + upper_b) // 2
if array[mid_pos] == number:
return mid_pos
else:
if array[mid_pos] < number:
lower_b = mid_pos + 1
else:
upper_b = mid_pos - 1
return None
test1 = binSearch(list1, searched_number)
if test1 is not None:
print("The number's position is ", test1 + 1)
else:
print("Position not found")
# Linear search algortihm Iterative!!!
def linSearch(array, number):
for i in range(len(array)):
if array[i] == number:
return i
else:
pass
return None
test2 = linSearch(list1, searched_number)
if test2 is not None:
print("The number's position is ", test2 + 1)
else:
print("Position not found")
| true |
917550b05a2bf1f5689c081a3142a7e6f6165cf7 | taison2000/Python | /sqlite3/sqlite3_add_data.py | 1,430 | 4.53125 | 5 | #!/Python34/python
#!/usr/bin/python
import sqlite3
# Connecting to the database file
## it will create the database if not exist
conn = sqlite3.connect( 'mytest.db' )
# A cursor is what to use to move around the database, execute SQL statement, and get data.
cursor = conn.cursor()
print( "Let's input some students!" )
while True:
name = input( "Student's name: ")
username = input( "Student's username: " )
id_num = input( "Student's id number: " )
sql = """INSERT INTO students
(name, username, id)
VALUES
(:st_name, :st_username, :id_num)
"""
cursor.execute( sql, {'st_name':name, 'st_username':username, 'id_num':id_num} )
# Committing changes to the database file
conn.commit() ## Not sure if this necessary ??
cont = input( "Another student? ")
if cont[0].lower() == 'n': break
# Closing the connection to the database file
cursor.close()
##-----------------------------------------------------------------------------
## NOTES:
"""
CREATE TABLE
cursor.execute("CREATE TABLE IF NOT EXISTS students (name, username, id);")
"""
##-----------------------------------------------------------------------------
"""
Resource :
- http://sebastianraschka.com/Articles/2014_sqlite_in_python_tutorial.html
- https://github.com/rasbt/python_reference/blob/master/tutorials/sqlite3_howto/code/create_new_db.py
"""
| true |
6a000ebf2c64ebbc852ab04ced14cc4acebf2e90 | taison2000/Python | /builtin_functions/func_sorted.py | 1,383 | 4.21875 | 4 | #!C:\Python34\python.exe
#!/Python34/python
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function - sorted
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sorted( iterable[, key] [, reverse] )
"""
import os
import time
##-----------------------------------------------------------------------------
def sorted_with_key():
"""
Use the key as method to sort.
"""
fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana']
## sorted by the length of list items
s1 = sorted(fruits, key=len)
# -> ['fig', 'apple', 'cherry', 'banana', 'raspberry', 'strawberry']
## sorted by uppercase
fruits = ['strawberry', 'Fig', 'apple', 'Cherry', 'raspberry', 'banana']
sorted_upper = sorted(fruits, key=str.upper) # ['apple', 'banana', 'Cherry', 'Fig', 'raspberry', 'strawberry']
sorted_normal = sorted(fruits) # ['Cherry', 'Fig', 'apple', 'banana', 'raspberry', 'strawberry']
return
##-----------------------------------------------------------------------------
def main():
a = 123
print ('%05s', a) # <- Leading empty spaces
print ('%05s', a) # <- Leading empty spaces
# with leading '0'
format( 1234, '05X' )
if __name__ == "__main__":
main()
##-----------------------------------------------------------------------------
"""
Resources:
-
"""
| true |
6bbd3f81596cf86231edbd8747fcebf6b97d7759 | taison2000/Python | /builtin_functions/func_map.py | 1,604 | 4.625 | 5 | #!C:\Python34\python.exe
#!/Python34/python
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function - map
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
map( function, iterable, ... )
equivalent of map implementation
def map( func, iterable ):
for i in iterable:
yield func(i)
"""
import os
import time
##-----------------------------------------------------------------------------
def map_lambda():
list_numbers = [4, 1, 9, 11]
result = map(lambda x: x**2, list_numbers)
# result == <map object at 0x02D53CD0>
print(list(result)) # [16, 1, 81, 121]
return
def map_lambda():
list_numbers1 = [4, 1, 9, 11]
list_numbers2 = [3, 23, 5, 4]
## Note: if two lists have different length, map will stop at the shortest one.
## Note: since lambda here takes 2 arguments, so provide 'list_numbers1' and 'list_numbers2'
result = map(lambda x, y: x+y, list_numbers1, list_numbers2)
# result == <map object at 0x02D53CD0>
print(list(result)) # [7, 24, 14, 15], number member added individually of the two list numbers. Not append two lists.
return
##-----------------------------------------------------------------------------
def main():
a = 123
print ('%05s', a) # <- Leading empty spaces
print ('%05s', a) # <- Leading empty spaces
# with leading '0'
format( 1234, '05X' )
return
if __name__ == "__main__":
main()
##-----------------------------------------------------------------------------
"""
Resources:
-
"""
| true |
9aee5a852c25a74ac7e46e445fec44c8a166e8ef | rodgers2000/Projects | /udacity/data-structures-and-algorithms/notes/basic-algorithms/binary-search.py | 1,403 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 14:23:45 2019
@author: mrodgers
"""
def binary_search(array, target):
start_index = 0
end_index = len(array) - 1
while start_index <= end_index:
mid_index = (start_index + end_index)//2 # integer division in Python 3
mid_element = array[mid_index]
if target == mid_element: # we have found the element
return mid_index
elif target < mid_element: # the target is less than mid element
end_index = mid_index - 1 # we will only search in the left half
else: # the target is greater than mid element
start_index = mid_element + 1 # we will search only in the right half
return -1
def binary_search_recursive_soln(array, target, start_index, end_index):
if start_index > end_index:
return -1
mid_index = (start_index + end_index)//2
mid_element = array[mid_index]
if mid_element == target:
return mid_index
elif target < mid_element:
return binary_search_recursive_soln(array, target, start_index, mid_index - 1)
else:
return binary_search_recursive_soln(array, target, mid_index + 1, end_index)
| true |
4fba33657376efc34928f37d84fd8c2c9315cf42 | Warwickc3295/CTI110 | /M4T2_Warwick.py | 882 | 4.28125 | 4 | # CTI-110
# M4T2 - Python Exercise
# Cameron Warwick
# 10/2/17
def main():
# Ask the user for a string
tag = input('Please input an HTML tag: ')
#If it's one of the tags, print what the tag is and an example of it's use
if tag == "p":
print('<p> is the paragraph tag.')
print('Example of use: <p>text</p>')
elif tag == "h1":
print('<h1> is used to define HTML headings, h1 defines most the important.')
print('<h1>This is a heading</h1>')
elif tag == "b":
print('<b> is used to bold text')
print('<b>This text would be bold</b>')
elif tag == "div":
print('<div> is used to help divide the HTML document in to sections')
print('<div> Page elements would go between </div>')
else:
print('Sorry, tag not found.')
# else print ('Tag not found')
main()
| true |
9f157e3b3b8ee2919c1565e87cd8c0d5b686aec4 | JeanPaulLobat/Tarea-04 | /Mezclador de color.py | 1,616 | 4.125 | 4 | #encoding: UTF-8
#Jean Paul Esquivel Lobato
#Mátricula: A01376152
#Descripción: Imprime el color secundario resultante de la mezcla de dos números primarios.
#Hacer la mezcla de los colores
def mezclarColores(color,color2):
if (color == "amarillo" and color2 == "rojo") or (color2 == "amarillo" and color == "rojo"):
mezcla = "naranja"
elif (color == "amarillo" and color2 == "azul") or (color2 == "amarillo" and color == "azul") :
mezcla = "verde"
elif (color == "rojo" and color2 == "azul") or (color2 == "rojo" and color == "azul"):
mezcla = "morado"
elif color == color2 == "amarillo" or color == color2 == "rojo" or color == color2 == "azul":
mezcla = "iguales"
else:
mezcla = "invalido"
return mezcla
# Función principal
def main():
color = input("Escribe un color primario : ")
color2 = input("Esribe otro color primario: ")
color = color.upper()
color2 = color2.upper()
mezcla = mezclarColores(color,color2)
print ("""
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
""")
if mezcla == "iguales":
print ("Los colores son iguales")
elif mezcla == "invalido":
print ("¡ERROR! Los colores ingresados son invalidos")
else:
print("La mezcla de color primario: %s y color primario: %s, dan por resultado: %s" % (color,color2,mezcla))
main() | false |
299fe22626d35799ef48ed85dc58b5981729dab6 | aliciafmachado/drones-coordination | /src/decision_making/Node.py | 1,350 | 4.375 | 4 | class Node:
"""
Abstract Node class to use in graph algorithms.
"""
def __init__(self):
self.edges = []
def has_edge(self, node):
"""
Checks if there already is an edge to that node.
:param node:
:return: Boolean, True if the nodes are already connected.
"""
return node in self.edges
def add_edge(self, node):
"""
Adds an edge to the node.
:param node:
"""
if self.has_edge(node):
return
self.edges.append(node)
node.edges.append(self)
def dist(self, arg):
"""
Returns the distance to a certain object.
:param arg: Object to calculate distance. Can be Point, Pose, StablePose or MeshNode.
:return: float, distance to the object.
"""
raise NotImplementedError()
def __eq__(self, node):
"""
Checks if two nodes are equal.
:param node:
"""
raise NotImplementedError()
def __repr__(self):
"""
Used for printing node.
:return: String representing MeshNode.
"""
raise NotImplementedError()
def __hash__(self):
"""
Hash function to use in dicts.
:return: HashCode associated to Node.
"""
raise NotImplementedError()
| true |
09283d76e9d8e3099085b44c24898f2ce2817a1b | Cocomodd/image_sym_flip | /flip/text_functions.py | 1,027 | 4.25 | 4 | def flip(string_to_flip):
"""
Flips the given string
:param string_to_flip:
:return: string flipped
"""
return string_to_flip[::-1]
def get_half_str(string_to_half):
"""
Cuts the string in the middle and keeps the middle char if odd number
:param string_to_half:
:return: string halved
"""
if len(string_to_half) % 2 == 0:
return string_to_half[:len(string_to_half) // 2]
else:
return string_to_half[:len(string_to_half) // 2 + 1]
def sym_left(string_to_sym_left):
"""
Returns symmetric string from left side
:param string_to_sym_left:
:return: symmetric string
"""
half = get_half_str(string_to_sym_left)
if len(string_to_sym_left) % 2 == 0:
return half+flip(half)
else:
return half+flip(half[:-1])
def sym_right(string_to_sym_right):
"""
Returns symmetric string from left side
:param string_to_sym_right:
:return: symmetric string
"""
return sym_left(flip(string_to_sym_right))
| true |
f9d0fcbc74f63ae4e3503503c81ae672bcc0d579 | sanjbaby/aby | /code/Aby_Code/survey.py | 346 | 4.1875 | 4 | my_name = "Aby"
my_age = "9 years old"
your_name = input("What is your name? ")
your_age = input("How old are you? ")
print("My name is", my_name, ", and I am", my_age, "years old.")
print(your_name, "what a nice name ! and ", your_name, "you are young !", "only", your_age, "years old")
print("Thank you for taking this survey,", your_name, "!") | true |
edef2f6948d29d3883ad5b8860be6056c07107ec | Audarya07/Daily-Flash-Codes | /Week12/Day3/Solutions/Python/prog2.py | 220 | 4.4375 | 4 | string = input("Enter string:")
sub = input("Enter substring to find:")
if sub in string:
print("The entered string consists",sub,"as substring")
else:
print("The entered string does not consist the substring")
| true |
c00816869eb7ef2c7c4e510e144ad8a43b4c35cc | Audarya07/Daily-Flash-Codes | /Week10/Day3/Solutions/Python/prog3.py | 225 | 4.125 | 4 | from numpy import array
n = int(input("Enter length of array:"))
arr = array([int(i) for i in input().split()][:n])
print("Array before swapping:",*arr)
arr[0], arr[-1] = arr[-1], arr[0]
print("Array after swapping:",*arr)
| false |
132b3c6afc71306bfc40e81ef0e10f1899dbcd0a | Audarya07/Daily-Flash-Codes | /Week12/Day2/Solutions/Python/prog3.py | 279 | 4.25 | 4 | import numpy as np
rows = int(input("Enter number of rows:"))
cols = int(input("Enter number of columns:"))
print("Enter elements:")
elements = [int(i) for i in input().split()]
matrix = np.array(elements).reshape(rows,cols)
print("Diagonal Elements:",*matrix.diagonal())
| true |
576dd616b2c05708a7b0d5a7e909e2053cd3d4ec | Audarya07/Daily-Flash-Codes | /Week12/Day3/Solutions/Python/prog5.py | 258 | 4.125 | 4 | n = int(input("Enter n:"))
r = int(input("Enter r:"))
def fact(num):
fact = 1
for i in range(num,0,-1):
fact *= i
return fact
per = fact(n) / fact(n-r)
print("There are",int(per),"ways to distribute",r,"medals amongst",n,"employees")
| false |
3668a7cbd663c0016dfc669fcea2211246b3ee78 | yitelu/FCC_advPython | /build_in_examples/the_sorted.py | 398 | 4.28125 | 4 | # sorted() Returns a sorted list
"""
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
"""
num = [5, 4, 3, 2, 1]
print(sorted(num))
print(sorted(num, reverse=True)) | true |
faf9b13060004a2b3313dff0b1ec9e479356c2aa | yitelu/FCC_advPython | /heySets.py | 1,268 | 4.28125 | 4 | # Sets: unordered, mutable, no duplicates!
# like dict use {} but no key-value pair, just separate with comma
#not allow duplicates, so only 1,2,3 would print
myset = {1, 2, 3, 1, 2}
print(myset)
########
# nice trick to find out how many different characters in a words.
myset = set("hello")
print(len(myset))
# print 4 due to l is dup and order doesn't matter
#####
# if what to have a empty set need to use a SET method
emptySet = set()
print(type(emptySet))
#####
# add and remove the set
addtheset = set()
addtheset.add(1)
addtheset.add(2)
addtheset.add(3)
#no error if no such element in the set
addtheset.discard(4)
print(addtheset)
##############
for i in addtheset:
print(i)
#############
# union and intersection method in SET
odds = {1,3,5,7,9}
evens = {0,2,4,6,8}
primes = {2,3,5,7}
u = odds.union(evens)
print(u)
i = evens.intersection(primes)
print(i)
##################
# return diff
setA = {1,2,3,4,5,6,7,8,9}
setB = {1,2,3,10,11,12}
diff = setA.difference(setB)
print(diff)
print(type(diff))
###################
# frozenset is just the normal set but it's a immutable version of set.
# can't change the frozenset after its created.
a = frozenset([1,2,3,4])
print(a)
#add or remove won't work on the frozenset
#a.remove()
#a.add() | true |
15bedcacbf6c3ea076da59e28babc473bf33b8db | yitelu/FCC_advPython | /build_in_examples/the_abs.py | 766 | 4.125 | 4 | # the abs() function
"""
abs(x, /)
Return the absolute value of the argument.
"""
#In mathematics, the absolute value or modulus of a real number x, denoted |x|,
# is the non-negative value of x without regard to its sign. Namely,
# |x| = x if x is positive, and |x| = −x if x is negative, and |0| = 0.
# For example, the absolute value of 3 is 3, and the absolute value of −3 is also 3.
#show the absolute number
print(abs(-3))
#turn -3 in to positive number 3
# dir(__builtins__) that would include the builtin-constant, builtin-exceptions, and builtin-functions
print(dir(__builtins__))
#check out all the function use in the abs function
print(dir(abs))
#or use help to check the description of that function in their help file.
print(help(abs))
| true |
73d25ae4366ee244269602d7db905d3170dd3fc7 | yitelu/FCC_advPython | /build_in_examples/the_divmod.py | 403 | 4.125 | 4 | # divmod() Returns the quotient and the remainder when argument1 is divided by argument2
"""
divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
"""
#quotient = 5, remainder = 0
print(divmod(10, 2))
#quotient = 3, remainder = 1
print(divmod(10, 3))
#quotient = 2, remainder = 2
print(divmod(10, 4))
#quick assignment, a = 3, b = 1
a, b = divmod(10, 3)
print(a)
print(b) | true |
2b3edb12140d33651769421f3c415856f753c14f | yitelu/FCC_advPython | /heyTuples.py | 2,030 | 4.1875 | 4 | # Tuple: ordered, immutable, allows duplicate elements (size smaller and more efficient)
# Lists: ordered, mutable, allows duplicate elements
# Tuple can't be change change after its created (hence immutable)
import sys, timeit
myTuple = ("Max", 28, "Boston")
print(myTuple)
#######
#if only 1 element in the Tuple and need to put the comma in the end.
myTuple2 = ("Max", )
print(type(myTuple2))
########
#build in tuple function
myTuple3 = tuple(["max", 29, "SJ"])
print(myTuple3)
item = myTuple3[2]
print(item)
for x in myTuple3:
print(x)
if "john" in myTuple3:
print("yes")
else:
print("no")
#TypeError: 'tuple' object does not support item assignment (immutable)
#myTuple3[0] = "TOM"
###########
my_tuple = ('a', 'p', 'p', 'l', 'e')
print(len(my_tuple))
print(my_tuple.count("p"))
#return 1st occurrence of p
print(my_tuple.index('p'))
#convert tuple to list and convert from list back to list:
my_list = list(my_tuple)
print(type(my_list))
my_new_tuple = tuple(my_list)
print(type(my_new_tuple))
###################
#tuple slicing
a = (1,2,3,4,5,6,7,8,9)
b = a[1:3]
print(b)
####################
#unpacking in python:
my_tuple = "Max", 28, "Boston"
name, age, city = my_tuple
print(name)
print(age)
print(city)
#beware that the number of element for unpacking must match the tuple!!!
# due to valueError: too many values to unpack (expected 2)
######
#unpacking technics
my_tuple2 = (0, 1, 2,3, "JOHN",)
i1, *i2, i3 = my_tuple2
print(type(i1))
print(type(i3))
#i2 would become the list of [1,2,3] !!! good technics
print(i2)
########
#explain why TUPLE is MORE efficient than list!
my_list1 = [0,1,2,"hello", True]
my_tuple1 = (0,1,2,"hello", True)
print(sys.getsizeof(my_list1), "bytes")
print(sys.getsizeof(my_tuple1), "bytes")
# list has the same elements as the tuple, but the tuple's size is smaller
# tuple is more efficient to iterate
print(timeit.timeit(stmt="[0,1,2,3,4,5]", number=1_000_000))
print(timeit.timeit(stmt="(0,1,2,3,4,5)", number=1_000_000)) #tuple won!
######## | true |
6bd4af98e6fad5f1d4c18d4e2953c2764b3067a4 | yitelu/FCC_advPython | /build_in_examples/the_callable.py | 836 | 4.1875 | 4 | # callable() Returns True if the specified object is callable, otherwise False
"""
callable(obj, /)
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances of classes with a
__call__() method.
"""
#functions are callables
#Classes are callables
#Methods (which are functions) are callable
#Instances of classes can even be turned into callables.
#can check if it's callable, use the "hasattr(bool, '__call__')"
#print false due to String is data type not a class, hence not callable
print(callable("hey"))
#only class type is callable, hence type() is callable
print(callable(type("hey")))
print(hasattr("hey", "__call__")) #String not callable
print(hasattr(int, "__call__")) #integer object is callable
print(hasattr([], "__call__")) #not callable
| true |
2a7980e6ab04e854bacb7baf7cb65e486ae047a6 | yitelu/FCC_advPython | /build_in_examples/the_len.py | 533 | 4.3125 | 4 | # len() Returns the length of an object
#
# len(obj, /)
# Return the number of items in a container.
"""
len(obj, /)
Return the number of items in a container.
"""
# beware need to check if such object has __len__ method or len would fail on that object
# like int object doesn't have __len__ could use dir(int) to check if __len__ exists
#print(len(123))
#print(dir(int))
# the list object has the __len__ dunder methods so the len method would work on list object like following:
#print(dir(list))
print(len([1, 2, 3, 4]))
| true |
5aae2310b185c1bad3a64bcf999e75aac5b0c940 | Alves-Eduarda/Colecoes | /Tuplas/aulapraticatupla.py | 914 | 4.25 | 4 | lanche = ('Hambúrguer','Pizza','Guaraná')
#mostra a posição de cada repetição
for c in range(0,len(lanche)):
print(lanche[c])
# não mostra a posição
for c in lanche:
print(c)
for pos,c in enumerate(lanche):
print(f"Eu vou comer {c} na posição {pos} ")
# uso do sorted - mostra em ordem
print(sorted(lanche))
# manipulação de duas tuplas
# o uso do + junta duas tuplas, cuidado com a ordem
a = (2,3,4,2)
b =(5,6,7)
c = a +b
print(c)
# metodos na tupla
# mostra quantas vezes aparece o número indicado
print(c.count(9))
# mostra qual é a posição do número indicado na tupla, pegando da primeira posição
print(c.index(6))
# deslocamento - mostra o número a partir da posição escolhida no segundo valor
print(c.index(2,1))
#podem existir dados de um tipo diferente dentro da tupla
# uso do del - deleta a tupla inteira, não tem como apagar apenas um elemento da tupla
del(c)
| false |
454bcb1d4c43453d71ba5f76d28224230abf685e | pouyapanahandeh/python3-ref | /python-HR/appTwo.py | 1,700 | 4.125 | 4 | # print index of string
str_one = 'python land is a place for everyone not just beginner'
# 012345
print(str_one[0]) # print the first letter of our string str-one
print(str_one[-1]) # pring the last letter of our string str_one
# print special range of string
print(str_one[0:4]) # reult will be from index 0 till index 4, index 4 is not included, only 4 index is included.
print(str_one[0:]) # start from index 0 till end and will print whole string
print(str_one[1:]) # same as above just start from index 1
# f string in python, good for concat multiple string
first_name = 'pooya'
last_name = 'panahandeh'
message = f'{first_name} [{last_name}] is a beginner programmer.' # f string is a method to manipulate the string
print(message)
# get the number of element of string
course = 'python is awsome'
print(len(course))
# change string to upper case
print(course.upper())
# change letter to lower case
course_two = "NODEJS PROGRAMMING"
print(course_two.lower())
# finding specific element in string
str_two = 'we are one of the best group of people'
print(str_two.find('g'))
# replace two words in string
print(str_two.replace('best', 'fucking best'))
print('one' in str_two) # checking if there the string we mentioned is exist in str_two or not, result will be true or false
# division and remainder operation in python
print(10 / 3) # result will be float
print(10 // 3) # result will be integer
# multiplication
print(10 * 2) # multiplication of two number
print(10 ** 2) # power of number
# assign variable to number and manipulate.
x = 10
# x = x + 4 short way in next line
x += 4
print(x)
# first multiplication then addition
z = 10 + 2 ** 2
print(z)
| true |
aa22ee0ca2acbb648cacdf5195229028975871fa | pouyapanahandeh/python3-ref | /python-HR/appSeven.py | 695 | 4.1875 | 4 | # for loop in python
# here we iterate through the string we defined
for item in 'pooya':
print(item)
# iterate through the array
for index in ['pooya', 'amir', 'flix']:
print(index)
for indexer in [1,2,3,4,5,6]:
print(indexer)
# range start from 0 to range < desire number, here is ten
for i in range(10):
print(i)
# using range include start from, till desire number, and stepping,. by using range we print even number from 2 to 9
for j in range(2, 10, 2):
print(j)
# sum up the number of array
prices = [6, 22, 33]
total = 0
for price in prices:
total += price
print(f'the Total is: {total}')
# nested for loop
for x in range(4):
for y in range(4):
print(f'({x},{y})')
| true |
3014312942b466ba3d61553e68f8f7bd6fd78814 | krishna-rawat-hp/PythonProgramming | /codes/stringisspace.py | 326 | 4.21875 | 4 | # String isspace method in python
# Example-1 blank white spaced string
str1= " "
print(str1.isspace())
# Example-2 only one space between two strings
str2 = "Krishna Rawat"
print(str2.isspace())
# Example-3 multi space in string
str3 = "krishna Kant rawat"
print(str3.isspace())
# Example-4 \n and \t
str4 = "\n \t \n"
print(str4.isspace()) | false |
27c51057686a1c1c21a777ee535afc99620eb19c | krishna-rawat-hp/PythonProgramming | /codes/listvstuple2.py | 251 | 4.25 | 4 | # Python list VS tuple program2
# Example-1 print both
lst = [1,2,3,4,5,6]
tup = (1,2,3,4,5,6)
print("List Element: ",lst)
print("Tuple Element: ",tup)
# Example-2 Reassignment in both
lst[3] = 5
print("List: ",lst)
tup[3] = 5
print("Tuple: ",tup) | false |
7ac87931b544569c6f8540f0ecd13720b7e4930a | krishna-rawat-hp/PythonProgramming | /codes/stringisupper.py | 291 | 4.59375 | 5 | # String isupper method in python
# Example-1 simple uppercase string
str1 = "PYTHON PROGRAMMING"
print(str1.isupper())
# Example-2 mixed case string
str2 = "Hello WORLD"
print(str2.isupper())
# Example-3 special, numeric and uppercase string
str3 = "134 #$% PYTHON"
print(str3.isupper()) | true |
3e0a8a75be3e262dc66681a40595584c368d059d | krishna-rawat-hp/PythonProgramming | /codes/set11.py | 353 | 4.40625 | 4 | # Python set operations
# Example-1 difference of two sets using (-) operator
set1 = {"Krishna","Hemant","Raja","Atul","mehta"}
set2 = {"Rahul","Mohan","Krishna","Hemant"}
print("difference of two sets (-): ",set1-set2)
# Example-2 difference of two sets using difference() method
print("difference of two set (difference()): ",set1.difference(set2))
| true |
f3160da61334d86098183a592f9ce97062013936 | krishna-rawat-hp/PythonProgramming | /codes/set5.py | 216 | 4.5 | 4 | # Python set addition
# Example-1
set1 = {"january","february","march","april","may","june","july"}
print("Before Adding Months: ",set1)
set1.add("august")
set1.add("september")
print("After adding Months: ",set1)
| true |
6524b6c8324823f65536b9d34070d7584ef6469a | krishna-rawat-hp/PythonProgramming | /codes/tuple5.py | 356 | 4.28125 | 4 | # Python tuple accessing with indexing
tup = (1,2,3,4,5,6)
# Example-1 in range indexing
print("accessing 1,3,4,5 indexes: ",tup[1]," ",tup[3]," ",tup[4]," ",tup[5])
# Example-2 negetive indexing
print("accessing -5,-3,-2,-1 indexes: ",tup[-5]," ",tup[-3]," ",tup[-2]," ",tup[-1])
# Example-3 out of range indexing
print("Acees out of range: ",tup[6])
| false |
fab351e253b40634984d04a8cf1779fa5ee6ba71 | krishna-rawat-hp/PythonProgramming | /codes/set8.py | 316 | 4.59375 | 5 | # Python set operations
# Example-1 union of two sets using | operator
set1 = {"Krishna","Hemant","Raja","Atul","mehta"}
set2 = {"Rahul","Mohan","Krishna","Hemant"}
print("Union of two sets (|): ",set1|set2)
# Example-2 Union of two sets using union() method
print("Union of two set (union()): ",set1.union(set2))
| false |
239b771f84bbbb0fe518ee899721565cb1fbfa8a | krishna-rawat-hp/PythonProgramming | /codes/stringreplace.py | 611 | 4.5625 | 5 | # String replace method in python
# Example-1 simple replace
str1 = "Java is a good programming language"
print("old string:", str1)
print("new string:", str1.replace("Java","Python"))
# Example-2 multi replace
str2 = "C C++ JAVA C# JAVA PYTHON C# JAVA"
print("old string:", str2)
print("new string:", str2.replace("JAVA", "PYTHON"))
# Example-3 counted replaces
count = 1
print("old string:", str2)
print("new string:", str2.replace("JAVA", "PYTHON", count))
# Example-3 replace whole string
str3 = "adfgf hgf jhfsj"
strr = "Krishna Kant Rawat"
print("old string:", str3)
print("new string:", str3.replace(str3, strr)) | true |
f9beaaa356f1647265978c17e7e75528877fead5 | krishna-rawat-hp/PythonProgramming | /codes/listvstuple3.py | 276 | 4.21875 | 4 | # Python list VS tuple eay debugging
# Example-1
lst = [1,2,3,4,5,6]
tup = (1,2,3,4,5,6)
print("List Element: ",lst)
print("Tuple Element: ",tup)
lst1=lst
lst[3] = 5
print("List1: ",lst1)
print("List: ",lst)
tup1 = tup
print("Tuple1: ",tup1)
tup[3] = 5
print("Tuple: ",tup) | false |
492d5b3a949467f53e8a1284b7bb42e3e42cf3fd | krishna-rawat-hp/PythonProgramming | /codes/stringistitle.py | 251 | 4.15625 | 4 | # String istitle method in python
# Example-1 title cased string
str1 = "Krishna Kant Rawat"
print(str1.istitle())
# Example-2 normal string
str2 = "Krishna kant rawat"
print(str2.istitle())
# Example-3 spacial, numeric characters
str3 = "123 #$% 56"
print(str3.istitle()) | true |
92625ef5fbec950153ad9607207960fb4ba8621e | krishna-rawat-hp/PythonProgramming | /ifelse/codes/ifexample2.py | 284 | 4.125 | 4 | a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a>b and a>c:
print("The largest number is a..")
if b>a and b>c:
print("The largest number is b..")
if c>a and c>b:
print("The largest number is c..")
| false |
cacc2650c5f00a13252bdd3f0eb204a763257c2a | Kate-CCRi/Advent-of-Code-2019 | /Day 01/day01.py | 1,087 | 4.25 | 4 | # import the math module so you can use it later
import math
# this is a function that forces it to round down rather than up
def round_down(n, decimals=0):
multiplier = 10 ** decimals
return math.floor(n * multiplier) / multiplier
# read in the data file and split it into lines
data = open("input.txt")
lines = data.readlines()
# PART ONE
# a global variable to hold the total
total1 = 0
total2 = 0
# for each line
for line in lines:
# convert it from a string to a float
line_num = float(line)
# do the required math operations
mass = line_num / 3
mass = round_down(mass)
mass = mass - 2
# a testing output step
print(mass)
#add the resulting mass to the total
total1 += mass
# calculate the additional fuel needs for part 2
extra = mass
while extra > 0:
total2 += extra
extra = extra / 3
extra = round_down(extra)
extra = extra - 2
# print the final result
print(f"The part one fuel requirements are: {str(total1)}")
print(f"The part two fuel requirements are: {str(total2)}")
| true |
0eefacf3c4ed851c8bd1b0acbf7b14190e00bb81 | StaticNoiseLog/python | /basics/decimal_to_any_number_system.py | 463 | 4.21875 | 4 | def convert(decimal, target_base):
if decimal <= 0:
return ""
remainder = decimal % target_base
integer_part = decimal // target_base
return convert(integer_part, target_base) + str(remainder)
target_base = int(input("Target number base: "))
decimal = int(input("Decimal number to convert: "))
print("{decimal} dec in base {base} is {result}".format(decimal=decimal, base=target_base, result=convert(decimal, target_base)))
| false |
35997eb19daad0d3190d04e148dae5b7afb01e15 | Lev1sDev/leetcode_problems | /ok_linked_list_reverse_2.py | 1,770 | 4.15625 | 4 | """
92. Reverse Linked List II
Medium
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
Runtime: 24 ms, faster than 96.70% of Python3 online submissions for Reverse Linked List II.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Reverse Linked List II.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
def reverse(head: ListNode, k: int) -> ListNode:
p_node = None
t_node = head
while k >= 0 and t_node:
f_node = t_node.next
t_node.next = p_node
p_node = t_node
t_node = f_node
k -= 1
head.next = t_node
return p_node
k = n - m
if k == 0:
return head
node = head
if m == 1:
return reverse(node, k)
while m > 2: # since arr starts from 1
node = node.next
m -= 1
node.next = reverse(node.next, k)
return head
if __name__ == '__main__':
def get_list_repr(node):
values = []
while node:
values.append(node.val)
node = node.next
return '->'.join(map(str, values))
head = ListNode(1)
node = head
for x in range(2, 3):
node.next = ListNode(x)
node = node.next
print('Before:', get_list_repr(head))
head = Solution().reverseBetween(head, 1, 2)
print('After: ', get_list_repr(head))
| true |
4680d5395ed69b3b632ff70684c508624596cc7f | maikellin/self-tightening-shoos | /testing.py | 997 | 4.28125 | 4 | def shoelace (tightness):
if tightness==1:
return "The tightness of your shoelaces is one"
elif tightness==2:
return "The tightness of your shoelaces is two"
elif tightness==3:
return "The tightness of your shoelaces is three"
elif tightness==4:
return "The tightness of your shoelaces is four"
elif tightness==5:
return "The tightness of your shoelaces is five"
elif tightness==6:
return "The tightness of your shoelaces is six"
elif tightness==7:
return "The tightness of your shoelaces is seven"
elif tightness==8:
return "The tightness of your shoeslaces is eight"
elif tightness==9:
return "The tightness of your shoelaces is nine"
elif tightness==10:
return "The tightness of your shoelaces is ten"
else:
return "Please put in a number from 1 to 10"
print(shoelace(int(input("From a scale of 1 to 10, how would you want the tightness of your shoes to be?")))) | true |
d888250b4f20b95ea69cd27872b46c28ace7bfe7 | ericjiang107/CodingTempleCodingQuestions | /Question4.py | 843 | 4.25 | 4 | """Write a function to return if the given year is a leap year. A leap year is divisible by 4, but not divisible by 100, unless it is also divisible by 400. The return should be boolean Type (true/false)"""
"Must be divisible by 4"
"Not divisible by 100 unless divisible by 400"
"Return True or False"
#for divisible, use modulo (no remainder)
#for not divisible, use modulo (a remainder)
#unless means another condition
#0 always read False, any other number reads True
#Whenever you use a condition, use if
#Can use if statement within if statement because first if reads true, continue to next if or else go to else statement
def is_leap_year(a_year):
if (a_year) % 4 == 0:
if (a_year) % 100 != 0:
return True
elif (a_year) % 400 == 0:
return True
return False
print(is_leap_year(1700))
| true |
c4c3fef12f5b808294be6711c83f5d504ab4cf34 | lauromoura/playground | /introalgo/sum_bit_array.py | 2,326 | 4.15625 | 4 | """Introduction to Algorithms, Third Edition
Problem 2.1-4 - Adding two integer as bit arrays"""
import sys
def add_integers(a, b):
"""Adds two integers (arrays of n bits) and returns an array of n+1 bits"""
# Specs: position [0] is the least significant bit. Position [n-1] is the
# most significant bit
# Loop invariant: Array of size i+1 with the result of two i bits numbers
# added
# Loop invariant initialization: The output array is of size 1 with zero,
# as no numbers have been added
output = [False]*(len(a) + 1)
for i, (x, y) in enumerate(zip(a, b)):
# Loop invariant maintenance: If i bits were processed, the loop
# invariant contains i+1 bits with the current sum. After the loop,
# the invariant contains i+1+1 contains the sum of i+1 bits
# Table:
# 0 + 0 + 0 = 0
# 1 + 0 + 0 = 1
# 1 + 1 + 0 = 0 (c 1)
# 1 + 1 + 1 = 1 (c 1)
has_carry = output[i]
output[i] = (x != y) != has_carry # Double xor
output[i+1] = (x and y) or ((x or y) and has_carry)
# Loop invariant termination: The output array of size i+1 has the sum of
# two arrays of i bits
return output
def fromBitArray(a):
x = 0;
for i, bit in enumerate(a):
x += bit * 2**i
return x
def toBitArray(x, size=10):
bits = []
bin_str = bin(x)[2:] # Remote the leading 0b
for i in bin_str[::-1]:
bits.append(bool(int(i)))
diff = size - len(bits)
bits += [False] * diff
return bits
def mergeArraySize(a, b):
max_len = max(len(a), len(b))
a.append([False]*())
def main():
one = toBitArray(1, 5)
two = toBitArray(2, 5)
three = toBitArray(3, 5)
five = toBitArray(5, 5)
eleven = toBitArray(11, 5)
twelve = toBitArray(12, 5)
twenty = toBitArray(20, 5)
twentysix = toBitArray(26, 5)
seven = toBitArray(7, 5)
fifteen = toBitArray(15, 5)
print fromBitArray(add_integers(one, one))
print fromBitArray(add_integers(one, two))
print fromBitArray(add_integers(two, two))
print fromBitArray(add_integers(eleven, twelve))
print fromBitArray(add_integers(twentysix, twenty))
print fromBitArray(add_integers(seven, fifteen))
if __name__ == '__main__':
main() | true |
75b5fe6d96b789fe092ca9ab51cdabe4e63b7dad | tanchekwei/alien-invasion | /python_work/squares.py | 712 | 4.21875 | 4 | squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
squares = []
for value in range(1,11):
squares.append(value**2)
squares = [value**2 for value in range(1,11)]
print(squares)
print(squares)
#Simple Statistics with a List of Numbers
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
#Exercise
for value in range(1,21):
print(value)
odd = []
for value in range(1,21,2):
print(value)
for value in range(3,31,3):
print(value)
multiple_3 = list(range(3,31,3))
print(multiple_3)
cube = []
for value in range(1,11):
cube.append(value**3)
print(cube)
cube = [value**3 for value in range(1,11)]
print(cube)
| true |
c9b8362f5312b77dfbcd46d8e17e5c176f329060 | tanchekwei/alien-invasion | /python_work/magicians.py | 455 | 4.28125 | 4 | #looping through an entire list
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
#Doing More Work Within a for Loop
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print("\n" + magician.title() + ", that was a good trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
#Doing Something After a for Loop
print("Thank you, everyone. That was a great magic show!")
| true |
2ba8d2b4dbc5afd7c1aa377f03611c30af2d49b9 | JinnnnH/LearningProgress-Python | /Python Lab1/Lab1 BMI/Lab1 BMI/Lab1_BMI.py | 351 | 4.28125 | 4 | #This program gives your BMI
height = float(input("Please input your height in meters: ")) #inputs can be in float
weight = float(input("Please input your weight in kg: ")) #inputs can be in float
BMI = weight/(height**2) #BMI = weight / height^2
print("Your BMI is: ", BMI) | true |
c475ffe85eae1724f718122eff496e9bcfde4781 | BenDosch/holbertonschool-higher_level_programming | /0x03-python-data_structures/3-print_reversed_list_integer.py | 299 | 4.28125 | 4 | #!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
if my_list:
for i in range(len(my_list)):
print("{:d}".format(my_list[-(i + 1)]))
def main():
test_list = [1, 2, 3, 4, 5]
print_reversed_list_integer(test_list)
if __name__ == "__main__":
main()
| false |
17ad1381fa0a8d94ec3d8425c83a7a58debad419 | 912-CUCONU-MARIA/FP | /src/lecture/livecoding/lecture_04/game.py | 1,555 | 4.21875 | 4 | """
Functions for the Tic Tac Toe game go here
These functions can call functions from board
There is no UI ! (communicate with params / exceptions)No UI
"""
from board import get_board_pos
from random import shuffle
def move_computer(board):
"""
Alternate computer strategies (read strategy from a file ??)
Strategy design pattern - https://en.wikipedia.org/wiki/Strategy_pattern
:param board:
:return:
"""
# return move_computer_first_position(board)
return move_computer_random_position(board)
# move_computer_prevent_human_win(board)
def move_computer_first_position(board):
"""
The computer moves in the first square it finds available
:param board: The game board
:return: (x,y) of computer move
"""
for row in range(3):
for col in range(3):
if get_board_pos(board, row, col) == 0:
return row, col
raise ValueError("No moves available")
def move_computer_random_position(board):
"""
The computer moves in a random, but valid square.
:param board:
:return:
"""
# TODO Computer wins if possible
choices_choices = []
for row in range(3):
for col in range(3):
if get_board_pos(board, row, col) == 0:
choices_choices.append((row, col))
shuffle(choices_choices)
return choices_choices[0]
def move_computer_prevent_human_win(board):
"""
The computer moves to prevent the human winning on the next move
:param board:
:return:
"""
pass
| true |
b45790d97c9d94557c81cf77db7b70c542ead3bf | 912-CUCONU-MARIA/FP | /src/seminar/group_912/seminar_04.py | 1,125 | 4.25 | 4 | """
Write a program that manages circles. Each circle has an (x,y) center (x,y - integers) and a the radius r
(r > 0, r is an integer). Functionalities will be available using a command-based UI:
1. Generate 'n' circles.
- n is a positive integer read from the keyboard.
- program generates and stores n distinct, random circles (distinct = at least one of x,y,radius must differ) ,
each completely enclosed in the square defined by corners (0,0) and (40,40)
2. Delete all circles from a given rectangle
- read rectangle data (x, y, width, height) # rect corner coordinates (x,y) - (x + width, y + height)
- delete all circles that are fully enclosed in this rectangle
3. Display all circle data on the console, sorted descending by radius
4. Exit
Requirements:
- handle input errors with exceptions
- unit test for 2. delete
Required modules:
circle.py (functions that work directly with circles)
functions.py (implement program functionalities)
console.py (user interface)
function calls
console.py -> function.py -> circle.py
-> circle.py
""" | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.