blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
92d209d4a9a200a2be4cee6c61d66892a10a08bb | koushik-chandra-sarker/PythonLearn | /a_script/f_Booleans.py | 462 | 3.71875 | 4 | print("========1=========")
print(5 > 4) # Output: True
print(5 == 4) # Output: False
print(5 < 4) # Output: False
print("========2=========")
print(bool("Hello")) # Output: True
print(bool(11)) # Output: True
bool(["apple", "cherry", "banana"])# Output: True
print("========3=========")
print(bool("")) # Output: False
print(bool(0)) # Output: False
print(bool(())) # Output: False
print(bool({})) # Output: False
print(bool([])) # Output: False
|
a13f132c3ac6e87e313570bcc86e470c096ae0b5 | koushik-chandra-sarker/PythonLearn | /a_script/o_Built-in Functions.py | 1,608 | 4.125 | 4 | """
Python Built-in Functions: https://docs.python.org/3/library/functions.html
or https://www.javatpoint.com/python-built-in-functions
"""
# abs()
# abs() function is used to return the absolute value of a number.
i = -12
print("Absolute value of -40 is:", abs(i)) # Output: Absolute value of -40 is: 12
# bin()
# Convert an integer number to a binary string prefixed with “0b”.
i = 5
print(bin(i)) # Output: 0b101
# sum()
x = sum([2, 5, 3])
print(x) # Output: 10
x = sum((5, 5, 3))
print(x) # Output: 13
x = sum((5, 5, 3), 10)
print(x) # Output: 23
x = sum((3 + 5j, 4 + 3j))
print(x) # Output: (7+8j)
# pow()
"""
pow(x, y, z)
x: It is a number, a base
y: It is a number, an exponent.
z (optional): It is a number and the modulus.
"""
print(pow(2, 3)) # Output: 8
print(pow(4, 2)) # Output: 16
print(pow(-4, 2)) # Output: 16
print(pow(-2, 3)) # Output: -8
# min() function is used to get the smallest element from the collection.
s = min(123, 2, 5, 3, 6, 35)
print(s) # Output: 2
s = min([10, 12], [12, 21], [13, 15])
print(s) # Output: 2[10, 12]
s = min("Python", "Java", "Scala")
print(s) # Output: java
s = min([10, 12, 33], [12, 21, 55], [13, 15], key=len)
print(s) # Output:[13,15]
# max() function is used to get the highest element from the collection.
s = max(123, 2, 5, 3, 6, 35)
print(s) # Output: 123
s = max([10, 12], [12, 21], [13, 15])
print(s) # Output: [13, 15]
s = max("Python", "Java", "Scala")
print(s) # Output: scala
s = max([10, 12, 33], [12, 21, 55, 9], [13, 15], key=len)
print(s) # Output:[12, 21, 55, 9]
|
0b2bea62a44bc4696c77b6f2b387c3235cadbc67 | koushik-chandra-sarker/PythonLearn | /a_script/p_Lambda.py | 266 | 3.78125 | 4 | """
A lambda function is a small anonymous function.
A lambda function can take any number of arguments
Limitation: can only have one expression.
"""
sum = lambda x, y: x + y
print(sum(5, 6)) # Output: 11
sub = lambda x,y: x-y
print(sub(10, 2)) # Output: 8
|
596f08af3fe1f2f0b3be54503071b133b543cabc | wangxin4278/store | /gaojicaiziyouxi.py | 409 | 3.65625 | 4 | import random
import time
num1 = random.randint(0, 101)
num = 5000
num0=1
while True:
num2=int(input("请输入数字:"))
if(num0<=5):
if (num2 >= num1):
num0=num0-1
print('猜对了现有金额为:', num)
else:
num0 = num0 + 1
num = num - 500
print('猜错了现有金额为:', num)
else:
time.sleep(2000)
|
64ebb368789ed8a5fb2b079e9853dc1e787ea1a7 | leandro-hl/python | /cadenas/4_1_capicua.py | 523 | 3.703125 | 4 | def esCapicua(cadena):
largo = len(cadena)
mitad = largo // 2
if(largo % 2 == 0):
return cadena[:mitad] == cadena[:mitad-1:-1]
else:
return cadena[:mitad] == cadena[:mitad:-1]
def main():
cadena = "Yo tengo un ojo de un color y otro de un color distinto"
palabras = cadena.split()
for palabra in palabras:
if(esCapicua(palabra)):
print(f"La palabra { palabra } es capicua.")
else:
print(f"La palabra { palabra } no es capicua.")
main() |
53319274e57b7f20d666664f2c195ac53ec58ccd | leandro-hl/python | /matrices/Trasnponer.py | 711 | 3.65625 | 4 | # Intercambiar filas por columnas
# Solo voy a admitir cambiar filas y columnas con el mismo indice
#Funciones
def intercambiarFilaYColumna(matriz, x):
for i in range(len(matriz)): # matriz cuadrada
aux = matriz[x][i]
matriz[x][i] = matriz[i][x]
matriz[i][x] = aux
matriz=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
intercambiarFilaYColumna(matriz, 1)
print(matriz)
#Transponer matriz
matriz=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
long = len(matriz)
for i in range(long):
for j in range(i):
aux = matriz[i][j]
matriz[i][j] = matriz[j][i]
matriz[j][i] = aux
for i in range(long):
print(matriz[i]) |
9885dc2361806599239214a33c4057f61507f245 | leandro-hl/python | /matrices/matrices_1_i.py | 952 | 3.53125 | 4 | import matrices_tools as tool
def MatrisEsSimetrica(matriz, esDiagonalPrincipal):
esSimetrica = True
area = len(matriz)
if(esDiagonalPrincipal):
for i in range(area):
for j in range(i):
if(esSimetrica and j != i and matriz[i][j] != matriz[j][i]):
esSimetrica = False
else:
for i in range(area, 0, -1):
for j in range(area-i):
if(esSimetrica and i != j):
iAEvaluar = area - (i + 1)
jAEvaluar = area - (j + 1)
if(matriz[i][j] != matriz[iAEvaluar][jAEvaluar]):
esSimetrica = False
print("La matriz es simetrica: ", esSimetrica)
def Main():
print()
#matriz = CrearMatrizAMano()
matriz = tool.CrearMatriz()
esDiagonalPrincipal = False
MatrisEsSimetrica(matriz, esDiagonalPrincipal)
Main() |
bb518f39c168fc64c8204076c3e2e4b9803944a5 | leandro-hl/python | /4_22_5_Archivos/ejemplo2.py | 204 | 3.546875 | 4 | fecha=[22,5,2020]
dia,*resto=fecha
dia=[dia]
print("La lista es:",fecha)
#print("Dia",dia,"Mes:",mes,"Año:",año)
print("Dia",dia,"Mes y año:",resto)
resto[0]=6
print("Resto",resto)
print("Lista",fecha) |
ceb491feae8660e30a40c502595e182283048021 | leandro-hl/python | /listas/1_d.py | 745 | 3.640625 | 4 | import random as r
# Determinar si el contenido de una lista cualquiera es capicúa, sin usar listas
# auxiliares. Un ejemplo de lista capicúa es [50, 17, 91, 17, 50].0,1,2,3,4
def EsCapicua(lista):
fin = -1
cantElementos = len(lista)
esCapicua = True
iteraciones = cantElementos // 2
if(cantElementos % 2 == 0):
iteraciones += 1
for i in range(iteraciones):
if(lista[i] != lista[fin]):
esCapicua = False
fin -=1
return esCapicua
def Main():
largoLista = int(input("Ingrese Largo lista"))
lista = []
for i in range(largoLista):
lista.append(int(input("Ingrese nro lista")))
print("su lista: ", lista)
print(EsCapicua(lista))
Main() |
b80c5a8f4f9a23befe7694f451965baa447081d4 | leandro-hl/python | /6_05_6_Diccionarios/TP7_ejercicio2.py | 639 | 3.984375 | 4 | # TP7 - ejercicio 2
# Desarrollar una función que reciba un número binario y lo devuelva convertido a base decimal.
# 1 0 1 1 -> 1*2**0 + 1*2**1 + 0*2**2 + 1*2**2 + 0
# cada recursividad resuelve un termino
def binarioDecimal(binario, exp=0):
'''Convertir a decimal.
Recibe un numero en binario'''
if binario == 0:
return 0
else:
digito = binario % 10
termino = digito * (2**exp)
return termino + binarioDecimal(binario//10, exp + 1)
binario=int(input("ingrese numero binario:"))
print(binario)
print(f"El numero {binario} en decimal: {binarioDecimal(binario)}")
|
5bfbe16edb5d230e5b4588b40eab33748629d2b9 | leandro-hl/python | /tp_integrador/ej1_p2.py | 964 | 3.65625 | 4 |
import tools as t
import random as r
# Crear una lista al azar, luego informar para cada valor,
# cuántas veces se repite(Utilizar el métodocount). El informe no debe repetir el número.
#Funciones
def EliminarOcurrenciasValorInformado(lista, numeroInformado, cantidadVeces):
for j in range(cantidadVeces):
lista.remove(numeroInformado)
def InformarValor(lista):
numeroAContar = lista[0]
cantidadVeces = lista.count(numeroAContar)
print("El numero: ", numeroAContar, " aparece ", cantidadVeces, " vez en la lista")
EliminarOcurrenciasValorInformado(lista, numeroAContar, cantidadVeces)
def GenerarInforme(lista):
while lista != []:
InformarValor(lista)
#Programa Principal
def Main():
cantidadElementos = r.randint(1, 100)
lista = t.CrearLista(True, cantidadElementos)
t.OrdenarDescendentementeListaNumerica(lista)
print("Lista creada: ", lista)
GenerarInforme(lista)
Main() |
4f0a9df8c1260a3d253611c13bd5dbda31828fde | leandro-hl/python | /Clase 3/Modulos/Ejemplo1/importparcial.py | 216 | 3.875 | 4 | from math import pi, degrees
from random import randint as aleatorio
print("2 pi radianes a grados:")
radianes = 2 * pi
grados = degrees(radianes)
print(grados)
print("Numero aleatorio:")
print(aleatorio(1,100))
|
97e2e7317e4e63e7da49967f834d641e93db752c | leandro-hl/python | /cadenas/4_5_filtrar.py | 1,396 | 4.03125 | 4 | #Escribir una función filtrar_palabras() que reciba una cadena de caracteres conteniendo
#una frase y un entero N, y devuelva otra cadena con las palabras que tengan
#N o más caracteres de la cadena original. Escribir también un programa para
#verificar el comportamiento de la misma. Hacer tres versiones de la función, para
#cada uno de los siguientes casos:
#a. Utilizando sólo ciclos normales
#b. Utilizando listas por comprensión
#c. Utilizando la función filter
def filtrar_palabras_ciclo(frase, min_caracteres):
"""
Version a: ciclos
"""
palabras = frase.split(' ')
nuevaFrase = []
for palabra in palabras:
if(len(palabra) > min_caracteres):
nuevaFrase.append(palabra)
return " ".join(nuevaFrase)
def filtrar_palabras_comprension(frase, min_caracteres):
"""
Version b: listas por comprensión
"""
palabras = frase.split(' ')
return " ".join([palabra for palabra in palabras if len(palabra) > min_caracteres])
def filtrar_palabras_flter(frase, min_caracteres):
"""
Version c: función filter
"""
palabras = frase.split(' ')
return " ".join(filter(lambda palabra: len(palabra) > min_caracteres, palabras))
def main():
frase = "Yo tengo un ojo de un color y otro de un color distinto"
minimo = 2
print(frase)
print(filtrar_palabras_flter(frase, minimo))
main() |
886715f02a0c80386c679882817bc53885eb30c1 | leandro-hl/python | /recursividad/tp_3.py | 141 | 3.578125 | 4 | def sumar(n):
if(n == 0):
return 0
return n + sumar(n-1)
def main():
n = 4
suma = sumar(n)
print(suma)
main() |
42d954d455970600a224ee327a4741a539a4734a | leandro-hl/python | /5_29_5_Recursividad/Ejemplo_rec6.py | 938 | 3.828125 | 4 | def contarVocalesIterativa(cad):
'''Cuenta cuantas vocales tiene una cadena en forma iterativa.'''
cont = 0
for letra in cad:
letra = letra.lower()
if letra in ['a','e','i','o','u']:
cont += 1
else:
cont += 0
return cont
def contarVocalesRecursivo(cad):
'''Cuenta cuantas vocales tiene una cadena en forma recursiva.'''
#cada iteracion va a analizar un caracter, el primero de la cadena que recibe
if len(cad)==0:
return 0
else:
letra = cad[0].lower()
if letra in ['a','e','i','o','u']:
return 1 + contarVocalesRecursivo(cad[1:])
else:
return 0 + contarVocalesRecursivo(cad[1:])
def main():
cadena = input("Ingrese una cadena:")
# print("Cantidad de vocales Iterativo:", contarVocalesIterativa(cadena))
print("Cantidad de vocales Recursivo:", contarVocalesRecursivo(cadena))
main() |
87dcf6f2ad171789589c8c4ef9e30ff1a7fed93c | leandro-hl/python | /matrices/matrices_1_k.py | 872 | 3.75 | 4 | # Determinar qué columnas de la matriz son palíndromos (capicúas), devolviendo
# una lista con los números de las mismas.
def obtenerColumnasCapicua():
matriz = [[1,2,3,2],
[2,1,3,2],
[1,1,3,2]]
columnasCapicuas = []
cantColumnas = len(matriz[0])
filasAEvaluar = len(matriz) // 2
for columna in range(cantColumnas):
inicio = 0
fin = -1
esCapicua = True
while esCapicua and inicio < filasAEvaluar:
if(matriz[inicio][columna] != matriz[fin][columna]):
esCapicua = False
else:
inicio += 1
fin -= 1
if(esCapicua):
columnasCapicuas.append(columna)
return columnasCapicuas
def Main():
matriz = []
columnasCapicuas = obtenerColumnasCapicua(matriz)
print(columnasCapicuas)
Main() |
644477c96e2a062b64077407c1b77b88b752a940 | leandro-hl/python | /test/HerenuLeandroEj2.py | 1,459 | 3.90625 | 4 | #Desarrollar un programa para que cree
#un conjunto de N elementos al azar
#entre A y B (N,A y B puede solicitarlos por teclado o crearlos al azar)
#Mostrar el conjunto creado por pantalla y
#luego informe la suma de sus elementos utilizando
#exclusivamente una función recursiva para sumar los valores.
import random as r
def crearConjunto():
#dado que no hay restricciones para los numeros creados, seteamos valores
#que no requieren muchas validaciones y son faciles de testear
cantidadElementosConjunto = r.randint(0, 100)
numeroDesde = r.randint(0, 20)
numeroHasta = r.randint(21, 40)
conjunto = set({})
for i in range(cantidadElementosConjunto):
ingresarAConjunto = r.randint(numeroDesde, numeroHasta)
if(ingresarAConjunto not in conjunto):
conjunto.add(ingresarAConjunto)
else:
i -= 1
return conjunto
def mostrarConjunto(conjunto):
mensaje = ' El Conjunto Creado Es '
mensaje.center(len(mensaje) + 6, '*')
print(mensaje)
print(conjunto)
def sumarConjunto(conjunto):
if(len(conjunto) == 0):
return 0
return conjunto.pop() + sumarConjunto(conjunto)
def mostrarSumaValoresConjunto(conjunto):
suma = sumarConjunto(conjunto)
print(f'La suma de los valores del conjunto es: { suma }')
def main():
conjunto = crearConjunto()
mostrarConjunto(conjunto)
mostrarSumaValoresConjunto(conjunto)
main() |
64dccfa80fdfdfcdd8b2dbe5c9591c0d7586408a | JoshGrant5/advent-of-code-2020 | /day_2.py | 3,898 | 3.890625 | 4 | # --- Day 2: Password Philosophy ---
# Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan.
# The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a look.
# Their password database seems to be a little corrupted: some of the passwords wouldn't have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen.
# To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set.
# For example, suppose you have the following list:
# 1-3 a: abcde
# 1-3 b: cdefg
# 2-9 c: ccccccccc
# Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.
# In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies.
# How many passwords are valid according to their policies?
def validate_password(passwords):
count = 0
for item in passwords:
# Break up each line
split_password = item.split()
# Grab the minimum and maximum number of instances for the key letter
instances = split_password[0]
split_instances = instances.split('-')
min_instances = int(split_instances[0])
max_instances = int(split_instances[1])
# Grab the key letter and the separated password
key = split_password[1]
password = split_password[2]
# Loop through password and count instances of the key letter
key_count = 0
i = 0
while i < len(password):
if password[i] == key[0]:
key_count += 1
i += 1
if key_count >= min_instances and key_count <= max_instances:
count += 1
return count
print(validate_password(passwords))
# The shopkeeper suddenly realizes that he just accidentally explained the password policy rules from his old job at the sled rental place down the street! The Official Toboggan Corporate Policy actually works a little differently.
# Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of "index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement.
# Given the same example list from above:
# 1-3 a: abcde is valid: position 1 contains a and position 3 does not.
# 1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
# 2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
def validate_again(passwords):
count = 0
for item in passwords:
# Break up each line
split_password = item.split()
# Grab the first and second locations to check
instances = split_password[0]
split_instances = instances.split('-')
first_instance = int(split_instances[0]) - 1
second_instance = int(split_instances[1]) - 1
# Grab the key letter and the separated password
key = split_password[1]
password = split_password[2]
# Check if the key is in the first position and NOT in the second or viceversa
if key[0] == password[first_instance] and key[0] != password[second_instance]:
count += 1
elif key[0] != password[first_instance] and key[0] == password[second_instance]:
count += 1
return count
print(validate_again(passwords)) |
30130a10cfc749aefba92d7ca287e62b88e0bf04 | bryanhann/pyforth | /utilities.py | 422 | 3.546875 | 4 | try: input = raw_input
except NameError: pass
def out(a):
print( repr(a) )
def eq(a,b):
try:
x=list(a)
y=list(b)
return x==y
except:
return a==b
def backward( aList ):
ret = aList[:]
ret.reverse()
return ret
def try_eval( x ):
try: return int(x)
except: return x
def str_reverse(s):
parts = s.split()
parts.reverse()
return ' '.join(parts)
|
0e3d8ae79d9542d7267a6a92463cb09806099893 | victorboneto/Python | /src/sqc/exe4.py | 371 | 3.984375 | 4 | #Faça um Programa que peça as 4 notas bimestrais e mostre a média.
number_1 = float(input("Digite a primeria nota: "))
number_2 = float(input("Digite a segunda nota: "))
number_3 = float(input("Digite a terceira nota: "))
number_4 = float(input("Digite a quarta nota: "))
media = (number_1 + number_2 + number_3 + number_4) / 4
print("A media foi de " + str(media)) |
681879f34aefef0a7ad1737bffab3fae05566bd1 | victorboneto/Python | /src/sqc/exe9.py | 266 | 4.1875 | 4 | #Faça um Programa que peça a temperatura em graus Fahrenheit,
#transforme e mostre a temperatura em graus Celsius.
#C = 5 * ((F-32) / 9).
graus = int(input("Digite o graus Fahrenheit aqui: "))
celsius = 5 * ((graus - 32) / 9)
print("Tem {}ºc" .format(celsius)) |
9a0fdc01b6bd00433b64bfc31279209e740b6a2b | SherifMounir/Deep-Neural-Network-for-Image-Classification | /LRC_Functions.py | 15,756 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Logistic Regression with a Neural Network mindset
# * This is a Practical Programming Assignment . I'll build a Logistic Regression Classifier to Recognize Cats
#
# # 1 - Packages
# * First, let's run the cell below to import all the packages that I need during the assignment.
# In[1]:
import numpy as np
import matplotlib.pyplot as plt # to plot graphs
import h5py # to interact with a dataset that is stored on a H5 file
import scipy # to test the model at the end
from PIL import Image
from scipy import ndimage
#from lr_utils import load_dataset
#get_ipython().run_line_magic('matplotlib', 'inline')
# * Loading the dataset ("data.h5")
# In[7]:
def load_dataset():
with h5py.File(r"C:\\Users\\SherifMounir\\Desktop\\PythonScripts\\train_catvnoncat.h5", "r") as train_dataset:
train_set_x_orig = np.array(train_dataset["train_set_x"][:])
train_set_y_orig = np.array(train_dataset["train_set_y"][:])
with h5py.File(r"C:\\Users\\SherifMounir\\Desktop\\PythonScripts\\test_catvnoncat.h5", "r") as test_dataset:
test_set_x_orig = np.array(test_dataset["test_set_x"][:])
test_set_y_orig = np.array(test_dataset["test_set_y"][:])
classes = np.array(test_dataset["list_classes"][:])
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
# In[8]:
# loading the data (cat/non-cat)
train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes = load_dataset()
# In[11]:
# Example of a picture
index = 7
#plt.imshow(train_set_x_orig[index])
#print("y = " + str(train_set_y_orig[:,index]) + ", it's '" + classes[np.squeeze(train_set_y_orig[:,index])].decode("utf-8") + "' Picture")
# # 2 - Pre-Processing
# * After we load the Dataset , now we're going to keep matrix/vector dimensions straight as :
# * m_train = (number of training examples)
# * m_test = (number of test examples)
# * num_px = (= height = width of a training image)
# In[15]:
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
'''
print("Number of training examples: m_train = " + str(m_train))
print("Number of testing examples: m_test = " + str(m_test))
print("Height/Width of each image: num_px = " + str(num_px))
print("Each image is of size: (" + str(num_px) + "," + str(num_px) + ", 3)" )
print("train_set_x shape: " + str(train_set_x_orig.shape))
print("train_set_y shape: " + str(train_set_y_orig.shape))
print("test_set_x shape: " + str(test_set_x_orig.shape))
print("test_set_y shape: " + str(test_set_y_orig.shape))
'''
# * Now reshape images of shape (num_px , num_px , 3) in a numpy-array of shape (num_px * num_px * 3 , 1).After this , our training(and test) dataset is a numpy-array where each column represents a flattened image .
# In[16]:
# Reshape the training and test examples
train_set_x_flatten = train_set_x_orig.reshape((train_set_x_orig.shape[0] , -1)).T
test_set_x_flatten = test_set_x_orig.reshape((test_set_x_orig.shape[0] , -1)).T
'''
print("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))
print("train_set_y shape: " + str(train_set_y_orig.shape))
print("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))
print("test_set_y shape: " + str(test_set_y_orig.shape))
'''
# * One commom pre-processing step in machine learning is to center and standardize your dataset . for picture datasets , it's simpler just divide every row of the dataset by 255 (the maximum value of a pixel channel) .
#
# In[17]:
train_set_x = train_set_x_flatten/255
test_set_x = test_set_x_flatten/255
# # 3 - Building Our Algorithm
#
# * Helper functions -- Sigmoid Activation Function
# In[18]:
'''
def sigmoid(z): # z = w*x + b
s = 1/(1 + np.exp(-z))
return s
'''
# In[20]:
#print("sigmoid([0 , 2]) = " + str(sigmoid(np.array([0,2]))))
# * Initlializing parameters
# In[21]:
def initialize_with_zeros(dim): # dim is the size of w vector we want
w = np.zeros((dim , 1))
b = 0
assert(w.shape == (dim,1))
assert(isinstance(b,float) or isinstance(b,int))
return w,b
# In[22]:
'''
dim = 2
w , b = initialize_with_zeros(dim)
print("w = " + str(w))
print("b = " + str(b))
'''
# * Forward and Backward propagation
# In[25]:
def propagate(w , b , X , Y):
m = X.shape[1]
# Forward propagation
A = sigmoid(np.dot(w.T,X) + b) # compute Activation
logA = np.log(A)
Y_multi_logA = np.dot(Y , logA.T)
logA2 = np.log(1 - A)
Y_multi_logA2 = np.dot((1 - Y) , logA2.T)
cost = (-1/m)*(Y_multi_logA + Y_multi_logA2) # compute cost function
###############################################
# Back propagation
dz = A - Y
dw = (1/m)*(np.dot(X , dz.T))
db_hat = (1/m)*dz
db = np.sum(db_hat , axis = 1 ,keepdims = True)
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
grads = {"dw":dw ,
"db":db }
return grads , cost
# In[29]:
'''
w , b , X , Y = np.array([[1.] , [2.]]) , 2. , np.array([[1. , 2. , -1.] , [3. , 4. , -3.2]]) , np.array([1 , 0 , 1])
grads , cost = propagate(w , b , X , Y)
print("dw = " + str(grads["dw"]))
print("db = " + str(grads["db"]))
print("cost = " + str(cost))
'''
# * Optimization -- update the parameters w , b using Gradient Descent
#
# In[36]:
def optimize(w , b , X , Y , num_iterations , learning_rate , print_cost = False):
costs = [] # list of all costs computed during the optimization ,the will be used to plot the learning curve
for i in range(num_iterations):
grads , cost = propagate(w , b , X , Y)
dw = grads["dw"]
db = grads["db"]
w = w - learning_rate * dw
b = b - learning_rate * db
if i % 100 == 0:
costs.append(cost)
if print_cost and i % 100 == 0 :
print("Cost after iteration %i : %f" %(i , cost))
params = {"w":w ,
"b":b}
grads = {"dw":dw ,
"db":db}
return params , grads , costs
# In[38]:
'''
params , grads , costs = optimize(w , b , X , Y , num_iterations=100 , learning_rate=0.009 , print_cost = False)
print("w = " + str(params["w"]))
print("b = " + str(params["b"]))
print("dw = " + str(grads["dw"]))
print("db = " + str(grads["db"]))
'''
# * Prediction
# In[41]:
'''
def predict(w , b , X):
m = X.shape[1]
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0] , 1)
A = sigmoid(np.dot(w.T , X) + b)
for i in range(A.shape[1]):
if A[0,i] <= 0.5 :
Y_prediction[0 , i] = 0
else:
Y_prediction[0 , i] = 1
assert(Y_prediction.shape == (1 , m))
return Y_prediction
'''
# In[42]:
'''
w = np.array([[0.1124579] , [0.23106775]])
b = -0.3
X = np.array([[1.,-1.1,-3.2] , [1.2 ,2. ,0.1]])
print("predictions = " + str(predict(w , b , X)))
'''
# # 4 - Merge all functions into a Model
# In[64]:
def model(X_train , Y_train , X_test , Y_test , num_iterations = 2000 , learning_rate = 0.5 , print_cost = False):
# builds the logistic regression model by calling the previously implemented functions
w , b = initialize_with_zeros(X_train.shape[0])
parameters , grads , costs = optimize(w , b , X_train , Y_train , num_iterations = 2000 , learning_rate=0.5 , print_cost = False)
w = parameters["w"]
b = parameters["b"]
Y_prediction_test = predict(w , b , X_test)
Y_prediction_train = predict(w , b , X_train)
print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs ,
"Y_prediction_test": Y_prediction_test ,
"Y_prediction_train": Y_prediction_train ,
"w" : w ,
"b" : b ,
"learning_rate" : learning_rate ,
"num_iterations" : num_iterations
}
return d
# In[65]:
#d = model(train_set_x , train_set_y_orig , test_set_x , test_set_y_orig , num_iterations = 2000 , learning_rate = 0.005 , print_cost = True)
# # Comment
# * Training accuracy is close 100%. This is a good sanity check: the model is working and has high enough capacity to fit the training data. Test accuracy is 72%. It's actually not bad for this simple model , given the small dataset we used and that logistic regression is a linear classifier. Also, we see that the model is clearly overfitting the training data . Using Regularization for example will reduce the overfitting. But no worries , I'll build an even better classifier in later assignment.
# In[ ]:
def sigmoid(Z):
A = 1/(1+np.exp(-Z))
cache = Z
return A, cache
def relu(Z):
A = np.maximum(0,Z)
assert(A.shape == Z.shape)
cache = Z
return A, cache
def relu_backward(dA, cache):
Z = cache
dZ = np.array(dA, copy=True) # just converting dz to a correct object.
# When z <= 0, you should set dz to 0 as well.
dZ[Z <= 0] = 0
assert (dZ.shape == Z.shape)
return dZ
def sigmoid_backward(dA, cache):
Z = cache
s = 1/(1+np.exp(-Z))
dZ = dA * s * (1-s)
assert (dZ.shape == Z.shape)
return dZ
def initialize_parameters(n_x, n_h, n_y):
np.random.seed(1)
W1 = np.random.randn(n_h, n_x)*0.01
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h)*0.01
b2 = np.zeros((n_y, 1))
assert(W1.shape == (n_h, n_x))
assert(b1.shape == (n_h, 1))
assert(W2.shape == (n_y, n_h))
assert(b2.shape == (n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
def initialize_parameters_deep(layer_dims):
np.random.seed(1)
parameters = {}
L = len(layer_dims) # number of layers in the network
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) / np.sqrt(layer_dims[l-1]) #*0.01
parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))
assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))
return parameters
def linear_forward(A, W, b):
Z = W.dot(A) + b
assert(Z.shape == (W.shape[0], A.shape[1]))
cache = (A, W, b)
return Z, cache
def linear_activation_forward(A_prev, W, b, activation):
if activation == "sigmoid":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = sigmoid(Z)
elif activation == "relu":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = relu(Z)
assert (A.shape == (W.shape[0], A_prev.shape[1]))
cache = (linear_cache, activation_cache)
return A, cache
def L_model_forward(X, parameters):
caches = []
A = X
L = len(parameters) // 2 # number of layers in the neural network
# Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
for l in range(1, L):
A_prev = A
A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b' + str(l)], activation = "relu")
caches.append(cache)
# Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], activation = "sigmoid")
caches.append(cache)
assert(AL.shape == (1,X.shape[1]))
return AL, caches
def compute_cost(AL, Y):
m = Y.shape[1]
# Compute loss from aL and y.
cost = (1./m) * (-np.dot(Y,np.log(AL).T) - np.dot(1-Y, np.log(1-AL).T))
cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
assert(cost.shape == ())
return cost
def linear_backward(dZ, cache):
A_prev, W, b = cache
m = A_prev.shape[1]
dW = 1./m * np.dot(dZ,A_prev.T)
db = 1./m * np.sum(dZ, axis = 1, keepdims = True)
dA_prev = np.dot(W.T,dZ)
assert (dA_prev.shape == A_prev.shape)
assert (dW.shape == W.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
def linear_activation_backward(dA, cache, activation):
linear_cache, activation_cache = cache
if activation == "relu":
dZ = relu_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
elif activation == "sigmoid":
dZ = sigmoid_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
return dA_prev, dW, db
def L_model_backward(AL, Y, caches):
grads = {}
L = len(caches) # the number of layers
m = AL.shape[1]
Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL
# Initializing the backpropagation
dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
# Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "AL, Y, caches". Outputs: "grads["dAL"], grads["dWL"], grads["dbL"]
current_cache = caches[L-1]
grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, activation = "sigmoid")
for l in reversed(range(L-1)):
# lth layer: (RELU -> LINEAR) gradients.
current_cache = caches[l]
dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, activation = "relu")
grads["dA" + str(l + 1)] = dA_prev_temp
grads["dW" + str(l + 1)] = dW_temp
grads["db" + str(l + 1)] = db_temp
return grads
def update_parameters(parameters, grads, learning_rate):
L = len(parameters) // 2 # number of layers in the neural network
# Update rule for each parameter. Use a for loop.
for l in range(L):
parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate * grads["dW" + str(l+1)]
parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate * grads["db" + str(l+1)]
return parameters
def predict(X, y, parameters):
m = X.shape[1]
n = len(parameters) // 2 # number of layers in the neural network
p = np.zeros((1, m),dtype=int)
# Forward propagation
probas, caches = L_model_forward(X, parameters)
# convert probas to 0/1 predictions
for i in range(0, probas.shape[1]):
if probas[0,i] > 0.5:
p[0,i] = 1
else:
p[0,i] = 0
#print results
#print ("predictions: " + str(p))
#print ("true labels: " + str(y))
print("Accuracy: %s" % str(np.sum(p == y)/float(m)))
return p
def print_mislabeled_images(classes, X, y, p):
a = p + y
mislabeled_indices = np.asarray(np.where(a == 1))
plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots
num_images = len(mislabeled_indices[0])
for i in range(num_images):
index = mislabeled_indices[1][i]
plt.subplot(2, num_images, i + 1)
plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest')
plt.axis('off')
plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8"))
|
6ae3776c21efd8345c033af243dedee384bf5580 | gniusranjan/algorithms | /crawler.py | 380 | 3.625 | 4 |
'''
import urllib.request
from bs4 import BeautifulSoup
w = urllib.request.urlopen("https://www.cafecoffeeday.com/cafe-menu/beverages").read()
raita= BeautifulSoup(w)
print(raita.find_all('a'))
for x in raita.find_all('nav'):
print(x)
'''
inp=input()
a,b=list(map(float,inp.split()))
if a%5==0 and a<b:
print("{:.2f}".format(b-a-.50))
else:
print("{:.2f}".format(b))
|
19c94192bbd45a17858bd0b0348a077042c144b7 | gibsonn/MTH420teststudent | /Exceptions_FileIO/exceptions_fileIO.py | 2,762 | 4.25 | 4 | # exceptions_fileIO.py
"""Python Essentials: Exceptions and File Input/Output.
<Name>
<Class>
<Date>
"""
from random import choice
# Problem 1
def arithmagic():
"""
Takes in user input to perform a magic trick and prints the result.
Verifies the user's input at each step and raises a
ValueError with an informative error message if any of the following occur:
The first number step_1 is not a 3-digit number.
The first number's first and last digits differ by less than $2$.
The second number step_2 is not the reverse of the first number.
The third number step_3 is not the positive difference of the first two numbers.
The fourth number step_4 is not the reverse of the third number.
"""
step_1 = input("Enter a 3-digit number where the first and last "
"digits differ by 2 or more: ")
step_2 = input("Enter the reverse of the first number, obtained "
"by reading it backwards: ")
step_3 = input("Enter the positive difference of these numbers: ")
step_4 = input("Enter the reverse of the previous result: ")
print(str(step_3), "+", str(step_4), "= 1089 (ta-da!)")
# Problem 2
def random_walk(max_iters=1e12):
"""
If the user raises a KeyboardInterrupt by pressing ctrl+c while the
program is running, the function should catch the exception and
print "Process interrupted at iteration $i$".
If no KeyboardInterrupt is raised, print "Process completed".
Return walk.
"""
walk = 0
directions = [1, -1]
for i in range(int(max_iters)):
walk += choice(directions)
return walk
# Problems 3 and 4: Write a 'ContentFilter' class.
"""Class for reading in file
Attributes:
filename (str): The name of the file
contents (str): the contents of the file
"""
class ContentFilter(object):
# Problem 3
def __init__(self, filename):
"""Read from the specified file. If the filename is invalid, prompt
the user until a valid filename is given.
"""
# Problem 4 ---------------------------------------------------------------
def check_mode(self, mode):
"""Raise a ValueError if the mode is invalid."""
def uniform(self, outfile, mode='w', case='upper'):
"""Write the data ot the outfile in uniform case."""
def reverse(self, outfile, mode='w', unit='word'):
"""Write the data to the outfile in reverse order."""
def transpose(self, outfile, mode='w'):
"""Write the transposed version of the data to the outfile."""
def __str__(self):
"""String representation: info about the contents of the file.""" |
1242058400bb98a528c7370854d52dc264ba64b1 | jerry0707-github/products | /products.py | 342 | 3.8125 | 4 | products =[]
while True:
name = input('請輸入商品名稱: ')
if name == 'q':
break
price = input('請輸入價格: ')
# p = []
# p.append(name)
# p.append(price)
p = [name, price] #上面2維清單簡寫法
# products.append(p)
products.append([name, price]) #上面2維清單簡寫法
print(products) |
6a452c335d58900c661a1504240a5e0775b53260 | yuankang134/python-mro-language-server | /mrols/parsed_class.py | 2,321 | 3.53125 | 4 | import jedi
from abc import ABC, abstractmethod
from typing import Tuple, Sequence, Dict
from jedi.api.classes import Name
class ParsedClass(ABC):
"""
This class encapsulates a class definition parsed for MRO list calculation
and all the intermediate results during the calculation.
All the necessary calculation to get the MRO list will be done during the
initialisation of the instance.
"""
OBJECT_CLASS: Name = jedi.Script(code='object').infer(1, 0)[0]
"""A Jedi Name to represent the `object` class."""
CONFLICT_MRO_MSG = 'Conflict MRO!!!'
def __init__(self, jedi_name: Name) -> None:
self.jedi_name = jedi_name
self.full_name = self.jedi_name.full_name if self.jedi_name.full_name else ''
self.start_pos: Tuple[int, int] = (0, 0)
self.end_pos: Tuple[int, int] = (0, 0)
self._code_lens = None
@property
@abstractmethod
def mro_parsed_list(self) -> Sequence['ParsedClass']:
"""The MRO list in ParsedClass of the target class."""
pass
@property
def code_lens(self) -> Dict:
"""The code lens correspondent to this parsed class."""
if not self._code_lens:
self._code_lens = self.get_code_lens()
return self._code_lens
@property
def mro_list(self) -> Sequence[str]:
"""The MRO list of the class."""
try:
return [parsed.jedi_name.name for parsed in self.mro_parsed_list]
except TypeError:
return [self.CONFLICT_MRO_MSG]
def get_code_lens(self):
"""Get the Code Lens associated with this parsed class."""
return {
'range': {
'start': {
# changing to line starting with 0 (LSP standard)
'line': self.start_pos[0] - 1,
'character': self.start_pos[1],
},
'end': {
# changing to line starting with 0 (LSP standard)
'line': self.end_pos[0] - 1,
'character': self.end_pos[1] - 1,
}
},
'data': self.mro_list,
}
def __eq__(self, o: object) -> bool:
if not isinstance(o, ParsedClass):
return False
return self.full_name == o.full_name
|
6e11e0e47eeb678382cd33ec0c9d414dbb2c166f | patjonstevenson/Sorting | /src/recursive_sorting/quicksort.py | 449 | 3.984375 | 4 | def quicksort(arr):
if len(arr) == 0:
return arr
else:
print(arr)
pivot = arr[0]
right = []
left = []
for el in arr[1::]:
if el > pivot:
right.append(el)
else:
left.append(el)
return quicksort(left) + [pivot] + quicksort(right)
test = [61,40,44,5,2,4,3,1,8,4,9,5,3,2,1,10,11,12,16,4,16,17,20,45,0,2,50,3]
print(quicksort(test)) |
f892b94cb660e3d61a39c7aca022d4f38b4ce0c2 | Shulik95/Python-Practice | /Hangman.py | 4,586 | 3.75 | 4 | HANGMAN_ASCII_ART = """
_ _
| | | |
| |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __
| __ |/ _' | '_ \ / _' | '_ ' _ \ / _' | '_ \\
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/
"""
MAX_TRIES = 7
HANGMAN_PHOTOS = {0: "", 1: "x-------x", 2: """ x-------x\n |\n |\n |
|\n |\n""", 3: """ x-------x\n | |\n | 0\n |
|\n |""", 4: """ x-------x\n | |\n | 0
| |\n |\n |""", 5: """ x-------x\n | |
| 0\n | /|\\\n |\n |""", 6: """ x-------x
| |\n | 0\n | /|\\\n | /\n |""",
7: """ x-------x\n | |\n | 0
| /|\\\n | / \\\n |"""}
def create_board():
word = input("Please enter a word: ")
board = "".zfill(len(word)).replace('0', '_ ')
print(board)
def check_valid_input(letter_guessed, old_letters_guessed):
"""
checks legality of given user input
:param old_letters_guessed: list of previously guessed letters.
:param letter_guessed: the letter the user guessed
:return: True if guess is legal, False otherwise
:rtype: boolean
"""
if len(letter_guessed) != 1 or not letter_guessed.isalpha() or \
letter_guessed.lower() in old_letters_guessed:
return False
return True
def try_update_letter_guessed(letter_guessed, old_letters_guessed):
"""
:param letter_guessed:
:param old_letters_guessed:
"""
if not check_valid_input(letter_guessed, old_letters_guessed): # user guess is illegal
print("X")
guess_str = " -> ".join(sorted(old_letters_guessed))
print("Let us remind you of the letters you guessed so far: ",
guess_str)
return False
else:
old_letters_guessed.append(letter_guessed.lower())
return True
def show_hidden_word(secret_word, old_letters_guessed):
"""
shows the player his advancement in guessing the word.
:param secret_word: word to guess
:param old_letters_guessed: list of the letters the user guessed so far
:return string representing the parts of the secret word the user guessed
:rtype: string
"""
word_as_list = list('_' * len(secret_word))
for letter in old_letters_guessed:
for i in range(len(secret_word)):
if letter == secret_word[i]:
word_as_list[i] = letter
return " ".join(word_as_list)
def check_win(secret_word, old_letters_guessed):
"""
checks if all the letters of the word were guessed
:param secret_word: word to guess
:param old_letters_guessed: list of guessed letters by user
:return: True if the player won, False otherwise
:rtype: boolean
"""
guessed_word = show_hidden_word(secret_word, old_letters_guessed).replace(" ", '')
return secret_word == guessed_word
def print_hangman(num_of_tries):
"""
prints the state of the
:param num_of_tries:
:return:
"""
print(HANGMAN_PHOTOS[num_of_tries])
def choose_word(file_path, index):
"""
:param file_path:
:param index:
:return:
"""
word_dict = {}
file = open(file_path)
all_words_lst = (file.readline()).split(" ") # create array of words
for word in all_words_lst:
if word in word_dict:
word_dict[word] += 1
else: # create new entry for the word
word_dict[word] = 0
return all_words_lst[(index - 1) % len(all_words_lst)]
def start_game():
"""
the main function on the games, runs it from start to finish.
"""
guessed_letters = []
num_of_guesses = 0
print(HANGMAN_ASCII_ART)
file_path = input("Please insert the file adress: ")
word_idx = int(input("Please choose a number: ")) # get index of a word
secret_word = choose_word(file_path, word_idx)
while not check_win(secret_word, guessed_letters):
user_guess = input("Please choose a letter: ")
if not try_update_letter_guessed(user_guess, guessed_letters):
continue
print(show_hidden_word(secret_word, guessed_letters))
print()
if user_guess not in secret_word: # update drawing
num_of_guesses += 1
print_hangman(num_of_guesses)
if num_of_guesses == MAX_TRIES:
print("Loser :(")
return
print("Winner! you win nothing")
if __name__ == '__main__':
start_game()
|
79a2b63047f6469472076a2274cea2b205cb0b06 | Idolnanib/Domashka1.0 | /alone_pract.py | 9,820 | 4.21875 | 4 | # Задание по переводу рублей в доллары.
# План выполнения: наинпутить рубли с курсом доллара и запринтовать ответ
# Rubl = float(input('Введи сколько рублей хочешь перевести в баксы, бро : '))
# print('17.10.2021 курс был такой: за 1$ дают 70.99 рублей')
# Kurs = float(input('Введи курс баксов к рублю , бро : '))
# import math
# print('Столько франклинов ты получишь за свои рубли :', round(Rubl/Kurs,2),' $')
# Зaдание 2 на print и input.
# productName1 = input('Что купил сперва ты седня? : ')
# price1 = int(input('Назови цену этого чуда, только давай без копеек, я уже int поставил : '))
# productName2 = input('Что второе ты купил? : ')
# price2 = int(input('Назови цену этого чуда, только без копеек,ty : '))
# print('давай сделаем итог вышенаписанного :', productName1, '- ', price1, 'and', productName2, '- ',price2 )
# print('Чувак, то что ты сегодня накупил вышло на', price1+price2 , " рублей")
# Задание 3 , которое я еще не читал
# balanc = int(input('Сколько денег на карте? : '))
# roznica = int(input('Напиши цену за товар(1 шт.) '))
# cena = int(input('Друг, какая цена этого товара? '))
# print('друг, там цена на все товары ', roznica * cena,', а баланс на карте останется : ',balanc - roznica * cena)
# Try part №4
# day_of_the_week = int(input('Напиши плс номер дня недели (номера начинаются с понедельника)) : '))
# if day_of_the_week == 1:
# print('На понедельник запланирована(барабанная дробь) РАбоТА.Поздравляю!!')
# elif day_of_the_week == 2:
# print('Во вторник спорт зал. ну мы же знаем, что работа, верно?? ;) ')
# elif day_of_the_week == 3:
# print('В среду хобби. Т.е. идем на работу. Усиление ж ')
# elif day_of_the_week == 4:
# print('В четверг выходной. За который дадут переработку, т.к. идешь на работу ')
# elif day_of_the_week == 5:
# print('В пятницу плавание.Плавание в рутине на работе хе-хе ')
# elif day_of_the_week == 6:
# print('Обучение рабочим моментам . Соре бро ')
# elif day_of_the_week == 7:
# print('В воскресенье выходной только у христиан.А у нас работа ')
# else :
# print('попробуй другую цифру')
# Задача 5 - ноутбук.- не работает правильно
# voper = int(input('Сколько оперативки на компе? : '))
# wind = input('экран IPS или LED? : ')
# price = int(input('Назови цену устройства : '))
# core = int(input('Сколько ядер ? '))
#
# if ((voper == 8 or 16) and (wind == 'IPS' or "LED") and (price <= 50000) and (core == 4 or 6 or 8)):
# print('Бери его не глядя.')
# else:
# print('Параметры не подходят или ты хулиганишь.Трай эгейн ')
# 6. Время суток
# time = float(input('Сколько время?? '))
# if 6 <= time < 12:
# print('утро')
# elif 12 <= time < 18:
# print('день')
# elif 18 <= time < 22:
# print('вечер')
# elif 22 <= time <= 24 or 1 <= time < 6:
# print('ночь')
# else:
# print('Введи число со значением из промежутка [1:24]')
# 7 задание.
# number = int(input('Введи количество зведочек, которое ты хотел бы видеть )) '))
# z = '*'
# n = 0
# while n != number:
# print(z,end='')
# n = n + 1
# 8. массив , который список(28.10.2021)
# import math
# вариант 1 - цикл по списку через индекс i
# myList = [5, -3, 4, -6, 1]
# for i in range(len(myList)):
# if myList[i] > 0: # если число положительное
# print('+', myList[i])
# else:
# print(myList[i])
# print()
# вариант 2 - цикл по списку без индексов, сразу по элементам
# myList = [5, -3, 4, -6, 1]
# for elem in myList:
# if elem > 0: # если число положительное
# print('+', elem)
# else:
# print(elem)
# print()
# 10.11.2021
# ЗАДАЧА 1.
# Создать список на 10 элементов, заполнить его числами в диапазоне от 0 до 100, вывести элементы списка в вместе с их индексами.
# К примеру, есть с {1,8,4}, тогда программа должна вывести:
# 0: 1
# 1: 8
# 2: 4
# import math
# import random
#
# my_glist = []
#
# for i in range(10):
# my_glist.append(random.randint(0, 100))
# print(i,': ',my_glist[i] )
# print()
# print(my_glist)
# Задача 2 Создать список на 5 элементов,
# заполнить его числами в диапазоне от -10 до 100,
# вывести элементы списка в одну строку.
# Найти минимальный элемент.
# import math
# import random
#
# mega_list = []
#
# for i in range(5):
# mega_list.append(random.randint(-10, 100))
# print(mega_list[i],end=' ')
#
# min_value = min(mega_list)
# print()
# print(min_value)
# Задача 3 Создать список на 15 элементов,
# заполнить его числами в диапазоне от 0 до 20,
# вывести элементы массива в одну строку. Найти максимальный элемент.
# import math
# import random
#
# list_listok = []
#
# for i in range(15):
# list_listok.append(random.randint(0, 20))
# print(list_listok[i], end=' ')
# max_value = max(list_listok)
# print()
# print(max_value)
# Задача 4 Реализовать меню простого калькулятора
# 1. Сложить
# 2. Вычесть
# 3. Умножить
# 4. Делить
# 5. Выход
#
# При выборе пунктов с 1 по 4 программа считывает два числа,
# выполняет выбранное действие и выводит результат
#
# spi_1 = []
# spi_2 = []
# a = 0
# b = 0
# user_input = ''
#
# while user_input != "5":
# print('1. Сложить')
# print('2. Вычесть')
# print('3. Умножить')
# print('4. Делить')
# print('5. Выход')
#
# user_input = input()
# if user_input == '1':
# a = int(input("Введи первое чило : "))
# b = int(input("Введи второе чило : "))
# print('Cумма равна', a + b)
# elif user_input == '2':
# a = int(input("Введи первое чило : "))
# b = int(input("Введи второе чило : "))
# print('Разница чисел равна ', a - b)
# elif user_input == '3':
# a = int(input("Введи первое чило : "))
# b = int(input("Введи второе чило : "))
# print('Произведение чисел равно ', a * b)
# elif user_input == '4':
# a = int(input("Введи первое чило : "))
# b = int(input("Введи второе чило : "))
# print('Деление чисел равно ', a / b)
# print('Пока ')
# Задача 5 Создать программу, позволяющую вести список лиц, приглашенных на мероприятие.
# Список должен хранить имена приглашенных. Создать консольное меню:
# 1. Добавить гостя
# 2. Проверить, есть ли имя гостя в списке приглашенных
# 3. Вывести всех приглашенных
# 4. Выход
n=0
sp_1 = []
sp_2 = []
user_input = ''
a = 0
while user_input != '4':
print("1. Добавить гостя")
print("2. Проверить, есть ли имя гостя в списке приглашенных")
print("3. Вывести всех приглашенных")
print("4. Выход")
user_input = input('Цифру введи ')
if user_input == '1':
sp_1_1 = input('Введи имя гостя ')
sp_2_2 = input('Введи фамилию гостя ')
sp_1.append(sp_1_1)
sp_2.append(sp_2_2)
n =+ n #Количество зареганых людей для Вывода их потом при необходимости.
elif user_input == '2':
sp_1_1 = input('Имя чела, которого хочешь проверить: ')
sp_2_2 = input('Его фамилию : ')
if sp_1_1 in sp_1 and sp_2_2 in sp_2:
print('Такой гость зарегестрирован.')
else:
print('Нет его в списке или ввел ты что-то не так')
elif user_input == '3':
for i in range(n):
a = 1 + i
print(a,'. - ',sp_1[i],' ',sp_2[i], end='')
print(' Брейк зе программ ')
|
577e6159eadade42ea06061c3fbe1a16536644f1 | Rayff-de-Souza/Python_Geek-University | /SECAO-6-EXERCICIO-2/index.py | 408 | 4.15625 | 4 | """
GEEK UNIVERSITY - Exercício
- Faça um programa que escreva de 1 até 100 duas vezes, sendo a primeira vez com o loop FOR e a
segunda com o loop WHILE.
"""
print('FOR'.center(20, '_'))
for n in range(1, 101):
print(n)
print('FOR'.center(20, '_'))
print('\n')
contador = 1
print('WHILE'.center(20, '_'))
while contador < 101:
print(contador)
contador = contador + 1
print('WHILE'.center(20, '_')) |
b1635245fc31d7551519a39e0e88458728a85378 | luisejv/autograder_demo | /Lab103/solutions/p1.py | 873 | 4 | 4 | def main():
phrase = input("Ingrese frase:")
print("Frase:" + phrase)
minus = 0
mayus = 0
caracs = 0
nums = 0
sumnums = 0
strnums = ""
for i in phrase:
if i >= 'a' and i <= 'z':
minus += 1
elif i >= 'A' and i <= 'Z':
mayus += 1
elif i >= '0' and i <= '9':
nums += 1
sumnums += int(i)
strnums += i
else:
caracs += 1
print('Mayusculas:' + str(mayus))
print('Minusculas:' + str(minus))
#Imprimir la cantidad de numeros no estaba considerado en el
#ejemplo pero si en el enunciado de la pregunta
#Igual se tomara en cuenta como si no se hubiera pedido
print('Numeros:' + str(nums))
print('Caracteres especiales:' + str(caracs))
print('Suma numeros:' + str(sumnums))
print('String numeros:' + strnums)
|
c0b7a937dae740563aa68c938aed3627064121e3 | Kim280990/Kim | /kim4.py | 486 | 3.8125 | 4 | import math
a = float(input("informe valor de a: "))
b = float(input("informe valor de b: "))
c = float(input("informe valor de c: "))
if a>b>c:
print("o maior número é",a, "e o menor número é",c)
if a<b<c:
print("o menor número é",a, "e o maior número é",c)
if a>c>b:
print("o maior número é",a, "e o menor número é",b)
if b>a>c:
print("o maior número é",b, "e o menor número é",c)
if c>b>a:
print("o maior número é",c, "e o menor número é",a) |
495c17bd6c0fe83b618360a74c52333857610c51 | JuanmaGlez/Kata1 | /kata1/tabla_multiplicar.py | 430 | 3.75 | 4 | """
enunciado
"""
#tabla = 5
#tabla = int(input("Dime el númoro de la tabla "))
tabla = input("Dime el númoro de la tabla ")
try:
tabla = int(tabla)
# if (isinstance(tabla, int)):
# range(11) -> range(0, 11, 1) -> empieza por 0, y el numero llega hasta x-1
for i in range(11):
#print(i)
print(str(tabla) + " x " + str(i) + " = " + str(tabla * i))
except:
print("Solo vale números")
|
02c80b5ca4a6ab3fe97c8acee0622928d30822eb | d3m0n-r00t/ML-algorithms-from-scratch | /rnn.py | 582 | 3.921875 | 4 | import numpy as np
class rnn():
def step(self,x):
#hidden layer
self.h=np.tanh(np.dot(self.W_hh,self.h)+np.dot(self.W_xh,x))
#output layer
y=np.dot(self.W_hy,self.h)
'''
3 matrices. W_hh,W_xh,W_hy
np.dot --> matrix multiplication with two inputs previous hidden state and present input
The two intermediates interact with addition. Then it is sqashed by tanh
'''
return y
#Single hidden layer. Or single step
'''
nn = rnn()
y=nn.step(x)
'''
#2-layer network
'''
y1=rnn.step(x)
y=rnn.step(y1)
''' |
bed2e86e2117862842cd49a96c65de758c2be985 | nikita-p/stepik_algorithms | /First Part/8.2.py | 510 | 3.65625 | 4 | #Последовательнократная подпоследовательность
def finder(arr):
indexes = [ -1 for i in range(len(arr)) ]
for i1 in range(len(arr)):
for i2 in range(i1+1, len(arr)):
if ( arr[i2]%arr[i1]==0 and indexes[i2]<indexes[i1]+1 ):
indexes[i2] = indexes[i1]+1
#print(indexes)
#print(arr)
print( max(indexes)+2 )
if __name__=="__main__":
n = input()
arr = list( map( int, input().split(' ') ) )
finder(arr)
|
6bec56ba2119b6eec776088aa5fec648808e9eb8 | ASR-99/new_repository | /1.py | 330 | 3.859375 | 4 | # האם אתה יכול לצאת עם בחורה בגיל הזה
#age = 24
number = int(input("בת כמה הבחורה שאתה שוקל לצאת איתה?\n"))
age = number
if age < 24:
print("מטריד היא יותר צעירה ")
else:
print("מספיק זקנה בשביל שזה לא יחשב מטריד...") |
d782eb2a181684f5fec0f24be28c07b2e749ba9a | mrnguyener21/Udemy-Python-for-Data-Science-and-Machine-Learning-Bootcamp | /section_7_python_for_data_analysis_pandas_exercises/sf_salaries_exercise.py | 2,108 | 4.0625 | 4 | #%%
import pandas as pd
# %%
#Read Salaries.csv as a dataframe called sal.
salaries = pd.read_csv('Salaries.csv')
salaries
# %%
#check the head of the DataFrame
salaries.head()
# %%
#use the info method to find out how many entries there are
salaries.info()
# %%
#what is the average BasePay?
salaries['BasePay'].mean()
# %%
#what is the highest amount of overtimepay in the dataset
salaries['OvertimePay'].max()
# %%
#what is the job title of JOSEPH DRISCOLL?
salaries[salaries['EmployeeName'] == 'JOSEPH DRISCOLL']['JobTitle']
# %%
# How much does JOSEPH DRISCOLL MAKE INCLUDING BENEFITS
salaries[salaries['EmployeeName'] == 'JOSEPH DRISCOLL']['TotalPayBenefits']
# %%
#What is the name of highest paid person (including benefits)?
# salaries[salaries['TotalPayBenefits'].max()]['EmployeeName']
salaries[salaries['TotalPayBenefits']== salaries['TotalPayBenefits'].max()]
# %%
salaries['TotalPayBenefits'].max()# %%
# %%
#What is the name of the lowest paid person including benefits
salaries[salaries['TotalPayBenefits'] == salaries['TotalPayBenefits'].min()]
# %%
#what was the average(mean) basepay of all employees per year? (2011- 2014)
#we want the mean for each year
salaries.groupby('Year').mean()['BasePay']
# %%
salaries['JobTitle'].nunique()
# %%
#what are the top 5 most common jobs
#group by job
#sort from highest to lowest
#only return the top 5
salaries['JobTitle'].value_counts().head(5)
# %%
#how many job titles were represented by only one person in 2013?
sum(salaries[salaries['Year'] == 2013]['JobTitle'].value_counts() == 1)
# %%
#how many people have the word chief in their job title?
#I DONT GET THIS ONE AT ALL
def chief_string(title):
if 'chief' in title.lower().split():
return True
else:
return False
sum(salaries['JobTitle'].apply(lambda x: chief_string(x)))
#the .APPLY(LAMBDA X is applying the if else statement to the salaries['JobTitle] so that we get our list of true and false)
# %%
#is there a correlation between length of the job title stirng and salary?
salaries['title_len'] = salaries['JobTitle'].apply(len)
salaries[['JobTitle','title_len']].corr()
# %%
|
2370c5e7c60495ff9ea67ff3bdfedcdc46d9a129 | mrnguyener21/Udemy-Python-for-Data-Science-and-Machine-Learning-Bootcamp | /section_5-10_exercises/1)numpy_exercise.py | 912 | 3.59375 | 4 | #%%
#import numpy as np
import numpy as np
# %%
np.zeros(10)
# %%
#createa an array of 10 ones
np.ones(10)
# %%
#create an array of 10 fives
np.ones(10) * 5
# %%
#create an array of the integers froom 10 to 50
np.arange(0,51)
# %%
#create an array of all the even integers from 10 to 60
np.arange(0,51,2)
# %%
#create a 3x3 matrix with values ranging from 0 t0 8
np.arange(0,9).reshape(3,3)
# %%
#create a 3x3 identity matrix
np.identity(3)
# %%
#use numpy to generate a random number between 0 and 1
np.random.rand(1)
# %%
#use numpy to generate an array of 25 random numbers sampled from a standard normal distribution
np.random.rand(25)
# %%
np.arange(1,101).reshape(10,10)/100
# %%
#create an array of 20 linearly spaced points betwen 0 and 1
np.linspace(0,1)
# %%
mat = np.arange(1,26).reshape(5,5)
mat
# %%
mat[2:,1:]
# %%
mat[:3,1:2]
# %%
mat[3:]
# %%
mat.sum()
# %%
mat.std()
# %%
mat.sum(axis=0)
# %%
|
3d3cfa287ae10160ad2cf6fcd3c7c98a0121bfe7 | mrnguyener21/Udemy-Python-for-Data-Science-and-Machine-Learning-Bootcamp | /section_8_python_for_data_visualization_matplotlib/Matplotlib_part_2.py | 1,241 | 3.984375 | 4 | #%%
import matplotlib.pyplot as plt
import numpy as np
# %%
x = np.linspace(0,5,11)
y = x ** 2
x
fig = plt.figure()
axes1 = fig.add_axes([0.1,0.1,0.8,0.8])
axes2 = fig.add_axes([0.2,0.5,0.4,0.3])
axes1.plot(x,y)
axes1.set_title('larger plot')
axes2.plot(y,x)
axes2.set_title('smaller plot')
# %%
#here we created two subplots that both has one row and 2 columns(not sure what that means)
fig,axes = plt.subplots(nrows =1 , ncols =2)
# axes.plot(x,y)
# for current_ax in axes:
# current_ax.plot(x,y)
axes[0].plot(x,y)
axes[0].set_title('first plot')
axes[1].plot(y,x)
axes[1].set_title('second plot')
plt.tight_layout()
# %%
#here we are going about changing the size of the graph(width and height)
fig = plt.figure(figsize = (8,2))
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
# %%#the same can be done for the smaller graphs wtihin the big graphs
fig,axes = plt.subplots(nrows = 2, ncols = 1, figsize = (8,2))
axes[0].plot(x,y)
axes[1].plot(x,y)
plt.tight_layout()
# %%
# fig.savefig('my_picture.png',dpi = 200)
# %%
#here we are creating a graph with two graph lines and a legend is included
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x,x**2, label = 'X SQUARED')
ax.plot(x,x**3, label = 'X CUBED')
ax.legend(loc=0)
# %%
|
f63d44fba6261f1e0ecaf4d952b14fc9f8ac33db | alinedsoares/PythonMundo1 | /ex017.py | 276 | 3.8125 | 4 | from math import hypot
co = float(input("Digite o comprimneto do cateto oposto: "))
ca = float(input('Digite o comprimento do cateto adjacente: '))
print('Considerando cateto oposto {} e cateto adjacente {}, a hipotenusa vai medir {:.2f}'.format(co, ca, hypot(co, ca)))
|
bbc4a02307772175ed2d581313fc7f2bece0b3a0 | alinedsoares/PythonMundo1 | /ex014.py | 163 | 3.890625 | 4 | temperatura = float(input('Qual a temperatura em ºC: '))
print ('A temperatura de {} ºC corresponde a {} ºF'.format(temperatura, ((temperatura * 9/5) + 32)))
|
2721749795823dbd4651a805799510053dc76020 | alinedsoares/PythonMundo1 | /ex016.py | 161 | 4 | 4 | from math import trunc
decimal = float(input('Digite um número real: '))
print ('O número real {} tem a parte inteira {}.'.format(decimal, trunc(decimal)))
|
f9f7e86bd2bb9bd737b56659a001d9ec611871aa | ZASXCDFVA/LeetCodeAns | /single-number.py | 382 | 3.625 | 4 | from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)):
if (i - 1 < 0 or nums[i - 1] != nums[i]) and (i >= len(nums) - 1 or nums[i + 1] != nums[i]):
return nums[i]
return nums[0]
if __name__ == '__main__':
print(Solution().singleNumber([1, 1]))
|
ba5c4f27316d0adb0e12bc56c1f5e10195f6d53b | ZASXCDFVA/LeetCodeAns | /missing-number.py | 553 | 3.765625 | 4 | from typing import List
class Solution:
def missingNumber(self, nums: List[int]) -> int:
bits: int = 0
for n in nums:
bits |= 1 << n
index = 0
bits = ~bits
while bits != 0:
if bits & 0xFFFFFFFF != 0:
break
index += 32
bits >>= 32
bits = bits & 0xFFFFFFFF
while bits & 1 == 0:
bits >>= 1
index += 1
return index
if __name__ == '__main__':
print(Solution().missingNumber([3, 0, 1]))
|
63c050a1ca83ec3b2e980a0905fb4927e32947b6 | ZASXCDFVA/LeetCodeAns | /add-two-numbers.py | 1,015 | 3.78125 | 4 | # Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def extractNumber(self, node: ListNode) -> int:
if node.next is not None:
return self.extractNumber(node.next) * 10 + node.val
return node.val
def storeNumber(self, value: int) -> ListNode:
if value // 10 == 0:
return ListNode(value, None)
return ListNode(value % 10, self.storeNumber(value // 10))
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1: int = self.extractNumber(l1)
num2: int = self.extractNumber(l2)
sum = num1 + num2
return self.storeNumber(sum)
if __name__ == '__main__':
l1 = ListNode(2, ListNode(4, ListNode(3)))
l2 = ListNode(5, ListNode(6, ListNode(4)))
solution = Solution()
result = solution.addTwoNumbers(l1, l2)
print(solution.extractNumber(result)) |
e6a1daf5279736580841e4300db5ee0c2d61ba02 | gayatri-a-b/91R-fall-code | /algo.py | 16,745 | 3.640625 | 4 | import numpy
import pandas
import matplotlib.pyplot as plt
from matplotlib import animation
from scipy.stats import wasserstein_distance
from matplotlib.animation import FuncAnimation
# Threshold Classifier Agent
class Threshold_Classifier:
# constructor
def __init__( self,
pi_0 = [10, 10, 20, 30, 30, 0, 0],
pi_1 = [0, 10, 10, 20, 30, 30, 0],
certainty_0 = [0.1, 0.2, 0.45, 0.6, 0.65, 0.7, 0.7],
certainty_1 = [0.1, 0.2, 0.45, 0.6, 0.65, 0.7, 0.7],
loan_chance = 0.1,
group_chance = 0.5,
loan_amount = 1.0,
interest_rate = 0.3,
bank_cash = 1000 ):
self.pi_0 = pi_0 # disadvantaged group
self.certainty_0 = certainty_0
self.pi_1 = pi_1 # advantaged group
self.certainty_1 = certainty_1
# chance you loan to someone you are uncertain whether they will repay
self.loan_chance = loan_chance
# chance they come group 1
self.group_chance = group_chance
# loan amount
self.loan_amount = loan_amount
# interest rate
self.interest_rate = interest_rate
# bank cash
self.bank_cash = bank_cash
# return an individual and their outcome
def get_person(self):
# what group they are in
group = numpy.random.choice(2, 1, p=[1 - self.group_chance, self.group_chance])[0]
# what their credit score bin they walk in from
decile = numpy.random.choice(7, 1, p=[1/7, 1/7, 1/7, 1/7, 1/7, 1/7, 1/7])[0]
# whether they will repay or not
if group == 0:
loan = numpy.random.choice(2, 1, p=[1 - self.certainty_0[decile], self.certainty_0[decile]])[0]
else:
loan = numpy.random.choice(2, 1, p=[1 - self.certainty_1[decile], self.certainty_1[decile]])[0]
# determine whether to loan to uncertain person
if loan == 0:
loan = numpy.random.choice(2, 1, p=[1 - self.loan_chance, self.loan_chance])[0]
# determine whether they repay or not
if group == 0:
repay = numpy.random.choice(2, 1, p=[1 - self.certainty_0[decile], self.certainty_0[decile]])[0]
else:
repay = numpy.random.choice(2, 1, p=[1 - self.certainty_1[decile], self.certainty_1[decile]])[0]
# if nobody in that bin
if group == 0 and self.pi_0[decile] == 0 :
loan = 0
if group and self.pi_1[decile] == 0:
loan = 0
return ((group, decile, loan, repay))
# get the average score of a given distribution
def average_score(self, pi_):
average = ( 1*pi_[0] + 2*pi_[1] + 3*pi_[2] + 4*pi_[3] + 5*pi_[4] + 6*pi_[5] + 7*pi_[6] ) / 100
return average
# return what an update of the environment would yield
def one_step_update(self):
# make copies of then current variables
pi_0 = self.pi_0.copy()
certainty_0 = self.certainty_0.copy()
pi_1 = self.pi_1.copy()
certainty_1 = self.certainty_1.copy()
bank_cash = self.bank_cash
# get the person and their outcome
(group, decile, loan, repay) = self.get_person()
# if group 0
if group == 0:
# if we loaned
if loan:
current_bin = pi_0[decile] # current bin count
current_repayment = certainty_0[decile] # current bin repayment certainty
# if loan was not repaid
if repay == 0:
# if they can be moved down
if decile != 0:
bin_under = pi_0[decile - 1] # bin under count
repayment_under = certainty_0[decile - 1] # bin under repayment certainty
# update count of current bin
pi_0[decile] = pi_0[decile] - 1
# update count of bin under
pi_0[decile - 1] = pi_0[decile - 1] + 1
# bank loses money
bank_cash -= self.loan_amount
# if loan was repaid
else:
# if they can be moved down
if decile != 6:
bin_over = pi_0[decile + 1] # bin under count
repayment_over = certainty_0[decile + 1] # bin under repayment certainty
# update count of current bin
pi_0[decile] = pi_0[decile] - 1
# update count of bin over
pi_0[decile + 1] = pi_0[decile + 1] + 1
# bank gains money
bank_cash += self.loan_amount * (1 + self.interest_rate)
return (group, pi_0, certainty_0, bank_cash, loan, repay)
# if group 1
else:
# if we loaned
if loan:
current_bin = pi_1[decile] # current bin count
current_repayment = certainty_1[decile] # current bin repayment certainty
# if loan was not repaid
if repay == 0:
# if they can be moved down
if decile != 0:
bin_under = pi_1[decile - 1] # bin under count
repayment_under = certainty_1[decile - 1] # bin under repayment certainty
# update count of current bin
pi_1[decile] = pi_1[decile] - 1
# update count of bin under
pi_1[decile - 1] = pi_1[decile - 1] + 1
# bank loses money
bank_cash -= self.loan_amount
# if loan was repaid
else:
# if they can be moved down
if decile != 6:
bin_over = pi_1[decile + 1] # bin under count
repayment_over = certainty_1[decile + 1] # bin under repayment certainty
# update count of current bin
pi_1[decile] = pi_1[decile] - 1
# update count of bin over
pi_1[decile + 1] = pi_1[decile + 1] + 1
# bank gains money
bank_cash += self.loan_amount * (1 + self.interest_rate)
return (group, pi_1, certainty_1, bank_cash, loan, repay)
# take one step of the environment if successful iteration
# return whether successful update took place
def one_step(self):
# get current distribution averages
current_average_0 = self.average_score(self.pi_0)
current_average_1 = self.average_score(self.pi_1)
# check out what one step would be
(group, pi_, certainty_, bank_cash_, loan_, repay_) = self.one_step_update()
# get the proposed step distribution
potential_average_ = self.average_score(pi_)
# if group 0
if group == 0:
# get the wasserstein distance
earth_mover_distance_ = wasserstein_distance(self.pi_0, pi_)
# successful step means average increased and bank at least breaks even
if bank_cash_ >= 1000 and potential_average_ >= current_average_0:
# take the step
self.pi_0 = pi_
self.certainty_0 = certainty_
self.bank_cash = bank_cash_
# successful update
return True
# if group 1
else:
# get the wasserstein distance
earth_mover_distance_ = wasserstein_distance(self.pi_1, pi_)
# successful step means average increased and bank at least breaks even
if bank_cash_ >= 1000 and potential_average_ >= current_average_1:
# take the step
self.pi_1 = pi_
self.certainty_1 = certainty_
self.bank_cash = bank_cash_
# successful update
return True
# not successful so no update took place
return False
# update specific number of times
def iterate(self, iterations):
# index
i = 0
# only count successful updates
while (i < iterations):
self.one_step()
i += 1
# return distributions after given number of successful updates
return (self.pi_0, self.pi_1)
## SIMULATION
# parameter values from: https://github.com/google/ml-fairness-gym/blob/master/environments/lending_params.py
pi_0 = [10, 10, 20, 30, 30, 0, 0] # Disadvantaged group distribution
pi_1 = [0, 10, 10, 20, 30, 30, 0] # Advantaged group distribution
certainty_0 = [0.1, 0.2, 0.45, 0.6, 0.65, 0.7, 0.7] # Likelihood of repayment by credit score (fixed during simulation)
certainty_1 = [0.1, 0.2, 0.45, 0.6, 0.65, 0.7, 0.7] # Likelihood of repayment by credit score (fixed during simulation)
group_chance = 0.5 # chance of selecting a group (fixed during simulation)
loan_amount = 1.0 # amount of each loan (fixed during simulation)
interest_rate = 0.3 # interest rate of loans (fixed during simulation)
bank_cash = 1000 # starting amount in bank -- altruistic bank so seeks to a least break even
# tunable hyper parameters
loan_chance = 0.02 # chance of loaning to someone who should not receive the loan
iterations = 300 # number of time steps to simulate
"""
## TO RUN SIMULATION
# RUN
th = Threshold_Classifier(
pi_0 = pi_0,
pi_1 = pi_1,
certainty_0 = certainty_0,
certainty_1 = certainty_1,
loan_chance = loan_chance,
group_chance = group_chance,
loan_amount = loan_amount,
interest_rate = interest_rate,
bank_cash = bank_cash )
(updated_pi_0, updated_pi_1) = th.iterate(iterations)
# PRINT
# print distribution before and after
print("Time steps: ", iterations)
print("Inital Group A (Disadvantaged): ", pi_0)
print("Updated Group A (Disadvantaged): ", updated_pi_0)
print("Inital Group B (Advantaged): ", pi_1)
print("Updated Group B (Advantaged): ", updated_pi_1)
"""
"""
## TEST ITERATIONS
# test iterations
iterations_array = [50, 100, 250, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 10000]
ones_0 = []
twos_0 = []
threes_0 = []
fours_0 = []
fives_0 = []
sixes_0 = []
sevens_0 = []
ones_1 = []
twos_1 = []
threes_1 = []
fours_1 = []
fives_1 = []
sixes_1 = []
sevens_1 = []
updated_pi_0s = []
updated_pi_1s = []
for iteration_i in iterations_array:
iterations = iteration_i
th = Threshold_Classifier(
pi_0 = pi_0,
pi_1 = pi_1,
certainty_0 = certainty_0,
certainty_1 = certainty_1,
loan_chance = loan_chance,
group_chance = group_chance,
loan_amount = loan_amount,
interest_rate = interest_rate,
bank_cash = bank_cash )
(updated_pi_0, updated_pi_1) = th.iterate(iterations)
updated_pi_0s.append(updated_pi_0)
updated_pi_1s.append(updated_pi_1)
ones_0.append(updated_pi_0[0])
twos_0.append(updated_pi_0[1])
threes_0.append(updated_pi_0[2])
fours_0.append(updated_pi_0[3])
fives_0.append(updated_pi_0[4])
sixes_0.append(updated_pi_0[5])
sevens_0.append(updated_pi_0[6])
ones_1.append(updated_pi_1[0])
twos_1.append(updated_pi_1[1])
threes_1.append(updated_pi_1[2])
fours_1.append(updated_pi_1[3])
fives_1.append(updated_pi_1[4])
sixes_1.append(updated_pi_1[5])
sevens_1.append(updated_pi_1[6])
data = {'Iterations': iterations_array,
'100s': ones_0, '200s': twos_0, '300s': threes_0, '400s': fours_0, '500s': fives_0, '600s': sixes_0, '700s': sevens_0,
'100s-1': ones_1, '200s-1': twos_1, '300s-1': threes_1, '400s-1': fours_1, '500s-1': fives_1, '600s-1': sixes_1, '700s-1': sevens_1}
df = pandas.DataFrame(data=data)
df.to_csv(r'data-iterations.csv', index = False)
data_0 = {'Iterations': iterations_array,
'100s': ones_0, '200s': twos_0, '300s': threes_0, '400s': fours_0, '500s': fives_0, '600s': sixes_0, '700s': sevens_0}
df_0 = pandas.DataFrame(data=data_0)
data_1 = {'Iterations': iterations_array,
'100s-1': ones_1, '200s-1': twos_1, '300s-1': threes_1, '400s-1': fours_1, '500s-1': fives_1, '600s-1': sixes_1, '700s-1': sevens_1}
df_1 = pandas.DataFrame(data=data_1)
for ind, arr in enumerate(updated_pi_0s):
iterations_ = iterations_array[ind]
objects = ('100', '200', '300', '400', '500', '600', '700')
y_pos = numpy.arange(len(objects))
outcome_ = arr
plt.bar(y_pos, outcome_, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Number of People')
plt.xlabel('Credit Score')
plt.title('Group 0 ' + str(iterations_) + " Iterations")
plt.savefig('charts-iterations/group_0_' + str(iterations_) + '.png')
plt.clf()
for ind, arr in enumerate(updated_pi_1s):
iterations_ = iterations_array[ind]
objects = ('100', '200', '300', '400', '500', '600', '700')
y_pos = numpy.arange(len(objects))
outcome_ = arr
plt.bar(y_pos, outcome_, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Number of People')
plt.xlabel('Credit Score')
plt.title('Group 1 ' + str(iterations_) + " Iterations")
plt.savefig('charts-iterations/group_1_' + str(iterations_) + '.png')
plt.clf()
"""
"""
## TEST LOAN_CHANGE
# test loan chance
loan_chance_array = [0.01, 0.02, 0.03, 0.05, 0.08, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.6, 0.7, 0.8]
ones_0 = []
twos_0 = []
threes_0 = []
fours_0 = []
fives_0 = []
sixes_0 = []
sevens_0 = []
ones_1 = []
twos_1 = []
threes_1 = []
fours_1 = []
fives_1 = []
sixes_1 = []
sevens_1 = []
updated_pi_0s = []
updated_pi_1s = []
for loan_chance_i in loan_chance_array:
loan_chance = loan_chance_i
th = Threshold_Classifier(
pi_0 = pi_0,
pi_1 = pi_1,
certainty_0 = certainty_0,
certainty_1 = certainty_1,
loan_chance = loan_chance,
group_chance = group_chance,
loan_amount = loan_amount,
interest_rate = interest_rate,
bank_cash = bank_cash )
(updated_pi_0, updated_pi_1) = th.iterate(iterations)
updated_pi_0s.append(updated_pi_0)
updated_pi_1s.append(updated_pi_1)
ones_0.append(updated_pi_0[0])
twos_0.append(updated_pi_0[1])
threes_0.append(updated_pi_0[2])
fours_0.append(updated_pi_0[3])
fives_0.append(updated_pi_0[4])
sixes_0.append(updated_pi_0[5])
sevens_0.append(updated_pi_0[6])
ones_1.append(updated_pi_1[0])
twos_1.append(updated_pi_1[1])
threes_1.append(updated_pi_1[2])
fours_1.append(updated_pi_1[3])
fives_1.append(updated_pi_1[4])
sixes_1.append(updated_pi_1[5])
sevens_1.append(updated_pi_1[6])
data = {'Loan-Chance': loan_chance_array,
'100s': ones_0, '200s': twos_0, '300s': threes_0, '400s': fours_0, '500s': fives_0, '600s': sixes_0, '700s': sevens_0,
'100s-1': ones_1, '200s-1': twos_1, '300s-1': threes_1, '400s-1': fours_1, '500s-1': fives_1, '600s-1': sixes_1, '700s-1': sevens_1}
df = pandas.DataFrame(data=data)
df.to_csv(r'data-loan-chance.csv', index = False)
data_0 = {'Loan-Chance': loan_chance_array,
'100s': ones_0, '200s': twos_0, '300s': threes_0, '400s': fours_0, '500s': fives_0, '600s': sixes_0, '700s': sevens_0}
df_0 = pandas.DataFrame(data=data_0)
data_1 = {'Loan-Chance': loan_chance_array,
'100s-1': ones_1, '200s-1': twos_1, '300s-1': threes_1, '400s-1': fours_1, '500s-1': fives_1, '600s-1': sixes_1, '700s-1': sevens_1}
df_1 = pandas.DataFrame(data=data_1)
for ind, arr in enumerate(updated_pi_0s):
loan_chance_ = loan_chance_array[ind]
objects = ('100', '200', '300', '400', '500', '600', '700')
y_pos = numpy.arange(len(objects))
outcome_ = arr
plt.bar(y_pos, outcome_, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Number of People')
plt.xlabel('Credit Score')
plt.title('Group 0 ' + str(loan_chance_) + " Loan Chance")
plt.savefig('charts-loan-chance/group_0_' + str(loan_chance_) + '.png')
plt.clf()
for ind, arr in enumerate(updated_pi_1s):
loan_chance_ = loan_chance_array[ind]
objects = ('100', '200', '300', '400', '500', '600', '700')
y_pos = numpy.arange(len(objects))
outcome_ = arr
plt.bar(y_pos, outcome_, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Number of People')
plt.xlabel('Credit Score')
plt.title('Group 1 ' + str(loan_chance_) + " Loan Chance")
plt.savefig('charts-loan-chance/group_1_' + str(loan_chance_) + '.png')
plt.clf()
""" |
89753e911ea2dbbb7d45c011286cd46f2d069a71 | EMIKO548/Calculator | /Code3.py | 2,690 | 3.984375 | 4 |
# The author name is Emiko Okoturo
# The purpose of the game is to assess the accuracy of answers to certain literacy and numeracy questions
# The rules of the game is to answer one of the multiple choice questions to gain marks
# The name of the game is General Knowledge Quiz
# This is the 2021 first Release and Emiko Okoturo has copyright
# Defining Score variables
x = 0
score = x
# Question One
print("What is 1 + 1")
answer_1 = input("a)1\nb)2\nc)3\nd)4\n:")
if answer_1.lower() == "b" or answer_1.lower() == "2":
print("Correct")
x = x + 1
else:
print("Incorrect, 1 + 1 is 2")
# Question Two
print("Who is the 45th president of the United States?")
answer_2 = input("a)Barack Obama\nb)Hillary Clinton\nc)Donald Trump\nd)Tom Brady\n:")
if answer_2.lower() == "c" or answer_2.lower() == "donald trump":
print("Correct")
x = x + 1
else:
print("Incorrect, The 45th president is Donald Trump")
# Question Three
print("True or False... The Toronto Maple Leafs have won 13 Stanley Cups?")
answer_3 = input(":")
if answer_3.lower() == "true" or answer_3.lower() == "t":
print("Correct")
x = x + 1
else:
print("Incorrect")
# Question Four
print("What was the last year the Toronto Maple Leafs won the Stanley Cup?")
answer_4 = input("a)1967\nb)1955\nc)1987\nd)1994\n:")
if answer_4.lower() == "a" or answer_4 == "1967":
print("Correct")
x = x + 1
else:
print("Incorrect, The last time the Toronto Maple Leafs won the Stanley Cup was 1967")
# Question Five
print("True or False... The current Prime Minister of Canada is Pierre Elliot Tredeau?")
answer_5 = input(":")
if answer_5.lower() == "false" or answer_5.lower() == "f":
print("Correct")
x = x + 1
else:
print("Incorrect, The current Prime Minster of Canada is Justin Tredeau")
# Question Six
print("What is 10 + 10")
answer_6 = input("a)1\nb)20\nc)3\nd)4\n:")
if answer_6.lower() == "b" or answer_1.lower() == "20":
print("Correct")
x = x + 1
else:
print("Incorrect, 10 + 10 is 20")
# Question Seven
print("True or False... The number one is a Prime Number")
answer_7 = input(":")
if answer_7.lower() == "false" or answer_7.lower() == "f":
print("Correct")
x = x + 1
else:
print("Incorrect, The number one is not a Prime Number")
# Question Eight
print("True or False... The number zero is not a Number")
answer_8 = input(":")
if answer_8.lower() == "false" or answer_7.lower() == "f":
print("Correct")
x = x + 1
else:
print("Incorrect, The number zero is a Number")
#Total Score
score = float(x / 7) * 100
print(x,"out of 7, that is",score, "%") |
064bcdb98819d3c863f7e42e2e684d06d10bea70 | MichaelJamesHart/Python-File-Analyzer | /File_Analyzer.py | 1,680 | 4.03125 | 4 | #Michael Hart
#5/8/2019
# Create the class called FileAnalyzer.
class FileAnalyzer:
# Create the constructor for FileAnalyzer.
def __init__(self, filename):
# Set the filename argument as self.filename.
self.filename = filename
# Open the filename.
file = open(filename)
# Do readlines on the file.
file_contents = file.readlines()
# Create self.linecount to keep track of the number of lines.
self.line_count = 0
# Create self.word_count to keep track of the number of words.
self.word_count = 0
# Iterate through the lines of file_list and add one to self.line_count
# for each line.
for line_index in range(0, len(file_contents)):
self.line_count += 1
# Split the file contents at the current line index into the
# variable current_line.
current_line = file_contents[line_index].split()
self.word_count += len(current_line)
# Create the method filename to return the name of the file.
def get_filename(self):
' returns the file name '
return self.filename
# Create the method get_number_of_lines to return the number of lines.
def get_number_of_lines(self):
' returns the number of lines in the file '
return self.line_count
# Create the method get_number_of_words to return the number of words.
def get_number_of_words(self):
' returns the number of words in the file '
return self.word_count |
6f3b43520f517bb4cc63440ca841092653f06f07 | Anfercode/Codigos-Python | /Clase 1/Capitulo4/Problema/Ejercicio2.py | 275 | 3.703125 | 4 | ##Ejercicio2
Lista = list(range(1,11))
print(f'Los valores de la lista:')
for i in Lista:
print(i,end = '-')
print('\nIngrese un numero')
Numero = int(input('->'))
for Indice,i in enumerate(Lista):
Lista[Indice] *= Numero
Indice +=1
print(f'la lista actual {Lista}') |
db24639a70f71be144d74847e2c67757d29b4982 | Anfercode/Codigos-Python | /Clase 1/Capitulo5/Ejercicio2/Cadenas2.py | 197 | 3.75 | 4 | ### Cadenas
Cadena = 'Andres'
print(Cadena)
print(Cadena[1])
print(Cadena[2])
print(Cadena[5])
print(Cadena[-1])
print(Cadena[0:4])
Cadena = 'a' + Cadena[1:]
print(Cadena)
print(len(Cadena))
|
9c482b69b6342627c6d7aba6c38532efe1cb1de3 | Anfercode/Codigos-Python | /Clase 1/Capitulo1/Problemas/Parcial5.py | 197 | 3.71875 | 4 | #Parte 5
TotalCompra = float(input('Ingrese el valor total de la compra:'))
Descuento = TotalCompra * 0.15
PrecioTotal = int(TotalCompra - Descuento)
print(f'El valor a pagar es {PrecioTotal}') |
7c998ce93da1819233d0b38f9f395c662b41d40d | Anfercode/Codigos-Python | /Clase 1/Capitulo3/Ejercicio2/Listas2.py | 2,546 | 3.640625 | 4 | #Listas parte 2
# Metodo append
print('######### Append ################')
Lista = ['Lunes','Martes','Miercoles','Jueves','Viernes']
Lista.append('Sabado')
Lista.append('Domingo')
print(Lista)
print(len(Lista)) #Longitud lista
print('##################################')
#Metodo insert
print('############insert##############')
Lista2 = ['Lunes','Martes','Jueves','Viernes']
Lista2.insert(2,'Miercoles')
print(Lista2)
print(len(Lista2)) #Longitud lista
print('#################################')
print('############extend##############')
Lista3 = ['Lunes','Martes','Jueves','Viernes']
Lista3.extend(['Sabado','Domingo'])
print(Lista3)
print(len(Lista3)) #Longitud lista
print('################################')
#Suma Listas
print('#############Suma#############')
ListaA = ['Lunes','Martes']
ListaB = ['Miercoles','Jueves']
ListaC = ListaA + ListaB
print(ListaC)
print(len(ListaC)) #Longitud lista
print('################################')
print('############Buscar#############')
Lista3 = ['Lunes','Martes','Jueves','Viernes']
print('Lunes' in Lista3)
print(10 in Lista3)
print('###############################')
print('#############Indice############')
Lista3 = ['Lunes','Martes','Jueves','Viernes']
print(Lista3.index('Lunes'))
print('###############################')
print('############duplicados#########')
Lista3 = ['Lunes','Martes','Jueves','Viernes','Lunes']
print(Lista3.count('Lunes'))
print('###############################')
print('##########Eliminar comn pop#########')
Lista3 = ['Lunes','Martes','Jueves','Viernes','Lunes']
Lista3.pop()
print(Lista3)
Lista3.pop(1)
print(Lista3)
print('###########################')
print('##########Eliminar con remove#########')
Lista3 = ['Lunes','Martes','Jueves','Viernes','Lunes']
Lista3.remove('Lunes')
print(Lista3)
print('###########################')
print('##########Eliminar con clear#########')
Lista3 = ['Lunes','Martes','Jueves','Viernes','Lunes']
Lista3.clear()
print(Lista3)
print('###########################')
print('##########Invertir#########')
Lista3 = ['Lunes','Martes','Jueves','Viernes','Lunes']
Lista3.reverse()
print(Lista3)
print('##########################')
print('##########Multiplicar valores#########')
Lista3 = ['Lunes','Martes','Jueves','Viernes','Lunes']*2
Lista3.reverse()
print(Lista3)
print('##########################')
print('##########ordenar valores#########')
Lista3 = [2,5,6,8,9,7,10]
Lista3.sort()
print(Lista3)
Lista3.sort(reverse=True)
print(Lista3)
print('##########################')
|
0cd0ee2d5346aad4ab1a2cd0eafca811e66b952d | Anfercode/Codigos-Python | /Clase 1/Capitulo5/problemas/Ejercicio3.py | 287 | 4 | 4 | ### Ejercicio3
print('Ingrese una cadena')
Palabra = input('->')
Palabra = Palabra.replace(' ','')
Palindromo = Palabra[::-1]
print(f'La palabra es palindroma {Palindromo}')
if Palabra == Palindromo:
print(f'La palabra es palindromo')
else:
print(f'La palabra no es palindromo')
|
d4839931f400486981a16ff65b571820f59339b8 | Anfercode/Codigos-Python | /Clase 1/Capitulo1/Ejercicio5/OperadoresLog.py | 681 | 3.859375 | 4 | '''
And = Multiplicacion logica
or = Suma Logica
Not = Negacion
^ = Xor(O Exclucivo)
Orden
1-not
2-and
3-or
'''
a = 10
b = 12
c = 13
d = 10
Resultado = ((a > b) or (a < c))and((a == c) or (a >= b))
print(Resultado)
'''
#####################################################################
Prioridad ejecucion operadores Python
1- ()
2- **
3- *, /, %, not
4- +, -, and
5- <, >, ==,>=,<=,!=,or
######################################################################
'''
a = 10
b = 15
c = 20
Resultado = ((a>b)and(b<c))
print(Resultado)
Resultado = ((a>b)or(b<c))
print(Resultado)
Resultado = ((a>b)^(b>c))
print(Resultado)
Resultado = not((a>b)^(b>c))
print(Resultado) |
135af905c1f8e376476121b501069777489181f1 | Anfercode/Codigos-Python | /Clase 1/Capitulo4/Ejercicio3/BucleForRange.py | 156 | 3.65625 | 4 | ## For tipo range
for i in range(50):
print(f'{i+1} hola mundo')
print('##########################')
for i in range(10,0,-2):
print(f'{i} hola mundo') |
89c46932e554053b46bd1aee59151117e582df75 | Anfercode/Codigos-Python | /Clase 1/Capitulo4/Problema/Ejercicio3.py | 583 | 4 | 4 | ##Ejercicio 3
print('Inserte el numero en la lista')
valor = int(input('->'))
Lista = []
while valor != 0:
Lista.append(valor)
print('Inserte otro valor')
valor = int(input('->'))
Lista.sort()
print(f'La lista ordenada es {Lista}')
############################################
#Solucion Elegante
############################################+
Lista = []
salir = False
while not salir:
print('Inserte el numero en la lista')
valor = int(input('->'))
if valor == 0:
salir = True
else:
Lista.append(valor)
Lista.sort()
print(f'La lista ordenada es {Lista}')
|
18b51b8466ed986ae9f73762addf081c3a3cd932 | Anfercode/Codigos-Python | /Clase 1/Capitulo6/Problemas/Ejercicio5.py | 195 | 3.546875 | 4 | ## Ejercicio 5
def SumaRecursiva(Num):
if Num == 0:
f = 0
else:
f = SumaRecursiva(round(Num/10)) + (Num%10)
return f
a = int(input('Ingrese un numero -> '))
print(SumaRecursiva(a))
|
2f97a8cfd7d232be452f8297a9bb3d7f0d6bccf6 | Anfercode/Codigos-Python | /Clase 1/Capitulo3/Problemas/Ejercicio2.py | 540 | 4.03125 | 4 | #Ejercicio 2
ListaA = [1,2,3,4,5]
ListaB = [4,5,6,7,8]
print(f'valores lista 1 {ListaA}')
print(f'valores lista 2 {ListaB}')
#Conjuntos
Conjunto1 = set(ListaA)
Conjunto2 = set(ListaB)
#Lista unida
ListaU = list(Conjunto1 | Conjunto2)
print(f'Lista unida {ListaU}')
#Lista Left
ListaL = list(Conjunto1 - Conjunto2)
print(f'Lista izquierda {ListaL}')
#Lista Right
ListaR = list(Conjunto2 - Conjunto1)
print(f'Lista derecha {ListaR}')
#Lista valores comunes
ListaI = list(Conjunto1 & Conjunto2)
print(f'Lista valores {ListaI}') |
19317c08a5a8450948c644a342acec928123e855 | lyukov/computer_vision_intro | /07-Backprop/solution.py | 8,277 | 3.609375 | 4 | from interface import *
# ================================ 2.1.1 ReLU ================================
class ReLU(Layer):
def forward(self, inputs):
"""
:param inputs: np.array((n, ...)), input values,
n - batch size, ... - arbitrary input shape
:return: np.array((n, ...)), output values,
n - batch size, ... - arbitrary output shape (same as input)
"""
# your code here \/
return inputs.clip(0)
# your code here /\
def backward(self, grad_outputs):
"""
:param grad_outputs: np.array((n, ...)), dLoss/dOutputs,
n - batch size, ... - arbitrary output shape
:return: np.array((n, ...)), dLoss/dInputs,
n - batch size, ... - arbitrary input shape (same as output)
"""
# your code here \/
inputs = self.forward_inputs
return grad_outputs * (inputs > 0)
# your code here /\
# ============================== 2.1.2 Softmax ===============================
class Softmax(Layer):
def forward(self, inputs):
"""
:param inputs: np.array((n, d)), input values,
n - batch size, d - number of units
:return: np.array((n, d)), output values,
n - batch size, d - number of units
"""
# your code here \/
tmp = np.exp(inputs).T
return (tmp / tmp.sum(axis=0)).T
# your code here /\
def backward(self, grad_outputs):
"""
:param grad_outputs: np.array((n, d)), dLoss/dOutputs,
n - batch size, d - number of units
:return: np.array((n, d)), dLoss/dInputs,
n - batch size, d - number of units
"""
# your code here \/
outputs = self.forward_outputs
n, d = outputs.shape
tmp = -np.matmul(outputs.reshape((n, d, 1)), outputs.reshape((n, 1, d)))
tmp += np.eye(d) * outputs.reshape((n, d, 1))
return np.matmul(grad_outputs.reshape((n, 1, d)), tmp).reshape((n, d))
# your code here /\
# =============================== 2.1.3 Dense ================================
class Dense(Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.output_shape = (units,)
self.weights, self.weights_grad = None, None
self.biases, self.biases_grad = None, None
def build(self, *args, **kwargs):
super().build(*args, **kwargs)
input_units, = self.input_shape
output_units, = self.output_shape
# Register weights and biases as trainable parameters
# Note, that the parameters and gradients *must* be stored in
# self.<p> and self.<p>_grad, where <p> is the name specified in
# self.add_parameter
self.weights, self.weights_grad = self.add_parameter(
name='weights',
shape=(input_units, output_units),
initializer=he_initializer(input_units)
)
self.biases, self.biases_grad = self.add_parameter(
name='biases',
shape=(output_units,),
initializer=np.zeros
)
def forward(self, inputs):
"""
:param inputs: np.array((n, d)), input values,
n - batch size, d - number of input units
:return: np.array((n, c)), output values,
n - batch size, c - number of output units
"""
# your code here \/
batch_size, input_units = inputs.shape
output_units, = self.output_shape
return np.matmul(inputs, self.weights) + self.biases
# your code here /\
def backward(self, grad_outputs):
"""
:param grad_outputs: np.array((n, c)), dLoss/dOutputs,
n - batch size, c - number of output units
:return: np.array((n, d)), dLoss/dInputs,
n - batch size, d - number of input units
"""
# your code here \/
batch_size, output_units = grad_outputs.shape
input_units, = self.input_shape
inputs = self.forward_inputs
# Don't forget to update current gradients:
# dLoss/dWeights
self.weights_grad = np.matmul(
grad_outputs.reshape(batch_size, output_units, 1),
inputs.reshape(batch_size, 1, input_units)
).mean(axis=0).T
# dLoss/dBiases
self.biases_grad = grad_outputs.mean(axis=0)
return np.matmul(grad_outputs, self.weights.T)
# your code here /\
# ============================ 2.2.1 Crossentropy ============================
class CategoricalCrossentropy(Loss):
def __call__(self, y_gt, y_pred):
"""
:param y_gt: np.array((n, d)), ground truth (correct) labels
:param y_pred: np.array((n, d)), estimated target values
:return: np.array((n,)), loss scalars for batch
"""
# your code here \/
batch_size, output_units = y_gt.shape
return -(y_gt * np.log(1e-10 + y_pred)).sum(axis=1)
# your code here /\
def gradient(self, y_gt, y_pred):
"""
:param y_gt: np.array((n, d)), ground truth (correct) labels
:param y_pred: np.array((n, d)), estimated target values
:return: np.array((n, d)), gradient loss to y_pred
"""
# your code here \/
return - y_gt / (1e-10 + y_pred)
# your code here /\
# ================================ 2.3.1 SGD =================================
class SGD(Optimizer):
def __init__(self, lr):
self._lr = lr
def get_parameter_updater(self, parameter_shape):
"""
:param parameter_shape: tuple, the shape of the associated parameter
:return: the updater function for that parameter
"""
def updater(parameter, parameter_grad):
"""
:param parameter: np.array, current parameter values
:param parameter_grad: np.array, current gradient, dLoss/dParam
:return: np.array, new parameter values
"""
# your code here \/
assert parameter_shape == parameter.shape
assert parameter_shape == parameter_grad.shape
return parameter - self._lr * parameter_grad
# your code here /\
return updater
# ============================ 2.3.2 SGDMomentum =============================
class SGDMomentum(Optimizer):
def __init__(self, lr, momentum=0.0):
self._lr = lr
self._momentum = momentum
def get_parameter_updater(self, parameter_shape):
"""
:param parameter_shape: tuple, the shape of the associated parameter
:return: the updater function for that parameter
"""
def updater(parameter, parameter_grad):
"""
:param parameter: np.array, current parameter values
:param parameter_grad: np.array, current gradient, dLoss/dParam
:return: np.array, new parameter values
"""
# your code here \/
assert parameter_shape == parameter.shape
assert parameter_shape == parameter_grad.shape
assert parameter_shape == updater.inertia.shape
# Don't forget to update the current inertia tensor:
updater.inertia = self._momentum * updater.inertia + self._lr * parameter_grad
return parameter - updater.inertia
# your code here /\
updater.inertia = np.zeros(parameter_shape)
return updater
# ======================= 2.4 Train and test on MNIST ========================
def train_mnist_model(x_train, y_train, x_valid, y_valid):
# your code here \/
# 1) Create a Model
model = Model(CategoricalCrossentropy(), SGDMomentum(0.001, 0.5))
# 2) Add layers to the model
# (don't forget to specify the input shape for the first layer)
model.add(Dense(32, input_shape=(784,)))
model.add(ReLU())
model.add(Dense(10))
model.add(Softmax())
# 3) Train and validate the model using the provided data
model.fit(x_train, y_train, batch_size=30, epochs=2, x_valid=x_valid, y_valid=y_valid)
# your code here /\
return model
# ============================================================================
|
733197a71573e6a06aa87f249e7e960e73f10a9e | luizlibardi/diagnostico | /diagnostico.py | 2,569 | 3.953125 | 4 | """
Diagnóstico proposto na aula de Estrutura de Dados 1 - UCL, pelo professor André Ribeiro para nivelar o conhecimento da turma.
"""
# Entrada de dados pelo Usuário
eleitores_consultados = int(input('Quantos eleitores foram consultados? '))
votos_branco = int(input('Quantos votos foram em branco? '))
indecisos = int(input('Quantos votos foram indecisos? '))
# Classe para a criação dos candidatos
class Candidatos:
codigo = 1
def __init__(self, codigo, nome, intencoes):
"""[Construtor de candidatos"""
self._codigo = codigo
self._nome = nome
self._intencoes = intencoes
def get_codigo(self):
"""Função que retorna o código do candidato"""
return self._codigo
def get_nome(self):
"""Função que retorna o nome do candidato"""
return self._nome
def get_intencoes(self):
"""Função que retorna a quantidade de intenções de votos do candidato"""
return self._intencoes
candidatos = []
codigo = None
# Loop para o usuário fazer a criação dos candidatos
while codigo != 0:
codigo = int(input('\nCódigo do candidato: '))
if codigo != 0:
nome = input('Nome do candidato: ')
intencoes = int(input('Quantidade de intenções de votos: '))
candidato = Candidatos(codigo, nome, intencoes)
candidatos.append(candidato)
def total_votos():
"""Função que retorna o total de votos"""
return eleitores_consultados + votos_branco + indecisos
def percentual_branco():
"""Função que retorna o a porcentagem de votos em branco"""
return f'{((votos_branco * 100) / total_votos())}% - Votos em Branco'
def percentual_indecisos():
"""Função que retorna o a porcentagem de votos indecisos"""
return f'{((indecisos * 100) / total_votos())}% - Indecisos\n'
lista_votos = []
# Letra A) Retorno '%Votos - Nome'
for candidato in candidatos:
percentual_voto = ((candidato.get_intencoes() * 100) / total_votos())
print(f'{percentual_voto}% - {candidato.get_nome()}')
lista_votos.append(percentual_voto)
if percentual_voto > 50:
print(f'O candidato {candidato.get_nome()} possui alta probabilidade de eleição no primeiro turno') # Letra B)
percentual_branco()
percentual_indecisos()
# Letra C)
if max(lista_votos) - min(lista_votos) < 10:
print('\nFoi verificado um cenário de grande equilíbrio entre as escolhas dos eleitores')
# Letra D
if lista_votos == sorted(lista_votos):
print('O registro foi realizado em ordem crescente de número de intenções de votos')
|
3daf750ca30fb29c006bc064fd5a2168bc7787ec | Yu4n/Algorithms | /LeetCode_in_py/levelOrder.py | 550 | 3.5625 | 4 | from definition import TreeNode
class Solution:
def levelOrder(self, root: TreeNode) -> [[int]]:
if not root:
return []
res = []
queue = [root]
while queue:
level = []
k = len(queue)
for i in range(k):
if queue[0].left:
queue.append(queue[0].left)
if queue[0].right:
queue.append(queue[0].right)
level.append(queue.pop(0).val)
res.append(level)
return res
|
cd11542b28904b0865526267ec5db987183b714d | Yu4n/Algorithms | /CLRS/bubblesort.py | 647 | 4.25 | 4 | # In bubble sort algorithm, after each iteration of the loop
# largest element of the array is always placed at right most position.
# Therefore, the loop invariant condition is that at the end of i iteration
# right most i elements are sorted and in place.
def bubbleSort(ls):
for i in range(len(ls) - 1):
for j in range(0, len(ls) - 1 - i):
if ls[j] > ls[j + 1]:
ls[j], ls[j + 1] = ls[j + 1], ls[j]
'''for j in range(len(ls) - 1, i, -1):
if ls[j] < ls[j - 1]:
ls[j], ls[j - 1] = ls[j - 1], ls[j]'''
a = [5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
bubbleSort(a)
print(a)
|
c4c2d415fae659242f90496011427973f76442f4 | Yu4n/Algorithms | /CLRS/heapsort.py | 1,611 | 3.640625 | 4 | import math
def max_heapify(a, n, i):
heapSize = n
left = 2 * i + 1
right = 2 * i + 2
if left < heapSize and a[i] < a[left]:
largest = left
else:
largest = i
# if a[largest] < a[right] and right < heapSize:
# Be careful of the conditional statement above, which causes list out of range!
if right < heapSize and a[largest] < a[right]:
largest = right
if largest != i:
a[i], a[largest] = a[largest], a[i]
max_heapify(a, n, largest)
def build_max_heap(a):
for i in range(len(a) // 2 - 1, -1, -1):
max_heapify(a, len(a) - 1, i)
def heapsort(a):
build_max_heap(a)
for i in range(len(a) - 1, 0, -1):
a[0], a[i] = a[i], a[0]
max_heapify(a, i, 0)
def heap_maximum(a,):
return a[0]
def heap_extract_max(a, heapsize=None):
if heapsize is None:
heapsize = len(a)
if heapsize < 1:
return -1
max_value = a[0]
a[0] = a[heapsize - 1]
del(a[heapsize - 1])
heapsize -= 1
max_heapify(a, heapsize, 0)
return max_value
def heap_increase_key(a, i, key):
if key < a[i]:
return -1
a[i] = key
while i > 0 and a[(i - 1) // 2] < a[i]:
a[i], a[(i - 1) // 2] = a[(i - 1) // 2], a[i]
i = (i - 1) // 2
def max_heap_insert(a, key):
a.append(- math.inf)
heap_increase_key(a, len(a) - 1, key)
if __name__ == '__main__':
arr = [12, 11, 13, 20, 20, 50, 7, 4, 3, 2, 1, -1]
build_max_heap(arr)
print(arr)
heap_increase_key(arr, len(arr) - 1, 100)
print(arr)
max_heap_insert(arr, 101)
print(arr)
|
0519e8f7b081b8a2aefff895109c1fb8900580fd | Yu4n/Algorithms | /LeetCode_in_py/reorderSpaces.py | 375 | 3.578125 | 4 | class Solution:
def reorderSpaces(self, text: str) -> str:
space_count = text.count(' ')
words = text.split()
if len(words) == 1:
return words[0] + ' ' * space_count
spaces, tail = divmod(space_count, len(words) - 1)
return (' ' * spaces).join(words) + ' ' * tail
sln = Solution()
print(sln.reorderSpaces(" hello"))
|
69fe06f4d308eca042f3bf0c30f4a207d65473ac | Yu4n/Algorithms | /CLRS/insertion_sort.py | 1,175 | 4.3125 | 4 | # Loop invariant is that the subarray A[0 to i-1] is always sorted.
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Driver code to test above
def insertionSortRecursive(arr, n):
# base case
if n <= 1:
return
# Sort first n-1 elements
insertionSortRecursive(arr, n - 1)
'''Insert last element at its correct position
in sorted array.'''
key = arr[n - 1]
j = n - 2
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = key
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print(arr)
arr2 = [6, 5, 4, 3, 2, 1, 0, -1]
insertionSortRecursive(arr2, len(arr2))
print(arr2)
|
5de1abee9eb8659869f545a868aa9caaf747f517 | cjrokke/Prime-Time-Project | /GUI.py | 1,069 | 3.53125 | 4 | # Project Name: Prime-Time-Project
# File: GUI.py
# NOTE: this is our graphical user interface
import index
from Tkinter import * # Importing the Tkinter (tool box) library
#might need be "tkinter"
root = Tk() # Creats object root that has properties for the window. Access via .instr
# configuration portion
root.font = ('Verdana', '20', 'bold') #changes the font for ALL text belonging to root
def pfunction():
pass # some code here hitting yes, pass just means no code is running here
return
def npfunction():
pass # just pass this function for now
return
Ybutton = Button(root, text="Prime", command=pfunction(), fg='blue', bg='green',).pack() #currently packed just to populate the message box
Nbutton = Button(root, text="Not-Prime", command=npfunction(), fg='black', bg='red').pack() #need to link to functions
#above for functionallity
root.mainloop() # Execute the main event handler
|
27f4ba9581b020bdb3ade1e68b58fae844a26f84 | dmentipl/phantom-setup | /phantomsetup/sinks.py | 1,395 | 3.703125 | 4 | """Sink particles."""
from typing import Tuple
class Sink:
"""Sink particles.
Parameters
----------
mass
The sink particle mass.
accretion_radius
The sink particle accretion radius.
position
The sink particle position.
velocity
The sink particle velocity.
"""
def __init__(
self,
*,
mass: float,
accretion_radius: float,
position: Tuple[float, float, float] = None,
velocity: Tuple[float, float, float] = None
):
self._mass = mass
self._accretion_radius = accretion_radius
if position is not None:
self._position = position
else:
self._position = (0.0, 0.0, 0.0)
if velocity is not None:
self._velocity = velocity
else:
self._velocity = (0.0, 0.0, 0.0)
@property
def mass(self) -> float:
"""Sink particle mass."""
return self._mass
@property
def accretion_radius(self) -> float:
"""Sink particle accretion radius."""
return self._accretion_radius
@property
def position(self) -> Tuple[float, float, float]:
"""Sink particle position."""
return self._position
@property
def velocity(self) -> Tuple[float, float, float]:
"""Sink particle velocity."""
return self._velocity
|
cd1c431b1eb29a17410d8d584b89c8fdf65fd7c5 | Siaperas/Ternary-Huffman-Encoding-To-Store-DNA | /ternary_huffman.py | 6,981 | 3.59375 | 4 | import argparse
import csv
class Node:
def __init__(self, chara=None, number=None, child_1=None, child_2=None, child_3=None):
self.chara = chara
self.number = number
self.child_1 = child_1
self.child_2 = child_2
self.child_3 = child_3
def is_leaf(self):
return self.child_1 == self.child_2 == self.child_3 == None
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-d', default=None,
action='store_true', help='Decoding.')
parser.add_argument('input', help='The input file.')
parser.add_argument('output', help='The output file.')
parser.add_argument('huffman', help='The huffman file.')
args = parser.parse_args()
return args.d, args.input, args.output, args.huffman
def makeList(tree):
paths = []
if not (tree.child_1 or tree.child_2 or tree.child_3):
return [[tree.chara]]
if tree.child_1:
paths.extend([["0"] + child for child in makeList(tree.child_1)])
if tree.child_2:
paths.extend([["1"] + child for child in makeList(tree.child_2)])
if tree.child_3:
paths.extend([["2"] + child for child in makeList(tree.child_3)])
return paths
decoding, inputfile, outputfile, huffman = parse_args()
if decoding == None:
info = ""
with open(inputfile, 'r') as myfile:
info = myfile.read()
char = []
freq = []
for i in info:
if i in char:
index = char.index(i)
freq[index] = freq[index] + 1
else:
char.append(i)
freq.append(1)
if (len(char) % 2 == 0):
char.append("")
freq.append(0)
freq, char = zip(*sorted(zip(freq, char)))
char2 = []
freq2 = []
for i in char:
char2.append(i)
for i in freq:
freq2.append(i)
nodes = []
for i in range(len(char)):
node = Node(chara=char2[i], number=freq2[i])
nodes.append(node)
nodes2 = []
for i in nodes:
nodes2.append(i)
while(len(nodes2) > 0):
if(len(nodes2) >= 3):
summ = nodes2[0].number + nodes2[1].number + nodes2[2].number
new_node = Node(
number=summ, child_1=nodes2[0], child_2=nodes2[1], child_3=nodes2[2])
nodes2.pop(0)
nodes2.pop(0)
nodes2.pop(0)
nodes.append(new_node)
nodes2.append(new_node)
nodes2 = sorted(nodes2, key=lambda x: (x.number, x.chara))
if(len(nodes2) == 1):
break
nodes = sorted(nodes, key=lambda x: (x.number, x.chara), reverse=True)
root = nodes[0]
list1 = []
list1 = makeList(root)
list2 = []
list3 = []
for i in list1:
list2.append(i[len(i) - 1])
toadd = ""
print i
for j in range(len(i) - 1):
toadd = toadd + str(i[j])
list3.append(toadd)
with open(huffman, 'wb') as csvfile:
fieldnames = ['character', 'tri']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
for i in range(len(list1)):
writer.writerow({'character': list2[i], 'tri': list3[i]})
trihuffman = ""
for i in info:
for j in range(len(list2)):
if(i == list2[j]):
trihuffman = trihuffman + list3[j]
currentdna = "A"
result = ""
for t in trihuffman:
if (currentdna == "A"):
if(t == "0"):
currentdna = "C"
result = result + "C"
elif(t == "1"):
currentdna = "G"
result = result + "G"
elif(t == "2"):
currentdna = "T"
result = result + "T"
elif (currentdna == "C"):
if(t == "0"):
currentdna = "G"
result = result + "G"
elif(t == "1"):
currentdna = "T"
result = result + "T"
elif(t == "2"):
currentdna = "A"
result = result + "A"
elif (currentdna == "G"):
if(t == "0"):
currentdna = "T"
result = result + "T"
elif(t == "1"):
currentdna = "A"
result = result + "A"
elif(t == "2"):
currentdna = "C"
result = result + "C"
elif (currentdna == "T"):
if(t == "0"):
currentdna = "A"
result = result + "A"
elif(t == "1"):
currentdna = "C"
result = result + "C"
elif(t == "2"):
currentdna = "G"
result = result + "G"
f = open(outputfile, 'w')
f.write(result)
else:
info = ""
with open(inputfile, 'r') as myfile:
info = myfile.read()
currentdna = "A"
result = ""
for t in info:
if (currentdna == "A"):
if(t == "C"):
currentdna = "C"
result = result + "0"
elif(t == "G"):
currentdna = "G"
result = result + "1"
elif(t == "T"):
currentdna = "T"
result = result + "2"
elif (currentdna == "C"):
if(t == "G"):
currentdna = "G"
result = result + "0"
elif(t == "T"):
currentdna = "T"
result = result + "1"
elif(t == "A"):
currentdna = "A"
result = result + "2"
elif (currentdna == "G"):
if(t == "T"):
currentdna = "T"
result = result + "0"
elif(t == "A"):
currentdna = "A"
result = result + "1"
elif(t == "C"):
currentdna = "C"
result = result + "2"
elif (currentdna == "T"):
if(t == "A"):
currentdna = "A"
result = result + "0"
elif(t == "C"):
currentdna = "C"
result = result + "1"
elif(t == "G"):
currentdna = "G"
result = result + "2"
huffmandict = {}
with open(huffman, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
huffmandict[row[0]] = row[1]
check = ""
finalresult = ""
for i in result:
check = check + i
try:
finalresult = finalresult + \
list(huffmandict.keys())[
list(huffmandict.values()).index(check)]
check = ""
except ValueError:
aaaa = 1
f = open(outputfile, 'w')
f.write(finalresult)
|
a844b9441a692e542d9c7b866a8f31fc92e0640a | sharifahblessing/practice | /agecal.py | 223 | 3.90625 | 4 | def ageCalculator(birth_year):
current = 2018
if isinstance(birth_year, int):
if birth_year <= current:
age = current - birth_year
return age
return None
print(ageCalculator(2000)) |
613a487676ab9af7df36d71a4a1cd4ca8c31c21c | Fer95/Ejercicios-de-recursividad | /MCD.py | 207 | 3.921875 | 4 | def mcd(a,b):
if b==0:
return a
else:
return mcd(b,a%b)
a= int(input("Ingrese el primer número"))
b= int (input("ingrese el segundo número"))
print ("El MCD ES :",mcd(a,b))
|
963cc758d023a6b1c526aee1f0404c9dd38cee60 | PG80/Training_and_Homework | /2019_03_27_some_works.py | 233 | 3.859375 | 4 | a=2
b=7
t=a
a=b
b=t
print(a,b)
print('load data')
side1 = float(input("Load side1: "))
side2 = float(input("Load side2: "))
side3 = float(input("Load side3: "))
p = side1 + side2 + side3
print(p)
abc=int(input())
print(abc * abc)
|
3b518e89e5fa903fcdbef5e2e33d7e1732f1d8e0 | PG80/Training_and_Homework | /2019_03_17_handling_exceptions.py | 501 | 4.0625 | 4 | while True:
try:
age = int(input('Enter your age: '))
if age > 21:
print('A Big answer!')
if age < 21:
print('A small answer!')
if age == 21:
print('Correct answer!')
if age < 0:
raise ValueError ('Incorrect age!')
except ValueError as error:
print('Error')
print(error)
# else:
# break
finally:
print('Thanks anyway!')
else:
print('Not correct answer. ')
|
f8fdb0c0de904238599085e8af989d252ec137a2 | thepiyush13/ds-python | /queues.py | 888 | 3.921875 | 4 | import random
# Create a queue and implement it
class Queue:
def __init__(self):
self.data = []
def enqueue(self,item):
# put at end of the queue
self.data.insert(0,item)
def dequeue(self):
# pop from last element
return self.data.pop()
def isEmpty():
# length of current queue
return self.data == []
def size(self):
return len(self.data)
def create_queue():
x = Queue()
for i in range(0,10):
# x.enqueue(random.randrange(0,10))
x.enqueue(i)
return x
def print_q(item):
x = ''
for i in range(item.size()):
x = x+ ' ' +str(item.dequeue())
print x
# reverse the queue
def reverse_q(item):
x = []
for i in range(item.size()):
x.append(item.dequeue())
j = len(x)-1
while(j>0):
print x[j]
j = j-1
myq = create_queue()
# print_q(myq)
reverse_q(myq)
|
6d73c42b23c0933eae4ac3ead5f65520ed8de7d0 | mohamed-elrifai/Exploring-US-Bikeshare-Data | /bikeshare.py | 9,020 | 4.25 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# Get user input for city (chicago, new york city, washington).
# Make sure the Input is valid
cities = ('chicago' , 'new york city' , 'washington')
while True:
city = input("PLEASE ENTER CITY NAME 'Chicago, New york city or Washington': ")
city = city.lower().strip()
if city not in cities:
print("Invalid city....PLEASE TRY AGAIN!")
else:
break
print("You choose {}".format(city.title()) )
# Get user input for month (all, january, february, ... , june)
# Make sure the Input is valid
months = ('all', 'january' , 'february' , 'march' , 'april' , 'may' , 'june')
while True:
month = input("PLEASE ENTER MONTH 'from january to june' or 'all': ")
month = month.lower().strip()
if month not in months:
print("Invalid month....PLEASE TRY AGAIN!")
else:
break
print("You choose {}".format(month.title()) )
# Get user input for day of week (all, monday, tuesday, ... sunday)
# Make sure the Input is valid
days = ['all', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
while True:
day = input("PLEASE ENTER DAY or 'all': ")
day = day.lower().strip()
if day not in days:
print("Invalid day....PLEASE TRY AGAIN!")
else:
break
print("You choose {}".format(day.title()) )
print('-'*40)
return city , month , day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# Reading CSV File
df = pd.read_csv(CITY_DATA[city])
# Change Start Time colomn to datetime in Pandas
df['Start Time'] = pd.to_datetime(df['Start Time'])
# Create a new coloumns 'month' , 'day_of_week' and 'hour' then get the data from 'Start Time' colomn
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.day_name()
df['hour'] = df['Start Time'].dt.hour
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
# Add a new coloumn 'Start to End Station' to save each trip from start to end
df['Trip Stations'] = 'From ' + df['Start Station'] + ' to ' + df['End Station']
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# Very impotant note : 'month' coloumn is the number of month
# Display the most common month
months = ['january', 'february', 'march', 'april', 'may', 'june']
index_of_most_common_month = df['month'].mode()[0]
most_common_month = months[index_of_most_common_month - 1]
print('Most common month is : {} .'.format(most_common_month.upper()) )
# Very impotant note : 'day_of_week' coloumn is the name of day
# Display the most common day of week
most_common_day = df['day_of_week'].mode()[0]
print('Most common day of week is : {} .'.format(most_common_day.upper()) )
# TDisplay the most common start hour
most_common_start_hour = df['hour'].mode()[0]
print('Most common start hour is : {} .'.format(most_common_start_hour) )
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# Display most commonly used start station *From 'Start Station' coloumn*
most_common_start_station = df['Start Station'].mode()[0]
print('Most common start station is : {} .'.format(most_common_start_station) )
# Display most commonly used end station *From 'End Station' coloumn*
most_common_end_station = df['End Station'].mode()[0]
print('Most common end station is : {} .'.format(most_common_end_station) )
# Display most frequent combination of start station and end station trip *From 'Trip Stations' coloumn*
most_common_trip_stations = df['Trip Stations'].mode()[0]
print('Most common trip stations is : {} .'.format(most_common_trip_stations) )
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# Display total travel time *From 'Trip Duration' coloumn*
total_travel_time = df['Trip Duration'].sum()
print("Total travel time = {} min".format(total_travel_time / 60.00) )
# Display mean travel time *From 'Trip Duration' coloumn*
# df.describe() ==> [0] == count , [1] == mean , [2] == std
mean_travel_time = df['Trip Duration'].describe()[1]
print("Mean travel time = {} min".format(mean_travel_time / 60.00) )
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types *From 'User Type' coloumn*
# df['User Type'].value_counts() ==> [0] == Subscriber , [1] == Customer , [2] == Dependent
subscriber = df['User Type'].value_counts()[0]
customer = df['User Type'].value_counts()[1]
#dependent = df['User Type'].value_counts()[2]
print("Number of SUBSCRIBERS : {} ".format(subscriber))
print("Number of CUSTOMERS : {} ".format(customer))
#print("Number of DEPENDENT : {} \n".format(dependent))
# Just if city is 'Chicago' or 'New york city'
# Display counts of gender *From 'Gender' coloumn*
# df['Gender'].value_counts() ==> [0] == male , [1] == female
if 'Gender' in df:
male = df['Gender'].value_counts()[0]
female = df['Gender'].value_counts()[1]
print("Number of MALES : {}".format(male))
print("Number of FEMALES : {} \n".format(female))
# Just if city is 'Chicago' or 'New york city'
# Display earliest, most recent, and most common year of birth *From 'Birth Year' coloumn*
# df['Birth Year'].describe() ==> [3] == min , [7] == max
if 'Birth Year' in df:
most_common_year_of_birth = df['Birth Year'].mode()[0]
youngest = df['Birth Year'].describe()[7]
oldest = df['Birth Year'].describe()[3]
print("Most common year of birth : {}".format(most_common_year_of_birth))
print("Earliest year of birth : {}".format(oldest))
print("Most recent year of birth : {}".format(youngest))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def display_raw_data(city):
print("Random raw data is available to check...\n")
repeat = 'yes'
while repeat == 'yes':
for chunk in pd.read_csv(CITY_DATA[city] , chunksize = 5):
print(chunk)
repeat = input("Do you want too check another raw data? 'yes or no' ")
if repeat == 'no':
break;
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
display_raw_data(city)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
ce1184176759a7fe316056610e5a3338a1b05128 | nwautomator/PyUrDHT | /services/chord/chordspacemath.py | 1,623 | 3.515625 | 4 |
"""
PLEASE READ THE FOLLOWING ASSUMPTIONS
Chord exists in a 1-d ring
All functions that do any useful math use the location of the node in this ring
the location is a base 10 int, not the actual hash
"""
import pymultihash as multihash
# TODO don't assume max is 160
KEYSIZE = 256
MAX = 2 ** KEYSIZE
def idToPoint(id):
"""
Converts a hashkey into some point
Keyword Arguments:
id -- the multihash id/key of a node/value
"""
idLong = multihash.parseHash(id)
return idLong
def isPointBetween(target, left, right):
assert isinstance(target, int)
if left == right:
return True
if target == left or target == right:
return False
if target < right and target > left:
return True
if left > right:
if left > target and target < right:
return True
if left < target and target > right:
return True
return False
def isPointBetweenRightInclusive(target, left, right):
if target == right:
return True
return isPointBetween(target, left, right)
def distance(origin, destination):
"""
measures the distance it takes to get to the destination
traveling from origin
"""
assert(isinstance(origin, int))
dist = destination - origin
if dist < 0:
return MAX + dist
return dist
def getClosest(point, candidates):
"""Returns the candidate closest to point without going over."""
return min(candidates, key=lambda x: distance(x.loc, point))
def getBestSuccessor(point, candidates):
return min(candidates, key=lambda x: distance(point, x.loc))
|
46fd209659f3dd4ca466d6ca7e7af8f23c661238 | mverini94/PythonProjects | /DesignWithFunctions.py | 2,401 | 4.65625 | 5 | '''
Author....: Matt Verini
Assignment: HW05
Date......: 3/23/2020
Program...: Notes from Chapter 6 on Design With Functions
'''
'''
Objectives for this Chapter
1.) Explain why functions are useful in structuring code in a program
2.) Employ a top-down design design to assign tasks to functions
3.) Define a recursive function
4.) Explain the use of the namespace in a program and exploit it effectively
5.) Define a function with required and optional parameters
6.) Use higher-order fuctions for mapping, filtering, and reducing
- A function packages an algorithm in a chunk of code that you can call by name
- A function can be called from anywhere in a program's code, including code
within other functions
- A function can receive data from its caller via arguments
- When a function is called, any expression supplied as arguments are first
evaluated
- A function may have one or more return statements
'''
def summation(lower, upper):
result = 0
while lower <= upper:
result += lower #result = result + lower
lower += 1 #lower = lower + 1
print(result)
summation(1, 4)
'''
- An algorithm is a general method for solving a class of problems
- The individual problems that make up a class of problems are known
as problem instances
- What are the problem instances of our summation algorithm?
- Algorithms should be general enough to provide a solution to many
problem instances
- A function should provide a general method with systematic variations
- Each function should perform a single coherent task
- Such as how we just computed a summation
'''
'''
TOP-DOWN Design starts with a global view of the entire problem and
breaks the problem into smaller, more manageable subproblems
- Process known as problem decomposition
- As each subproblem is isolated, its solution is assigned to a function
- As functions are developed to solve subproblems, the solution to the
overall problem is gradually filled ot.
- Process is also called STEPWISE REFINEMENT
- STRUCTURE CHART - A diagram that shows the relationship among a
program's functions and the passage of data between them.
- Each box in the structure is labeled with a function name
- The main function at the top is where the design begins
- Lines connecting the boxes are labeled with data type names
- Arrows indicate the flow of data between them
'''
|
57655a927915dff5ff3ed3ca426573b3f3f156ca | mverini94/PythonProjects | /Lab09StudentClassBCS109Verini.py | 3,556 | 4.28125 | 4 | '''
Author....: Matt Verini
Assignment: Lab09 Student Class
Date......: 04/11/2020
Program...: Student Class with Methods
'''
'''
Add three methods to the Student class that compare two objects.
One method should test for equality. A second method should test
less than. The third method should test for greater than or equal
to. In each case, the method returns the result of the comparison
of the two student's names. Include a main function that test all
restrictedsavingsaccount.py
'''
'''
This project assumes that you have completed assignment 9.1. Place
several Student objects into a list and shuffle it. Then run the
sort method with this list and display all of the student's info.
'''
import random
class Student(object):
"""Represents a student."""
def __init__(self, m_name, number):
"""All scores are initially 0."""
self.name = m_name
self.scores = []
for count in range(number):
self.scores.append(0)
def getName(self):
"""Returns the student's name."""
return self.name
def setScore(self, index, score):
"""Resets the ith score, counting from 1."""
self.scores[index - 1] = score
def getScore(self, index):
"""Returns the ith score, counting from 1."""
return self.scores[index - 1]
def getAverage(self):
"""Returns the average score."""
return sum(self.scores) / len(self._scores)
def getHighScore(self):
"""Returns the highest score."""
return max(self.scores)
"""Checks to see if two objects are equal"""
def __eq__(self, student):
if self is student:
return True
elif type(self) != type(student):
return False
return self.name == student.name
"""Checks to see if an object is less than another."""
def __lt__(self, student):
return self.name < student.name
"""Checks to see if an object is Greater than or Equal
to another."""
def __ge__(self, student):
return self.name > student.name or self.name == student.name
def __str__(self):
"""Returns the string representation of the student."""
return "Name: " + self.name + "\nScores: " + \
" ".join(map(str, self.scores))
def main():
"""A simple test."""
print("\nFirst Student: ")
student1 = Student("Ken", 5)
for index in range(1, 6):
student1.setScore(index, 100)
print(student1)
print("\nSecond Student:")
student2 = Student("Ken", 5)
print(student2)
print("\nThird Student:")
student3 = Student("Matthew", 5)
print(student3)
print("\nRunning a check to see if student1 " + \
"and student 2 are equal: ")
print(student1.__eq__(student2))
print("\nRunning a check to see if student1 " + \
"and student 3 are equal: ")
print(student1.__eq__(student3))
print("\nRunning a check to see if student1 " + \
"is greater than or equal to student3: ")
print(student1.__ge__(student3))
print("\nRunning a check to see if student1 " + \
"is less than student3: ")
print(student1.__lt__(student3))
print()
studentObjList = []
for counter in range(8):
students = Student(str(counter + 1), 5)
studentObjList.append(students)
random.shuffle(studentObjList)
studentObjList.sort()
for studentObj in studentObjList:
print(studentObj)
if __name__ == "__main__":
main()
|
caaceae86ca5f9ac137756c98fccecba86b05c88 | mverini94/PythonProjects | /__repr__example.py | 540 | 4.34375 | 4 |
import datetime
class Car:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
def __repr__(self):
return '__repr__ for Car'
def __str__(self):
return '__str__ for Car'
myCar = Car('red', 37281)
print(myCar)
'{}'.format(myCar)
print(str([myCar]))
print(repr(myCar))
today = datetime.date.today()
print()
'''str is used for clear representation for someone to read'''
print(str(today))
print()
'''repr is used for debugging for developers'''
print(repr(today))
|
2e0c3573ed6698fa45e56983fb5940dc57daeb94 | odai1990/madlib-cli | /madlib_cli/madlib.py | 2,673 | 4.3125 | 4 | import re
def print_wecome_mesage():
"""
Print wilcome and explane the game and how to play it and waht the result
Arguments:
No Arguments
Returns:
No return just printing
"""
print('\n\n"Welcome To The Game" \n\n In this game you will been asked for enter several adjectives,nouns,numbers and names and collect these and put them in a funny paragraph.\n\n Be Ready ')
def read_template(file_name):
"""
Reading file and return it to other function
Arguments:
n:string --- ptha file
Returns:
String of all countent of ifle
"""
try:
with open(file_name) as file:
content_text=file.read()
except Exception:
raise FileNotFoundError("missing.txt")
return content_text
def parse_template(content_text):
"""
Saprate text form each location will replace it inputs user
Arguments:
content_text:string --- test
Returns:
list contane stripted text and what we stripted in tuple
"""
all_changes=re.findall('{(.+?)}',content_text)
all_text_stripted=re.sub("{(.+?)}", "{}",content_text)
return all_text_stripted,tuple(all_changes)
def read_from_user(input_user):
"""
Reaing inputs from user
Arguments:
input_user:string --- to let users knows waht he should insert
Returns:
string of waht user input
"""
return input(f'> Please Enter {input_user}: ')
def merge(*args):
"""
put every thing toguther what user input and stripted text
Arguments:
args:list --- list of wat user input and stripted text
Returns:
return text merged with user inputs
"""
return args[0].format(*args[1])
def save(final_content):
"""
save the file to specifec location with final content
Arguments:
path:string --- the path where you whant to add
final_content:string --- final text
Returns:
none/ just print result
"""
with open('assets/result.txt','w') as file:
file.write(final_content)
print(final_content)
def start_game():
"""
Strating the game and mangae the order of calling functions
Arguments:
none
Returns:
none
"""
print_wecome_mesage()
content_of_file=parse_template(read_template('assets/sample.txt'))
save(merge(content_of_file[0],map(read_from_user,content_of_file[1])))
def test_prompt(capsys, monkeypatch):
monkeypatch.setattr('path.to.yourmodule.input', lambda: 'no')
val = start_game()
assert not val
if __name__ == '__main__':
start_game()
|
530cb062f378fbb67b42eb07ac0f7c8e93e69399 | vasyllyashkevych/computer_vision_practics | /Project_25.py | 998 | 3.609375 | 4 | from PIL import Image
import numpy as np
class ImageFlipping:
"""
Image flipping class.
@param isHorizontally:
Allow flipping horizontally.
@param isVertically:
Allow flipping vertically.
"""
isHorizontally: bool
isVertically: bool
def __init__(self, vertically: bool, horizontally: bool):
self.isVertically = vertically
self.isHorizontally = horizontally
def flip(self, image: Image) -> list:
"""
Flip the given image according to the defined parameters.
@param image: The image in Pillow format.
:return:
A list of the flipped images in numpy format.
"""
list_of_flipped = []
if self.isVertically:
list_of_flipped.append(image.transpose(Image.FLIP_TOP_BOTTOM))
if self.isHorizontally:
list_of_flipped.append(image.transpose(Image.FLIP_LEFT_RIGHT))
return list_of_flipped
|
0dbfe08ed9fd0f87544d12239ca9505083c85986 | mpsacademico/pythonizacao | /parte1/m004_lacos.py | 1,641 | 4.15625 | 4 | # codig=UTF-8
print("FOR") # repete de forma estática ou dinâmica
animais = ['Cachorro', 'Gato', 'Papagaio'] # o for pode iterar sobre uma coleção (com interador) de forma sequencial
for animal in animais: # a referência animal é atualizada a cada iteração
print(animal)
else: # executado ao final do laço (exceto com break)
print("A lista de animais terminou no ELSE")
# contando pares: passando para a próxima iteração em caso de ímpar
for numero in range(0, 11, 1):
if numero % 2 != 0:
#print(numero, "é ímpar")
continue # passa para a próxima iteração
print(numero)
else:
print("A contagem de pares terminou no ELSE")
'''
range(m, n, p) = retorna uma lista de inteiros
- começa em m
- menores que n
- passos de comprimento p
'''
# saldo negativo: parando o laço em caso de valor negativo
saldo = 100
for saque in range(1, 101, 1):
resto = saldo - saque
if resto < 0:
break # interrompe o laço, o ELSE não é executado
saldo = resto
print("Saque:", saque, "| Saldo", saldo)
else:
print("ELSE não é executado, pois o laço sofreu um break")
# --------------------------------------------------------------------
print("WHILE") # repete enquanto a codição for verdadeira
idade = 0
while idade < 18:
escopo = "escopo" # variável definida dentro do while
idade += 1 # incrementar unitariamente assim
if idade == 4:
print(idade, "anos: tomar vacina")
continue # pula o resto e vai para próxima iteração
if idade == 15:
print("Ops! :( ")
break # interrompe o laço completamente!!!
print(idade)
else:
print("ELSE: Você já é maior de idade | ESCOPOS:", idade, escopo) |
3c1cb160109928256565bf8da415a600d56c41f1 | ghostlypi/thing | /CeasarCypher.py | 540 | 3.9375 | 4 | def encrypt(user_input):
myname = user_input
bigstring = ""
for x in range (len(myname)):
bigstring = bigstring + str(ord(myname[x])+3).zfill(3)
x = 0
encrypted = ""
while x < len(bigstring):
charnumber = bigstring[x:x+3]
x = x + 3
charnumber = int(charnumber)
encrypted = encrypted + chr(charnumber)
return encrypted
def decrypt(ui):
x = 0
uo = ""
while x < len(ui):
char = chr(ord(ui[x])-3)
uo = uo + char
x += 1
return(uo)
|
c55551fc0fb4c59bfed84131f404f9b462487691 | PhenixI/programing-foundation-with-python | /useclasses/drawflower.py | 707 | 4.03125 | 4 | import turtle
def draw_rhombus(some_turtle,length,angel):
for i in range(1,3):
some_turtle.forward(length)
some_turtle.left(180-angel)
some_turtle.forward(length)
some_turtle.left(angel)
def draw_flower():
window = turtle.Screen()
window.bgcolor('white')
angie = turtle.Turtle()
angie.shape('arrow')
angie.color('yellow')
angie.speed(10)
for i in range(1,73):
draw_rhombus(angie,100,140)
angie.right(5)
angie.right(90)
angie.forward(300)
# angie.right(150)
# draw_rhombus(angie,150,140)
# angie.right(60)
# draw_rhombus(angie,150,140)
angie.hideturtle()
window.exitonclick()
draw_flower()
|
52830b84ae5750d5f1b39142770c8efaba5e8f41 | fastestmk/python_basics | /list_comprehension.py | 2,374 | 3.625 | 4 | # multiple input using list comprehension
# a, b, c = [int(i) for i in input().split()]
# print(a, b, c)
# List as input using list comprehension
# my_list = [int(i) for i in input().split()]
# print(my_list)
# for x in my_list:
# print(x, end=" ")
# 4*4 Matrix as input
# matrix = [[int(j) for j in input().split()] for i in range(4)]
# seq = [2, 3, 5, 1, 6, 7, 8]
# squares_of_even = [i**2 for i in seq if i%2==0]
# print(squares_of_even)
# charlist = ['A', 'B', 'C']
# ans = [x.lower() for x in charlist]
# print(ans)
# s = 'aaa bbb ccc ddd'
# print(''.join(s.split()))
# s = 'aaa bbb ccc ddd'
# s1 = str(''.join([i for i in s if i != ' ']))
# s2 = [i for i in s if i != ' ']
# print(s1)
# print(s2)
# li = [1, 2, 4, 0, 3]
# print_dict = {i:i*i for i in li}
# print(print_dict)
# print_list = [[i,i*i] for i in li]
# print(print_list)
word = 'CatBatSatFatOr'
print([word[i:i+3] for i in range(len(word))])
print([word[i:i+3] for i in range(0, len(word), 3)])
# towns = [{'name': 'Manchester', 'population': 58241},
# {'name': 'Coventry', 'population': 12435},
# {'name': 'South Windsor', 'population': 25709}]
# town_names = []
# for town in towns:
# town_names.append(town.get('name'))
# print(town_names)
# # List comprehensions...
# town_names = [town.get('name') for town in towns]
# print(town_names)
# # Map function...
# town_names = map(lambda town: town.get('name'), towns)
# print(town_names)
# # For loops...
# town_names = []
# town_populations = []
# for town in towns:
# town_names.append(town.get('name'))
# town_populations.append(town.get('population'))
# print(town_names)
# print(town_populations)
# # List comprehensions...
# town_names = [town.get('name') for town in towns]
# town_populations = [town.get('population') for town in towns]
# print(town_names)
# print(town_populations)
# # Zip function...
# town_names, town_populations = zip(*[(town.get('name'), town.get('population')) for town in towns])
# print(town_names)
# print(town_populations)
# # For loops...
# total_population = 0
# for town in towns:
# total_population += town.get('population')
# # Sum function...
# total_population = sum(town.get('population') for town in towns)
# print(total_population)
# import reduce
# Reduce function...
# total_population = reduce(lambda total, town: total + town.get('population'), towns, 0)
|
5cc5a1970d143188e1168d521fac27f4534f3032 | fastestmk/python_basics | /dictionaries.py | 441 | 4.375 | 4 | # students = {"Bob": 12, "Rachel": 15, "Anu": 14}
# print(students["Bob"])
#length of dictionary
# print(len(students))
#updating values
# students["Rachel"] = 13
# print(students)
#deleting values
# del students["Anu"]
# print(students)
my_dict = {'age': 24, 'country':'India', 'pm':'NAMO'}
for key, val in my_dict.items():
print("My {} is {}".format(key, val))
for key in my_dict:
print(key)
for val in my_dict.values():
print(val) |
aedfec35a3c19b30bc0ec285d7a652b4b340da89 | Temesgenswe/holbertonschool-higher_level_programming | /0x0B-python-input_output/13-student.py | 1,302 | 3.953125 | 4 | #!/usr/bin/python3
"""Module creates class Student"""
class Student:
"""Student class with public instance attributes
Instance Attributes:
first_name: first name of student
last_name: last name of student
age: age of student
"""
def __init__(self, first_name, last_name, age):
"""Instantiates public instance attributes"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""Returns dictionary representation of instance
Params:
attrs: attributes to retrieve.
if not a list of strings, retrieve all attributes
"""
if type(attrs) is not list:
return self.__dict__
filtered = {}
for a in attrs:
if type(a) is not str:
return self.__dict__
value = getattr(self, a, None)
if value is None:
continue
filtered[a] = value
return filtered
def reload_from_json(self, json):
"""Replace all attributes of instance with those in json
Params:
json: dictionary with attributes to use
"""
for key, value in json.items():
self.__dict__[key] = value
|
07cd0f2a3208e04dd0c34a501b68de19f692c35a | Temesgenswe/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 364 | 4.3125 | 4 | #!/usr/bin/python3
"""Module defines append_write() function"""
def append_write(filename="", text=""):
"""Appends a string to a text file
Return: the number of characters written
Param:
filename: name of text file
text: string to append
"""
with open(filename, 'a', encoding="UTF8") as f:
return f.write(str(text))
|
86e76c7aa9c052b23b404c05f57420750a5029b7 | Temesgenswe/holbertonschool-higher_level_programming | /0x06-python-classes/103-magic_class.py | 751 | 4.4375 | 4 | #!/usr/bin/python3
import math
class MagicClass:
"""Magic class that does the same as given bytecode (Circle)"""
def __init__(self, radius=0):
"""Initialize radius
Args:
radius: radius of circle
Raises:
TypeError: If radius is not an int nor a float
"""
self.__radius = 0
if type(radius) is not int and type(radius) is not float:
raise TypeError('radius must be a number')
self.__radius = radius
def area(self):
"""Returns the calculated area of circle"""
return self.__radius ** 2 * math.pi
def circumference(self):
"""Returns the calculated circumference of circle"""
return 2 * math.pi * self.__radius
|
d7378fd0f3ba0e609add78cc4e57919029736c9e | craymontnicholls/Booklet-3- | /Save-the-Change/main.py | 370 | 3.765625 | 4 | def SaveTheChange(Amount):
NearestPound = int(Amount) + 1
if int(Amount) != Amount:
return NearestPound - Amount
else:
NearestPound = Amount
Price = 1.20
Savings = SaveTheChange(Price)
print("Debit -purchase: £{:.2f}".format(Price))
print("Debit - Save the change: £{:.2f}".format(Savings))
print("Credit - Save the changes: £{:.2f}".format(Savings))
|
5a42b0695ea0a6d04e00ebce4a443f10dd0a6a61 | SeniorJunior/Tic-Tac-Toe | /Board.py | 1,417 | 3.953125 | 4 | #Tic Tac Toe
class Board:
def __init__(self, square1 =' ', square2=' ', square3=' ', square4=' ', square5=' ', square6=' ', square7=' ', square8=' ', square9=' '):
self.square1 = square1
self.square2 = square2
self.square3 = square3
self.square4 = square4
self.square5 = square5
self.square6 = square6
self.square7 = square7
self.square8 = square8
self.square9 = square9
def grid(self):
message = '\nSQUARES ARE 0-8, TOP LEFT TO BOTTOM RIGHT, TRAVEL HORIZONTALLY\n | | \n ' +self.square1+' | '+self.square2+' | '+self.square3+' \n___|___|___\n | | \n '+self.square4+' | '+self.square5+' | '+self.square6+' \n___|___|___\n | | \n '+self.square7+' | 'self.square8+' | '+self.square9+' \n | | '
print(message)
game= Board()
print(game.grid)
while True:
entry = raw_input('Please enter a number\n')
if entry == '0':
game.square1='X'
elif entry == '1':
game.square2='X'
elif entry == '2':
game.square3='X'
elif entry == '3':
game.square4='X'
elif entry == '4':
game.square5='X'
elif entry == '5':
game.square6='X'
elif entry == '6':
game.square7='X'
elif entry == '7':
game.square8='X'
elif entry == '8':
game.square9='X'
print(game.grid()) |
cac6b62dea819d2135dea643743f4ad8ea617888 | LorenzoChavez/CodingBat-Exercises | /Logic-1/sorta_sum.py | 259 | 3.734375 | 4 | # Given 2 ints, a and b, return their sum.
# However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20.
def sorta_sum(a, b):
sums = a + b
forbidden = 10 <= sums < 20
if forbidden:
return 20
else:
return sums
|
d3e203ffb4eac1ffe1bd1776de5f06220b81b6c1 | LorenzoChavez/CodingBat-Exercises | /Warmup-1/sum_double.py | 231 | 4.15625 | 4 | # Given two int values, return their sum. Unless the two values are the same, then return double their sum.
def sum_double(a, b):
result = 0
if a == b:
result = (a+b) * 2
else:
result = a+b
return result
|
dcdf2af82b901689753f9e158f009d274ce81580 | LorenzoChavez/CodingBat-Exercises | /Logic-2/make_chocolate.py | 490 | 4.03125 | 4 | # We want make a package of goal kilos of chocolate.
# We have small bars (1 kilo each) and big bars (5 kilos each).
# Return the number of small bars to use, assuming we always use big bars before small bars.
# Return -1 if it can't be done.
def make_chocolate(small, big, goal):
big_needed = goal // 5
if big_needed >= big:
small_needed = goal - (5*big)
else:
small_needed = goal - (5*big_needed)
if small < small_needed:
return -1
else:
return small_needed
|
9ddb20de902048ec957738f121f50212d3f2bd32 | LorenzoChavez/CodingBat-Exercises | /Warmup-1/near_hundred.py | 276 | 3.84375 | 4 | # Given an int n, return True if it is within 10 of 100 or 200.
# Note: abs(num) computes the absolute value of a number.
def near_hundred(n):
result = 0
if abs(100 - n) <= 10 or abs(200 - n) <= 10:
result = True
else:
result = False
return result
|
f884cb7d78aca6efb6943ebc2f7ed4194b0357c3 | Pradas137/Python | /Uf2/modulos/funciones.py | 256 | 3.859375 | 4 | def division_entera():
try:
dividendo = int(input("escrive un dividendo"))
divisor = int(input("escrive un divisor"))
return dividendo/divisor
except ZeroDivisionError:
raise ZeroDivisionError("y no puede ser cero")
|
a39e8f210577397f71242d2b3b841d4fe31e1656 | Pradas137/Python | /Ejercicios_año_pasado/Ejercicios_teoria/Ejercicio4.py | 113 | 3.609375 | 4 | def suma(l):
if (len(l) == 0):
return 0
return l[0] + suma(l[1:])
lista = [1,2,2,2]
print(suma(lista)) |
9fd1b66731c91a03576bb198733f7b6e803210ef | Pradas137/Python | /Ejercicios_año_pasado/Ejercicios_teoria/Ejercicio2.py | 174 | 4.125 | 4 | def producto(num1, num2):
if num2 == 1:
return num1
elif num2 == 0 or num1 == 0:
return 0
else:
return(num1+producto(num1, (num2-1)))
print(producto(0, 3)) |
13e493fdf614c4d1f92f8db7cdddeee4fcc79b32 | Pradas137/Python | /Ejercicios_año_pasado/Ejercicios_teoria/Ejercicio3.py | 353 | 3.921875 | 4 | def fibonacci(n):
if n>2:
return fibonacci(n-2)+fibonacci(n-1)
else:
return 1
print(fibonacci(12))
def fibonacci1(n):
if n>=10:
b=0
while (n>0):
b=b+n%10
n=n//10
return fibonacci1(b)
else:
return n
print(fibonacci1(1523)) |
7ce2d175697104c3df72fd437f9fe01fc0ed5053 | alxanderapollo/HackerRank | /WarmUp/salesByMatchHR.py | 1,435 | 4.3125 | 4 | # There is a large pile of socks that must be paired by color. Given an array of integers
# representing the color of each sock, determine how many pairs of socks with matching colors there are.
# Example
# There is one pair of color and one of color . There are three odd socks left, one of each color.
# The number of pairs is .
# Function Description
# Complete the sockMerchant function in the editor below.
# sockMerchant has the following parameter(s):
# int n: the number of socks in the pile
# int ar[n]: the colors of each sock
# Returns
# int: the number of pairs
# Input Format
# The first line contains an integer , the number of socks represented in .
# The second line contains space-separated integers, , the colors of the socks in the pile.
def sockMerchant(n, ar):
mySet = set() #hold all the values will see
count = 0
#everytime we a see a number we first check if it is already in the set
#if it is delete the number
for i in range(n):
if ar[i] in mySet:
mySet.remove(ar[i])
count+=1
else:
mySet.add(ar[i])
return count
#add one to the count
#otherwise if we've never seen the number before add it to the set and continue
#once we are done with the array
#return the count
n = 9
ar = [10,20 ,20, 10, 10, 30, 50, 10, 20]
print(sockMerchant(n, ar))
|
c9b5f7671742610dc86e6812456e9f645d4188e5 | hliaskost2001/hliaskost | /ask8.py | 493 | 3.5 | 4 | import urllib.request
import json
url="https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,LTC&tsyms=EUR&e=CCCAGG"
r=urllib.request.urlopen(url)
html=r.read()
html=html.decode()
d=json.loads(html)
file = input("File name: ")
f = open(file, 'r')
f = f.read()
f = json.loads(f)
thisdict = {
"BTC": "54267.673556",
"ETH": "10797,677999999998",
"LTC":"182.01"
}
print('Your portofolio is:')
print(f)
print('Which in Euros is: ')
print(thisdict)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.