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 |
|---|---|---|---|---|---|---|
472abe0dbb38fbe93f7c86f09e6a9605d2276084 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_persona.py | 592 | 3.90625 | 4 | # creamos la clase
class Persona:
# creamos las variables de la clase
nombre = "Juan"
Variable_local = 3
# declaramos el metodo __init__
def __init__(self):
self.nombre=input("Ingrese el nombre: ")
self.edad=int(input("Ingrese la edad: "))
# creamos la primera funcion
# para inicializar el atributo nombre
def inicializar(self, nom):
self.nombre = nom
# creamos el segundo método
# para mostrar el nombre
def mostrar(self):
print("Nombre: " , self.nombre)
print("Edad: ",self.edad)
|
ad24b511b70d2bb85230928b52d8c33117698ba8 | hector81/Aprendiendo_Python | /Prueba/encontrar.py | 192 | 3.859375 | 4 | cadena = "estamos en La Rioja por desgracia"
if cadena.find("La Rioja") >= 0:
print ("Se ha encontrado la rioja en el e-mail")
else:
print ("No se ha encontrado la rioja en el e-mail")
|
aa45f4f212d5892fa5f133b510d68416a5717fd4 | hector81/Aprendiendo_Python | /Listas/MaquinasExpendedoras_simple.py | 4,627 | 3.578125 | 4 | # solo devuelve monedas
# http://progra.usm.cl/apunte/ejercicios/1/maquina-alimentos.html
# funciones
def sumarCantidadDisponible(arrayCantidadMonedasBilletes):
cantidadTotal = 0.0
for i in range(len(arrayCantidadMonedasBilletes)):
cantidadTotal = cantidadTotal + arrayCantidadMonedasBilletes[i][0]*arrayCantidadMonedasBilletes[i][1]
return cantidadTotal
def desglosarCantidad(cantidad,arrayCantidadMonedasBilletes):
monBil = ''
restoCantidad = 0.0
cantidadUnidad = 0
for i in range(len(arrayCantidadMonedasBilletes)):
if cantidad == arrayCantidadMonedasBilletes[i][0]:
print('HAY ' + '1' + ' ' + monBil + ' DE ' + str(arrayCantidadMonedasBilletes[i][0]) + ' EUROS')
break
else:
# sacamos el resto
restoCantidad = cantidad%arrayCantidadMonedasBilletes[i][0]
# restamos el resto a la cantidad
cantidad = cantidad - restoCantidad
# y la dividimos por la posicion para sacar la cantidad exacta de billetes o monedas
cantidadUnidad = int(cantidad/arrayCantidadMonedasBilletes[i][0])
# estos es para billetes o monedas
if arrayCantidadMonedasBilletes[i][0] < 3:
if cantidadUnidad > 1:
monBil = 'MONEDAS'
else:
monBil = 'MONEDA'
else:
if cantidadUnidad > 1:
monBil = 'BILLETES'
else:
monBil = 'BILLETE'
print('HAY ' + str(cantidadUnidad) + ' ' + monBil + ' DE ' + str(arrayCantidadMonedasBilletes[i][0]) + ' EUROS')
# ponemos los valores para siguiente vuelta
cantidad = restoCantidad
cantidadUnidad = 0
# fin funcion
def pagasMenosMas(pago,precioTabacoElegido):
boolComp = False
if pago >= precioTabacoElegido:
boolComp = True
return boolComp
def comprobarTabacoExisteNumero(arrayTabacosPrecios, numero):
numero = numero - 1
boolCom = False
for i in range(len(arrayTabacosPrecios)):
if i == numero:
boolCom = True
return boolCom
def introducirNumeroInt():
while True:
try:
x = int(input("Por favor ingrese un número: "))
if x > 0:
return x
break
else:
print("Por favor. Número mayor que 0")
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
def introducirNumeroFloat():
while True:
try:
x = float(input("Por favor ingrese un número: "))
if x > 0:
return x
break
else:
print("Por favor. Número mayor que 0")
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
# variables
arrayTabacosPrecios = [
['Malboro',4.98],
['West',4.00],
['LM',4.55],
['Chesterfield',4.65],
['Lucky',4.40],
]
arrayCantidadMonedasBilletes = [
[500.00,3],
[200.00,2],
[100.00,0],
[50.00,0],
[20.00,3],
[10.00,4],
[5.00,55],
[2.00,6],
[1.00,4],
[0.5,7],
[0.2,7],
[0.1,11],
[0.05,14],
[0.02,15],
[0.01,14]
]
pago = 0.0
existeTabaco = False
pagoCorrecto = False
precioTabacoElegido = 0.0
cambios = 0.0
# operaciones
print('Elige el tabaco deseado')
while existeTabaco == False:
for i in range(len(arrayTabacosPrecios)):
print(str(i+1) + " = " + arrayTabacosPrecios[i][0] + ' .Precio = ' + str(arrayTabacosPrecios[i][1]))
numero = introducirNumeroInt()
existeTabaco = comprobarTabacoExisteNumero(arrayTabacosPrecios, numero)
if existeTabaco == False:
print('Debes elegir un número de la lista')
if existeTabaco == True:
print("Has elegido " + arrayTabacosPrecios[i][0] + ' .Precio = ' + str(arrayTabacosPrecios[i][1]) + '€')
precioTabacoElegido = arrayTabacosPrecios[i][1]
print('¿Cuanto vas a pagar?')
while pagoCorrecto == False:
pago = introducirNumeroFloat()
pagoCorrecto = pagasMenosMas(pago,precioTabacoElegido)
if pagoCorrecto == False:
print('Debes pagar por lo menos el precio justo')
else:
cambios = pago - precioTabacoElegido
cambiosS = "{0:.2f}".format(cambios)
print('Tus cambios son ' + str(cambiosS) + '€ y se te devuelven en =')
desglosarCantidad(cambios,arrayCantidadMonedasBilletes)
|
dd203682bf782143bc7db016931c8b016fe615b4 | hector81/Aprendiendo_Python | /CursoPython/Unidad6/Ejemplos/ejemplo1_Else.py | 1,039 | 3.984375 | 4 | n = int(input('Ingresa un número y te digo si es primo. '))
for x in range(2,n):
if n % x == 0:
print(n, 'es igual a', x, '*', n/x)
break
else:
print(n, 'es un número primo')
'''
Condicional con if para saber si un número no es primo.
En caso de que la condición sea verdadera (no primo), se ejecuta un print avisando del hecho y sale del
bucle con la sentencia break.
En caso contrario, es decir, que la condición no sea verdad se ejecutará el contenido identado dentro de else.
La instrucción "else" después de un ciclo solo tiene sentido cuando se usa en combinación con break.
Si durante la ejecución del bucle, el intérprete de Python encuentra un break, inmediatamente detiene
la ejecución del bucle y sale de él. En este caso, la rama else: no se ejecuta.
Básicamente, la sentencia else está conectada al bucle y cuando el bucle no tiene interrupción
(lo que significa que la sentencia break no es usada) lo que está bajo la sentencia else se ejecuta.
''' |
edd9c5c65bfbaac057661f230b380406d567ec93 | hector81/Aprendiendo_Python | /CursoPython/Unidad2/Ejemplos/operadores_comparacion.py | 618 | 3.734375 | 4 | resultado1 = 5 > 3
print("5 > 3 = " , resultado1)
resultado2 = 3 < 7
print("3 < 7 = " , resultado2)
resultado3 = 19 < 9
print("19 < 9 = " , resultado3)
resultado4 = 1 != 0
print("1 != 0 = " , resultado4)
resultado5 = 0 != 0
print("0 != 0 = " , resultado5)
resultado6 = False or (4 == 1 + 5) == False
print("False or (4 == 1 + 5) == False = " , resultado6)
resultado7 = 5<3
print("5<3 = " , resultado7)
resultado8 = 10>9
print("10>9 = " , resultado8)
resultado9 = 5>=5
print("5>=5 = " , resultado9)
resultado10 = 5>5
print("5>5 = " , resultado10)
resultado11 = 5>=2
print("5>=2 = " , resultado11)
|
4e3d2a56b9c1b632d79ae1147e6090c4f1fe8f06 | hector81/Aprendiendo_Python | /String_Cadenas/Palabra_Corta_Larga.py | 882 | 3.953125 | 4 | def introducirFrase():
while True:
try:
frase = input("Por favor ingrese una frase: ")
if frase != '':
print("La frase es " + frase)
return frase
break
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
frase = introducirFrase()
palArray = []
palArray = frase.split(" ")
contador = 0
palabraMasLarga = ''
palabraMasCorta = ''
for i in range(len(palArray)):
if len(palArray[i]) > contador:
palabraMasLarga = palArray[i]
contador = len(palArray[i])
print('La palabra más larga es ' + palabraMasLarga)
for i in range(len(palArray)):
if len(palArray[i]) < contador:
palabraMasCorta = palArray[i]
contador = len(palArray[i])
print('La palabra más corta es ' + palabraMasCorta)
|
62c48ed596bb30a48b40b4b7a1f5a31d2a90d805 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_metodo_str.py | 417 | 4.0625 | 4 | class punto():
"""Clase que va representar un punto en un plano
Por lo que tendrá una coordenada cartesiana(x,y)
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
""" Muestra un par de variables como una tupla, el punto cartesiano"""
return "(" + str(self.x) + ", " + str(self.y) + ")"
p = punto(7,15)
str(p)
print(p)
print(str(p)) |
6edc9a6cd63bbff4b6929879633cb39d5e4f8fe5 | hector81/Aprendiendo_Python | /CursoPython/Unidad3/Ejemplos/numero_int_float.py | 218 | 4.09375 | 4 | #Definimos dos variables llamadas numero1 y
# numero2, y asociaremos un número a cada una
numero1 = int(2)
numero2 =float(2.5)
print("numero1 = int(2) ==> " , numero1)
print("numero2 = float(2.5) ==> " , numero2) |
54fb0ee5160b4f686f630cebf3f331a99119071b | hector81/Aprendiendo_Python | /L14_Proyecto/Ejercicio1_1.py | 2,391 | 3.984375 | 4 | '''
EJERCICIO 1. Cargar los datos con la función pandas.read_json.
¿Qué tipo tiene cada columna?
¿Qué pasa con los datos numéricos?
Una pista: si necesitamos realizar manipulaciones elemento a elemento
(por ejemplo, eliminar un caracter extraño), podemos aplicar el método
apply junto con una función lambda. Si, en una cadena, quisiésemos
reemplazar ',' por '.' y convertir esos valores a punto flotante
podríamos hacer la siguiente llamada:
# df['MI_COLUMNA'].apply(lambda x: float(x.replace(",", ".")))
hay ERRORES en prec == ip 0 0.0 velmedia
'''
import pandas as pd
from pathlib import Path
# FUNCIONES
def cargarDatos_Archivo_Json(archivo):
fichero = Path(archivo)
# creamos el dataframe
df = pd.read_json(fichero)
return df
def modificarElementosFloatDataframe(df):
lista_columnas_float = ['tmed', 'prec', 'tmin', 'tmax', 'racha', 'sol', 'presMax', 'presMin']
for columna in lista_columnas_float:
df[columna] = df[columna].apply(lambda x: float(x.replace(",", ".")))
return df
def modificarOtrosElementos(df):
df['nombre'] = df['nombre'].apply(lambda x: str(x.replace("я", "ÑO")))
return df
# VARIABLES
archivo = "ficheros_proyecto/Agoncillo_2019.json"
# OPERACIONES
df = cargarDatos_Archivo_Json(archivo)
print(f"¿Qué tipo tiene cada columna?")
print(df.dtypes)
print()
print(f"Información de las columnas")
print(df.info())
print()
print(f"Cabecera")
print(df.head())
print()
print(f"Todos los datos con TAIL")
print(df.tail(364))
print()
print(f"Sacamos los datos con sus media, sumas, etc.")
print(df.describe())
print()
print(f"Si quisieramos ver los datos de temperatura media")
print(df['tmed'])
print()
df = modificarElementosFloatDataframe(df)
df = modificarOtrosElementos(df)
print(f"¿Qué pasa con los datos numéricos?")
print(f"Que los FLOAT al tener la separación con una coma (,) en vez de punto, los interpreta como un object")
print(f"Cambiamos las comas por punto con la funcion : df['MI_COLUMNA'].apply(lambda x: float(x.replace(',', '.')))")
print(f"Aunque solo cambiamos estos datos : tmed,prec,tmin,tmax,velmedia,racha,sol,presMax,presMin,horaPresMin")
print(f"Volvemos a ver los datos para ver que han cambiado en los float las comas por los puntos")
print(f"También hemos cambiado LOGROя por LOGROÑO")
print(df)
|
59fd1f3fdf086d9bf627467a89a6d86bb9b14e12 | hector81/Aprendiendo_Python | /CursoPython/Unidad10/Ejemplos/ejemplo_archivos.py | 2,058 | 3.5 | 4 | # EJEMPLO: Distintas pruebas con los métodos de archivos
archivo = open("Unidad10\\Ejemplos\\archivo.txt","bw")
archivo.write(b'Hola Mundo')
# 10
# Si intentas leer el archivo, como lo has abierto en modo escritura te devolverá un error.
# archivo.read()
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# io.UnsupportedOperation: read
# Es posible recorrer el archivo, es decir: pasar por sus caracteres.
archivo.seekable()
# True
# Sabe dónde está el puntero.
archivo.tell()
# 10
# Reubicar el puntero dentro del archivo.
archivo.seek(3)
# 3
# Vuelvo a comprobar donde está el puntero.
archivo.tell()
# 3
# Abro de nuevo el archivo en modo lectura.
archivo = open("Unidad10\\Ejemplos\\archivo.txt","br")
# Leer desde donde se encuentre el puntero hasta 9 caracteres.
archivo.read(9)
# b'Hola Mund'
# Leer desde donde se encuentre el puntero hasta el final.
archivo.read()
# b'o'
# Recoloco el puntero en la posición 0.
archivo.seek(0)
# 0
# Leer desde donde se encuentre el puntero hasta el final.
archivo.read()
# b'Hola Mundo'
# Vuelvo a abrir el archivo en modo escritura tipo texto para pode usar writelines y readlines
archivo = open("Unidad10\\Ejemplos\\archivo.txt","w")
# Reescribo la primera linea
archivo.write("Hola Mundo")
# 10
# Añado otras dos lineas de texto a mi archivo
archivo.write("\n Queremos un mundo")
# 19
archivo.write("\n Donde quepan muchos mundos")
# 28
# Utilizo la función writelines para añadir 2 lineas más al archivo
archivo.writelines(['\n cuarta linea','\n quinta linea'])
# Reabro en forma lectura
archivo = open("Unidad10\\Ejemplos\\archivo.txt","r")
# Realiza diferentes pruebas con el método readlines
archivo.readline()
# 'Hola Mundo\n'
archivo.readline()
# ' Queremos un mundo\n'
archivo.readline()
# ' Donde quepan muchos mundos'
archivo.seek(0)
# 0
a = archivo.readlines()
# a
print(a)
# ['Hola Mundo\n', ' Queremos un mundo\n', ' Donde quepan muchos mundos\n', 'cuarta linea', 'quinta linea']
# anterior
# 2
# 3
|
d17d2dc1ae1c064a10642e436debd175944a013c | hector81/Aprendiendo_Python | /Listas/MaquinasExpendedoras_complicado.py | 15,186 | 4.0625 | 4 | '''
FUNCIONES
'''
def comprobarTabacoExisteNumero(arrayTabacosPrecios_Cantidad, numero):
numero = numero - 1
boolCom = False
for i in range(len(arrayTabacosPrecios_Cantidad)):
if i == numero:
boolCom = True
return boolCom
def comprobarTabacoCantidad(arrayTabacosPrecios_Cantidad, numero):
numero = numero - 1
boolCom = False
for i in range(len(arrayTabacosPrecios_Cantidad)):
if i == numero:
tabacoElegido = arrayTabacosPrecios_Cantidad[i]
# esto seria la cantidad de paquetes del elegido
if tabacoElegido[2] == 0:
boolCom = True
print(f"Este tabaco está agotado. Hay que reponer")
return boolCom
# fin funcion
def introducirNumeroInt():
while True:
try:
x = int(input(f"Por favor ingrese un número: "))
if x > 0:
return x
break
else:
print(f"Por favor. Número mayor que 0")
except ValueError:
print(f"Oops! No era válido. Intente nuevamente...")
# fin funcion
def introducir_monedas_billetesInt():
while True:
try:
x = int(input(f"Por favor ingrese un número: "))
if x > -1:
return x
break
else:
print(f"Por favor. Número mayor que -1")
except ValueError:
print(f"Oops! No era válido. Intente nuevamente...")
# fin funcion
def introducirNumeroFloat():
while True:
try:
x = float(input(f"Por favor ingrese un número: "))
if x > 0:
return x
break
else:
print(f"Por favor. Número mayor que 0")
except ValueError:
print(f"Oops! No era válido. Intente nuevamente...")
# fin funcion
def mostrarTabacosDisponibles(arrayTabacosPrecios_Cantidad):
print(f"************************************")
print(f"Elige el tabaco deseado")
for i in range(len(arrayTabacosPrecios_Cantidad)):
print(f"{(i+1)} = {arrayTabacosPrecios_Cantidad[i][0]} .Precio = {arrayTabacosPrecios_Cantidad[i][1]}")
print(f"************************************")
# fin funcion
def hayPaquetes_en_la_maquina(arrayTabacosPrecios_Cantidad):
hayPaquetes = False
for elemento in arrayTabacosPrecios_Cantidad:
if elemento[2] != 0:
hayPaquetes = True
return hayPaquetes
# fin funcion
def devolver_precio_tabaco(arrayTabacosPrecios_Cantidad,numero):
precio = 0.0
for i in range(len(arrayTabacosPrecios_Cantidad)):
if (numero-1) == i:
tabacoElegido = arrayTabacosPrecios_Cantidad[i]
precio = tabacoElegido[1]
return precio
# fin funcion
def devolver_nombre_tabaco(arrayTabacosPrecios_Cantidad,numero):
nombre = ""
for i in range(len(arrayTabacosPrecios_Cantidad)):
if (numero-1) == i:
tabacoElegido = arrayTabacosPrecios_Cantidad[i]
nombre = tabacoElegido[0]
return nombre
# fin funcion
def ingresar_dinero_pago():
pago = []
print(f"Cuantos billetes de 500 euros quieres ingresar?")
billetes500 = introducir_monedas_billetesInt()
pago.append([500,billetes500])
print(f"Cuantos billetes de 200 euros quieres ingresar?")
billetes200 = introducir_monedas_billetesInt()
pago.append([200,billetes200])
print(f"Cuantos billetes de 100 euros quieres ingresar?")
billetes100 = introducir_monedas_billetesInt()
pago.append([100,billetes100])
print(f"Cuantos billetes de 50 euros quieres ingresar?")
billetes50 = introducir_monedas_billetesInt()
pago.append([50,billetes50])
print(f"Cuantos billetes de 20 euros quieres ingresar?")
billetes20 = introducir_monedas_billetesInt()
pago.append([20,billetes20])
print(f"Cuantos billetes de 10 euros quieres ingresar?")
billetes10 = introducir_monedas_billetesInt()
pago.append([10,billetes10])
print(f"Cuantos billetes de 5 euros quieres ingresar?")
billetes5 = introducir_monedas_billetesInt()
pago.append([5,billetes5])
print(f"Cuantos monedas de 2 euros quieres ingresar?")
monedas2 = introducir_monedas_billetesInt()
pago.append([2,monedas2])
print(f"Cuantos monedas de 1 euro quieres ingresar?")
monedas1 = introducir_monedas_billetesInt()
pago.append([1,monedas1])
print(f"Cuantos monedas de 0.50 centimos quieres ingresar?")
monedas0_50 = introducir_monedas_billetesInt()
pago.append([0.50,monedas0_50])
print(f"Cuantos monedas de 0.20 centimos quieres ingresar?")
monedas0_20 = introducir_monedas_billetesInt()
pago.append([0.2,monedas0_20])
print(f"Cuantos monedas de 0.10 centimos quieres ingresar?")
monedas0_10 = introducir_monedas_billetesInt()
pago.append([0.1,monedas0_10])
print(f"Cuantos monedas de 0.05 centimos quieres ingresar?")
monedas0_05 = introducir_monedas_billetesInt()
pago.append([0.05,monedas0_05])
print(f"Cuantos monedas de 0.02 centimos quieres ingresar?")
monedas0_02 = introducir_monedas_billetesInt()
pago.append([0.02,monedas0_02])
print(f"Cuantos monedas de 0.01 centimos quieres ingresar?")
monedas0_01 = introducir_monedas_billetesInt()
pago.append([0.01,monedas0_01])
escribir_cantidad_pago(pago)
return pago
# fin funcion
def devolver_cantidad_total_pago(pago):
total_pago = 0.0
for elemento in pago:
total_pago += (elemento[0]*elemento[1])
return total_pago
# fin funcion
def escribir_cantidad_pago(pago):
pagoStr = f"Has pagado ="
for elemento in pago:
moneda = elemento[0]
cantidad = elemento[1]
if elemento[0] < 5: # monedas
if elemento[0] < 1: # euros cantidades en centimos
if elemento[1] < 2:
pagoStr += f" {elemento[1]} moneda de {int(elemento[0]*100)} centimos."
else:
pagoStr += f" {elemento[1]} monedas de {int(elemento[0]*100)} centimos."
else: # euros cantidades enteras
if elemento[1] < 2:
pagoStr += f" {elemento[1]} moneda de {elemento[0]} euros."
else:
pagoStr += f" {elemento[1]} monedas de {elemento[0]} euros."
else: # billetes
if elemento[1] < 2:
pagoStr += f" {elemento[1]} billete de {elemento[0]} euros."
else:
pagoStr += f" {elemento[1]} billetes de {elemento[0]} euros."
total = "{0:.2f}".format(devolver_cantidad_total_pago(pago))
pagoStr += f" En total has pagado = {total} euros."
print(pagoStr)
# fin funcion
def escribir_cantidad_cambios(tusCambios):
pagoStr = f"Se te devuelven ="
for elemento in tusCambios:
moneda = elemento[0]
cantidad = elemento[1]
if elemento[0] < 5: # monedas
if elemento[0] < 1: # euros cantidades en centimos
if elemento[1] < 2:
pagoStr += f" {elemento[1]} moneda de {int(elemento[0]*100)} centimos."
else:
pagoStr += f" {elemento[1]} monedas de {int(elemento[0]*100)} centimos."
else: # euros cantidades enteras
if elemento[1] < 2:
pagoStr += f" {elemento[1]} moneda de {elemento[0]} euros."
else:
pagoStr += f" {elemento[1]} monedas de {elemento[0]} euros."
else: # billetes
if elemento[1] < 2:
pagoStr += f" {elemento[1]} billete de {elemento[0]} euros."
else:
pagoStr += f" {elemento[1]} billetes de {elemento[0]} euros."
print(pagoStr)
# fin funcion
def pagasMenosMas(pago_total,precioTabacoElegido):
boolComp = False
if pago_total >= precioTabacoElegido:
boolComp = True
return boolComp
# fin funcion
def restarUnidadTabaco(numero,arrayTabacosPrecios_Cantidad):
for i in range(len(arrayTabacosPrecios_Cantidad)):
if (numero-1) == i:
arrayTabacosPrecios_Cantidad[i][2] = arrayTabacosPrecios_Cantidad[i][2] - 1
return arrayTabacosPrecios_Cantidad
# fin funcion
def ingresarCantidadPagoMaquina(pago,arrayCantidadMonedasBilletes):
for i in range(len(arrayCantidadMonedasBilletes)):
arrayCantidadMonedasBilletes[i][1] = arrayCantidadMonedasBilletes[i][1] + pago[i][1]
return arrayCantidadMonedasBilletes
# fin funcion
def devolver_cantidad_total_maquina():
cantidad_pago = 0.0
for i in range(len(arrayCantidadMonedasBilletes)):
cantidad_pago += arrayCantidadMonedasBilletes[i][0] * arrayCantidadMonedasBilletes[i][1]
return cantidad_pago
# fin funcion
def devolver_cambios_moneda_numero_posible(cociente, moneda, arrayCantidadMonedasBilletes):
cantidad_posible_devolver = 0
for i in range(len(arrayCantidadMonedasBilletes)):
moneda_maquina = arrayCantidadMonedasBilletes[i][0]
cantidad_moneda_maquina = arrayCantidadMonedasBilletes[i][1]
if moneda_maquina == moneda:
if cociente <= cantidad_moneda_maquina:
cantidad_posible_devolver = cociente
else:
cantidad_posible_devolver = cantidad_moneda_maquina
return cantidad_posible_devolver
# fin funcion
def devolver_lista_con_cambios(pago, precio_producto, cantidad_cambio):
cociente_posible_devolver = 0
listaCambios = []
residuo = 0.0
for i in range(len(pago)):
moneda = round(pago[i][0],2)
cantidad_moneda_en_maquina = round(pago[i][1],0)
if cantidad_cambio >= moneda:
# El dividendo sería cantidad y el divisor sería moneda
# un ejemplo seria que si la cantidad fuera 4.47, y la moneda 2, el cociente seria 2 y el residuo 0.47
cociente = int(cantidad_cambio/moneda) # la cantidad de monedas que se obtendrian
residuo = round(cantidad_cambio%moneda, 2) # el resto que quedaria
#una vez calculado el cociente, calculamos si la maquina tiene las suficientes monedas para dar ese cambio
cociente_posible_devolver = devolver_cambios_moneda_numero_posible(cociente, moneda, arrayCantidadMonedasBilletes)
#le devolvemos las monedas posibles
#guardamos en lista de cambios los monedas
listaCambios.append([moneda,cociente_posible_devolver])
# si es posible devolver el cociente, entonces para la siguiente vuelta .....
cantidad_cambio = round(cantidad_cambio - (cociente_posible_devolver*moneda),2)
if ((cantidad_cambio)) == 0:
return listaCambios
else:
return []
# fin funcion
def restar_cambios_cantidad_maquina(tusCambios,arrayCantidadMonedasBilletes):
for i in range(len(arrayCantidadMonedasBilletes)):
moneda_maquina = arrayCantidadMonedasBilletes[i][0]
cantidad_maquina = arrayCantidadMonedasBilletes[i][1]
for y in range(len(tusCambios)):
moneda_cambio = tusCambios[y][0]
cantidad_cambio = tusCambios[y][1]
if moneda_cambio == moneda_maquina:
arrayCantidadMonedasBilletes[i][1] = arrayCantidadMonedasBilletes[i][1] - cantidad_cambio
return arrayCantidadMonedasBilletes
# fin funcion
'''
VARIABLES
'''
# [nombre tabaco, precio float, cantidad o stock en máquina]
arrayTabacosPrecios_Cantidad = [
['Malboro',4.98,105],
['West',4.00,10],
['LM',4.55,0],
['Chesterfield',4.65,10],
['Lucky',4.40,10],
['Ducados',500.00,10],
]
# [unidades billete o moneda,cantidad o stock en máquina]
arrayCantidadMonedasBilletes = [
[500,0],
[200,0],
[100,0],
[50,0],
[20,0],
[10,0],
[5,0],
[2,4],
[1,12],
[0.5,1],
[0.2,111],
[0.1,111],
[0.05,111],
[0.02,1],
[0.01,1111]
]
#esta variable es para comprobar que existe tabaco en la máquina
maquina_queda_tabaco = False
precioTabacoElegido = 0.0
cambios = 0.0
'''
OPERACIONES
'''
# esto comprueba que hay paquetes o productos en la máquina
maquina_queda_tabaco = hayPaquetes_en_la_maquina(arrayTabacosPrecios_Cantidad)
if maquina_queda_tabaco == True:
mostrarTabacosDisponibles(arrayTabacosPrecios_Cantidad)
numeroTabaco_elegido = introducirNumeroInt()
# comprobamos que el numero tabaco existe
if comprobarTabacoExisteNumero(arrayTabacosPrecios_Cantidad, numeroTabaco_elegido) == False:
print('Debes elegir un número de la lista')
else:
precio = devolver_precio_tabaco(arrayTabacosPrecios_Cantidad,numeroTabaco_elegido)
nombre = devolver_nombre_tabaco(arrayTabacosPrecios_Cantidad,numeroTabaco_elegido)
print(f"Has elegido {nombre} y su precio es {precio} euros")
# comprobamos que ese paquete en concreto tenga existencias
if comprobarTabacoCantidad(arrayTabacosPrecios_Cantidad, numeroTabaco_elegido) == False:
print(f"Procede al pago")
pago = ingresar_dinero_pago() # devulve una lista o array
total_pago = devolver_cantidad_total_pago(pago)
# comprobamos que la cantidad pueda pagar el tabaco elegido
if pagasMenosMas(total_pago,precio) == True:
# restamos un paquete de tabaco al tabaco elegido
arrayTabacosPrecios_Cantidad = restarUnidadTabaco(numeroTabaco_elegido,arrayTabacosPrecios_Cantidad)
# ingresamos monedas y billetes del pago a la cantidad existente a la máquina
arrayCantidadMonedasBilletes = ingresarCantidadPagoMaquina(pago,arrayCantidadMonedasBilletes)
# esta variable es para los cambios
cantidad_cambio = round(total_pago - precio, 2)
if total_pago == precio:
print(f"\n")
print(f"Has pagado el precio justo. Cambios = 0 euros")
else:
print(f"")
print(f"Has pagado más de lo que vale. Hay que devolverte cambios, que son {cantidad_cambio} euros")
tusCambios = devolver_lista_con_cambios(pago, precio, cantidad_cambio)
if tusCambios == []:
print(f"")
print(f"No hay suficientes cambios en la máquina.")
else:
print(f"")
escribir_cantidad_cambios(tusCambios)
# restamos los cambios a la cantidad que haya en la máquina
arrayCantidadMonedasBilletes = restar_cambios_cantidad_maquina(tusCambios,arrayCantidadMonedasBilletes)
else:
print(f"La cantidad de dinero introducida no es suficiente.")
else:
print(f"No hay paquetes disponibles en la máquina. Hay que recargarla.")
|
60db772fe0b20473827de17fbcd6ceaf75cfccf3 | hector81/Aprendiendo_Python | /Modulos_pickle_json/Ejercicio2_leer_archivos_json_pickle.py | 1,853 | 3.9375 | 4 | '''
EJERCICIOS MÓDULOS pickle Y json
2. Recupere el contenido del fichero 'ejercicios.pic' o 'ejercicios.json'.
Determine el número de líneas que ha programado hasta ahora en el curso.
No cuentan las líneas en blanco ni las líneas que sean comentarios.
'''
import pickle
import json
#FUNCIONES
def recuperarDatos_modulo_JSON(ruta):
with open(ruta, 'r') as archivo_entrada:
objeto = json.load(archivo_entrada)
objeto_en_json = json.dumps(objeto) # Para volcar el dato en una cadena:
objeto_load_json = json.loads(objeto_en_json) # Para recuperar el dato desde la cadena
return objeto_load_json
def numeroLineas_por_FicheroRuta(ruta):
contador = 0
try:
with open(ruta, "r", encoding="utf8") as archivo:
for linea in archivo.readlines():
if not "#" in linea[0] and not "'''" in linea[0:3] and len(linea.strip()) > 0:
contador += 1
except FileNotFoundError:
print("la ruta no es correcta")
return contador
def numeroTotalLineaArchivos(diccionarioJSON):
numeroLineasTotal = 0
numeroLineas = 0
for key in diccionarioJSON:
print(f"Archivo = {key} . Ruta absluta = {diccionarioJSON[key]}")
numeroLineas = numeroLineas_por_FicheroRuta(diccionarioJSON[key])
print(f"El número de lineas de este archivo es {numeroLineas}")
numeroLineasTotal += numeroLineas
numeroLineas = 0
print(f"**************************")
print(f"El número total de lineas de todos los archivos es {numeroLineasTotal}")
# VARIABLES
rutaJSON = "C:\\xampp\\htdocs\\AprenderPython\\Ejercicios\\L10_BibliotecaEstandarPython\\modulos_pickle_json\\ejercicios.json"
diccionarioJSON = recuperarDatos_modulo_JSON(rutaJSON)
numeroTotalLineaArchivos(diccionarioJSON)
|
6b89068c0bd117e7e4799e632cdce9e56c19122e | hector81/Aprendiendo_Python | /String_Cadenas/DevolverMayusculasMinusculas.py | 437 | 3.640625 | 4 | frase = 'Esto es una frase con Mayusculas y minusculas'
contadorMayusculas = 0
contadorMinusculas = 0
for i in range(len(frase)):
if frase[i].islower():
contadorMinusculas = contadorMinusculas + 1
elif frase[i].isupper():
contadorMayusculas = contadorMayusculas + 1
print('La frase : "' + frase + '" contiene ' + str(contadorMinusculas) + ' minusculas y ' + str(contadorMayusculas) + ' mayusculas')
|
670a651707c59584b5d5a13f1650c2d1905b1472 | hector81/Aprendiendo_Python | /CursoPython/Unidad4/Ejercicios/actividad_I_u4.py | 522 | 3.8125 | 4 | '''
Selecciona las tres fechas más recientes de esta lista utilizando la notación de
slicing de lista que hemos ido viendo durante el tema.
'''
dias_eclipse = ['21 de junio de 2001', '4 de diciembre de 2002', '23 de noviembre de 2003',
'29 de marzo de 2006', '1 de agosto de 2008', '22 de julio de 2009', '11 de julio de 2010',
'13 de noviembre de 2012', '20 de marzo de 2015', '9 de marzo de 2016']
# Elementos desde el antepenúltimo hasta el final, o igualemente los 3 últimos
print(dias_eclipse[-3:]) |
109761a1fca526bb59dd1074bf15aacf649d5167 | hector81/Aprendiendo_Python | /CursoPython/Unidad10/Ejemplos/archivo_read.py | 331 | 3.578125 | 4 | # Si el archivo se encuentra en modo de lectura, lo lee y devuelve el contenido del archivo desde la posición en la que se encuentre hasta el final del archivo. Si se introduce un número como argumento,
# lee el número de posiciones indicadas en el argumento.
f = open("Unidad10\\Ejemplos\\archivo.txt", "r")
print(f.read()) |
3cd870efac96ad2866c909ef969caf5acc2830d1 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_metodo_operador_matematico.py | 557 | 4.375 | 4 | class Punto():
"""Clase que va representar un punto en un plano
Por lo que tendrá una coordenada cartesiana(x,y)
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, otro):
""" Devuelve la suma de ambos puntos. """
return Punto(self.x + otro.x, self.y + otro.y)
def __sub__(self, otro):
""" Devuelve la resta de ambos puntos. """
return Punto(self.x - otro.x, self.y - otro.y)
p = Punto(3,4)
q = Punto(2,5)
print(p - q)
print(p + q) |
1ba04402ea117c9bc59eae2e91656535c84a8b57 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_emtodo_property.py | 1,588 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Perros(object): #La clase principal Perros
def __init__(self, nombre, peso): #Define los parámetros
self.__nombre = nombre #Declara los atributos (privados ocultos)
self.__peso = peso
@property
def nombre(self): #El método para obtener el nombre(sería el getter)
"Documentación del método nombre bla bla" # Doc del método
return self.__nombre #Aquí simplemente retorna el atributo privado oculto
#Hasta aquí los métodos para obtener los atributos ocultos o privados getter.
#Ahora utiliza setter y deleter para modificarlos
@nombre.setter #Propiedad SETTER
def nombre(self, nuevo):
print ("Modificando nombre..")
self.__nombre = nuevo
print ("El nombre se ha modificado por")
print (self.__nombre) #Aquí se vuelve a pedir que retorne el atributo para confirmar
@nombre.deleter #Propiedad DELETER
def nombre(self):
print("Borrando nombre..")
del self.__nombre
#Hasta aquí property#
def peso(self): #Método para obtener el peso
return self.__peso #Aquí simplemente retorna el atributo privado
#Instanciamos
Mira = Perros('Mira', 13)
print (Mira.nombre) #Imprime el nombre de Mira. Se hace a través de getter
#Que en este caso como está después de property lo toma como el primer método.
Mira.nombre = 'Pingüino' #Cambiamos el atributo nombre que se hace a través de setter
del Mira.nombre #Borramos el nombre utilizando deleter |
7a165c4d007d1ba99dc4024e658e26bcc7dbee5d | hector81/Aprendiendo_Python | /Listas/Ordenacion_listas.py | 729 | 4.40625 | 4 | '''
ORDENACIÓN DE LISTAS
'''
x = [8, 2, 3, 7, 5, 3, 7, 3, 1]
print(x)
print(f"1. El mayor número de la lista ")
print(f"{max(x)}")
print(f"2. El menor número de la lista ")
print(f"{min(x)}")
print(f"3. Los tres mayores números de la lista ")
lista = sorted(x, reverse=True)
print(lista[0:3])
print(f"4. El mayor de los tres primeros números de la lista")
print(f"{max(x)}")
print(f"5. El menor de los cuatro últimos números de la lista ")
print(f"{min(x[len(x)-4:len(x)])}")
print(f"6. La suma de los cinco mayores números de la lista ")
print(f"{sum(lista[0:5])}")
print(f"7. La suma de los tres menores números de la lista")
print(f"{sum(x[len(lista)-3:len(lista)])}")
print(lista)
|
c0c4a0af0ececd8f413b847aee15a3c4ed1fa24e | hector81/Aprendiendo_Python | /String_Cadenas/NumeroLetrasPalabra.py | 627 | 4.03125 | 4 | def introducirPalabra():
while True:
try:
palabra = input("Por favor ingrese una palabra: ")
if palabra != '':
print("La palabra es " + palabra)
return palabra
break
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
palabra = introducirPalabra()
def numeroLetrasPalabra(palabra):
palabra = palabra.strip() # quitamos espacios blanco
longitud = len(palabra)
print('La palabra tiene este numero de letras = ' + str(longitud) )
numeroLetrasPalabra(palabra)
|
87001d9e5d3f5215feeaad10012c67e76ef88824 | hector81/Aprendiendo_Python | /CursoPython/Unidad5/Ejercicios/ejercicio_III_u5.py | 848 | 4.03125 | 4 | '''
Escriba un programa que resuelva el siguiente problema:
El índice de masa corporal IMC de una persona se calcula con la fórmula IMC=P/T2 en donde P es
el peso en Kg. y T es la talla en metros.
Reciba un valor de P y de T, calcule el IMC y muestre su estado según la siguiente tabla:
IMC Estado
Menos de 18.5 Desnutrido
18.5 a 25.5 Peso óptimo
Más de 25.5 Sobrepreso
'''
p = float(input("Escribe el valor de P: ")) # peso
t = float(input("Escribe el valor de T: ")) # altura
imc = p/t**2
if imc < 18.5:
print(f"Tú índice de masa corporal IMC es {imc} y tu estado es desnutrido.")
elif imc >= 18.5 and imc <= 25.5:
print(f"Tú índice de masa corporal IMC es {imc} y tu estado es peso óptimo.")
else:
print(f"Tú índice de masa corporal IMC es {imc} y tu estado es sobrepreso.") |
2a6dbf6e9c92a0d20b12ed8c7ec58f3959f0b702 | hector81/Aprendiendo_Python | /CursoPython/Unidad8/Ejemplos/principal_calculadora.py | 1,059 | 3.65625 | 4 | import calculadora
# Uso las funciones importadas
calculadora.suma(3,9)
calculadora.resta(3,9)
calculadora.multiplica(3,9)
calculadora.divide(3,9)
print('******************')
# igualo variables con las funciones importadas, y las uso como funciones directamente
suma = calculadora.suma
resta = calculadora.resta
multiplica = calculadora.multiplica
divide = calculadora.divide
suma(32,9)
resta(32,9)
multiplica(32,9)
divide(32,9)
print('******************')
# importo las funciones que me interesan del modulo calculadora
from calculadora import suma
suma(11,9)
from calculadora import resta
resta(11,9)
from calculadora import multiplica
multiplica(11,9)
from calculadora import divide
divide(11,9)
print('******************')
# importo las funciones que me interesan del modulo calculadora y les asigno un nombre de variable
from calculadora import suma as SU
SU(11,10)
from calculadora import resta as RE
RE(11,10)
from calculadora import multiplica as MU
MU(11,10)
from calculadora import divide as DI
DI(11,10)
|
a43ddbb034d53912e38c51fc663c49e12520f22f | hector81/Aprendiendo_Python | /CursoPython/Unidad4/Ejemplos/listas_funciones.py | 996 | 4.40625 | 4 | ''' funciones_listas '''
x = [20, 30, 40, 50, 30]
y = [20, "abc", 56, 90, "ty"]
print(len(x)) # devuelve numero elemento lista x
print(len(y)) # devuelve numero elemento lista x
#max y min solo funcionan con listas numéricas
print(max(x)) # maximo de la lista x
# ERROR # print(max(y)) # maximo de la lista y
print(min(x)) # MINIMO de la lista x
# ERROR # print(min(y)) # MINIMO de la lista y
''' FUNCION SUMA funcionan con listas numéricas '''
print(sum(x)) # sumaria todos los elementos de la lista x
# ERROR # print(sum(y)) # sumaria todos los elementos de la lista y
''' OPERADORES Y CONCATENADORES '''
c = x + y # me devuelve la concatenacion de ambas listas
print(c)
d = x * 3 # me devuelve 3 veces la misma lista en una sola lista
print(d)
''' BUSQUEDA in devuelve valores booleanos'''
print(23 in x)# me pregunta si 23 está en la lista x, y devuelve true o false
print(30 in x)# me pregunta si 23 está en la lista x, y devuelve true o false |
3230c051226bfb61c9388f98cb1a8f5b31b3ddbe | tk-learn-2020/tk-learn-2020 | /pa/lx/chapter08/metalcass_test.py | 1,740 | 3.734375 | 4 | # 类也是对象,type创建类的类
def create_class(name):
if name == "user":
class User:
def __str__(self):
return "user"
return User
elif name == "company":
class Company:
def __str__(self):
return "company"
return Company
# -----------------------------------------
# type 动态创建类
class BaseClass:
def answer(self):
return "i am baseclass"
def say(self):
return "fine"
User = type("User", (BaseClass,), {"name": "user", "say": say})
# -----------------------------------------
# 什么是元类,元类就是创建类的类,type是一个元类,
# python 中类的实例化过程, 首先会查找metaclass,通过metaclass创建User类, 找不到了则去基类查找
# type去创建类对象
class MetaClass(type):
# 这个就是元类, 元类控制实例化的过程
def __new__(cls, *args, **kwargs):
# caution: 这里要把 实例的实例化参数传进来
return super().__new__(cls, *args, **kwargs)
class Person(metaclass=MetaClass):
def __init__(self, name):
self.name = name
def __str__(self):
return "user"
# -----------------------------------------
from collections.abc import *
# 里边有很多metaclass
if __name__ == '__main__':
# -----------------------------------------
# MyClass = create_class("user")
# my_obj = MyClass()
# print(my_obj)
# -----------------------------------------
# my_obj = User()
# print(my_obj)
# print(my_obj.name)
# print(my_obj.say())
# print(my_obj.answer())
# -----------------------------------------
persion = Person("zzlion")
print(persion)
|
5a7bf9ca914cf05eeaa6f4e44edaef234758807e | tk-learn-2020/tk-learn-2020 | /pa/hl/collection/namedtuple_lern.py | 292 | 3.609375 | 4 | '''
@Author : hallen
@Contact : hallen200806@163.com
@Time : 2020-02-07
@Desc :
'''
from collections import namedtuple
# 相当于类的实例化,创建了一个Student类,一般用于数据库
Student = namedtuple("Student",['name','age','cla'])
user = Student("hallen",18,3)
print(user) |
f70ef591a26b376d9dcc79c30d9abcc5f55584be | 51042/fall-2017-hw7 | /problem2.py | 1,793 | 3.96875 | 4 | import pandas as pd
import numpy as np
def search_by_zip(dataframe):
"""
This function return a dataframe that contains restaurants that have failed an inspection within the last year within ZIP code 60661
Args: dataframe - DataFrame containing the original data.
Return: return a new dataframe which contains all rows from the old dataframe that match the criterion
"""
emps = pd.read_csv(dataframe)
emps['Inspection Date'] = emps['Inspection Date'].apply(lambda x: x[6:] + x[0:2] + x[3:5])
fails = emps[(emps['Facility Type'] == 'Restaurant') & (emps['Inspection Date'] >= '20161101') & (emps['Results'] == 'Fail') & (emps['Zip'] == 60661.0)]
return fails
def search_by_location(dataframe):
"""
This function return a dataframe that contains restaurants that have failed an inspection within the last year within 0.5 miles from Professor home.
Args: dataframe - DataFrame containing the original data.
Return: return a sorted dataframe which contains all rows from the old dataframe that match the criterion
"""
romano_latitude, romano_longitude = 41.8873906, -87.6459561
emps = pd.read_csv(dataframe)
emps['Inspection Date'] = emps['Inspection Date'].apply(lambda x: x[6:] + x[0:2] + x[3:5])
emps['Distance'] = ((emps['Latitude'] - romano_latitude) ** 2 + (emps['Longitude'] - romano_longitude) **2).apply(np.sqrt)
results = emps[(emps['Facility Type'] == 'Restaurant') & (emps['Inspection Date'] >= '20161101') & (emps['Results'] == 'Fail') & (emps['Distance'] <= 0.5)]
results = results.sort_values('Distance')
return results
if __name__ == "__main__":
x = search_by_zip('Food_Inspections.csv')
y = search_by_location('Food_Inspections.csv')
print(x)
print("_" * 100)
print(y)
|
136ee1667d06e6cd8c6aeaca2ca6bf71d0c645cf | qtpeters/please-respond | /pleaserespond/main.py | 1,073 | 3.953125 | 4 |
from pleaserespond.prm import PleaseRespond
from sys import exit
DEFAULT_SEC = 60
def format_input( seconds ):
"""
Verifies that the value passed in is an integer
and if nothing is poassed in, the default is set.
"""
try:
if seconds == "":
seconds = DEFAULT_SEC
return int( seconds )
except:
print( "This (%s) is not acceptable input, please enter an integer" % seconds )
exit( 1 )
def main( seconds ):
"""
The main method. This gathers user
input and starts the application.
After the process is finished, it
displays the report to the user.
"""
# Get the duration from the user and make sure it's what we expect
if not seconds:
seconds = input( "Specify the number of seconds[%s]: " % DEFAULT_SEC )
i_seconds = format_input( seconds )
# Start collecting RSVPs from Meetup.com
please_respond = PleaseRespond( i_seconds )
please_respond.stream()
# Get the report and display it.
data = please_respond.report()
print( data )
|
722c65fc407a270f156204cc2c568cb5f2bf1381 | Nook-0/BD | /1/script/test_parser.py | 4,926 | 4.03125 | 4 | #!/usr/bin/env python3
# coding: utf8
import re
import sys
# Функция для очистки строки от двойных пробелов, пробела в начале строки и в конце
def deleteSpace(string):
if len(string) > 0:
while(string[0]==" "):
string = string[1:]
for i in range(len(string)-3):
if string[i+1] == " " and string[i] == " ":
string = string[:i] + string[(i+1):]
while(string[len(string)-1]==" "):
string = string[:-1]
return string
else:
return ""
# Функция для склеивания строк с разделителем
def splitData(string, tempString):
if string == "":
string = deleteSpace(tempString)
else:
string = deleteSpace(string) + "|" + deleteSpace(tempString)
return string
# Функция для составления строки шифров
def useCipher(line, it_cipher):
for item in (re.findall(x, line))[0].split("+"):
it_cipher = splitData(it_cipher, useRegular(REGULAR_CLEANING_FOR_CIPHER, item))
return it_cipher
# Функция для применения регулярного выражения к строке
def useRegular(REGULAR, item):
return re.sub(REGULAR, '', item)
# Функция для проверки на не пустую строку
def isNotEmpty(string):
if len(string) > 0:
return True
else:
return False
# Регулярные выражения для поиска строк из документа
REGULAR_FIO = r"\\fio.*\{(.*)\}\{(.*)\}\{([^}]*)\}\ ?"
REGULAR_BBK = r"\\bbk\{(.*)\}.*"
REGULAR_UDK = r"\\udk\{(.*)\}.*"
REGULAR_KEYWORDS = r"\\keywords\{(.*)\}\{.*"
REGULAR_ART = r"\\art(\[.*\])?\{(.*)\}\{(.*)\}.*"
# Регулярные выражения для очистки строк от не нужной информации (пробелы/английские буквы/и т.д.)
REGULAR_CLEANING = r"[аАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяЯ\,\.\-]*"
REGULAR_CLEANING_FOR_CIPHER = r"[^\d.]*"
REGULAR_CLEANING_SPACE = r"[^аАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяЯ\,\.\ \-]*"
REGULAR_CLEANING_FOR_FIO = r"[^аАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяЯ]*"
# Переменные для хранения данных
lists = [REGULAR_FIO, REGULAR_BBK, REGULAR_UDK, REGULAR_KEYWORDS, REGULAR_ART]
fio_list = ""
keyword = ""
sum_authors = 0
udk = ""
bbk = ""
art = ""
# Чтение файла .tex с принудительной кодировкой UTF-8 и запись его в list
if len(sys.argv) > 1:
f = open(sys.argv[1], 'r')
list = f.readlines()
if(len(list) == 0):
print("This file is empty.")
else:
# Чтение списка и поиск ключеных слов с помощью регулярных выражений
for line in list:
for x in lists:
if len(re.findall(x, line)) != 0:
if isNotEmpty(fio_list) & isNotEmpty(art) & isNotEmpty(bbk) & isNotEmpty(udk) & isNotEmpty(keyword):
break
if x == REGULAR_FIO: # если строка относится к ФИО
sum_authors += 1
tempFio = ""
for itemFio in re.findall(x, line)[0]:
tempFio = tempFio + " " + useRegular(REGULAR_CLEANING_FOR_FIO, itemFio)
fio_list = splitData(fio_list, tempFio)
if x == REGULAR_BBK: # если строка относится к шифру ББК
bbk = useCipher(line, bbk)
if x == REGULAR_UDK: # если строка относится к шифру УДК
udk = useCipher(line, udk)
if x == REGULAR_KEYWORDS: # если строка относится к ключевым словам
for y in useRegular(REGULAR_CLEANING_SPACE, (re.findall(x, line))[0]).split(", "):
if len(re.findall(REGULAR_CLEANING, y)[0]) != 0:
keyword = splitData(keyword, y)
if x == REGULAR_ART: # если строка относится к названию статьи
art = deleteSpace(useRegular(REGULAR_CLEANING_SPACE, (re.findall(x, line))[0][1]))
print(str(sum_authors) + ";" + fio_list + ";" + art + ";" + bbk + ";" + udk + ";" + keyword + ";")
list.clear()
else:
print("Error in read file or file name not found.") |
1861072d9b295defbd8c98e1a0d9a0914f3cfc54 | JDavid550/Python-Intermedio | /dics_Comprehenssions.py | 244 | 3.921875 | 4 | def run():
my_dic = {}
for i in range(1,101):
if i%3 != 0:
my_dic[i] = i**3
print(my_dic)
my_dic2 = {i: i**3 for i in range(0,101) if i%3 != 0}
print(my_dic2)
if __name__ == '__main__':
run() |
7915e90dd431cedcd1820486783a299df813b0b9 | SoumyaMalgonde/AlgoBook | /python/sorting/selection_sort.py | 654 | 4.21875 | 4 | #coding: utf-8
def minimum(array, index):
length = len(array)
minimum_index = index
for j in range(index, length):
if array[minimum_index] > array[j]:
minimum_index = j
return minimum_index
def selection_sort(array):
length = len(array)
for i in range(length - 1):
minimum_index = minimum(array, i)
if array[i] > array[minimum_index]:
array[i], array[minimum_index] = array[minimum_index], array[i]
if __name__ == "__main__":
entry = input("Enter numbers separated by space: => ")
array = [int(x) for x in entry.split()]
selection_sort(array)
print(array)
|
15c813389a914213fee28c4cba5c86d3fdfbcd09 | SoumyaMalgonde/AlgoBook | /python/dynamic_programming/Edit_distance.py | 1,450 | 4 | 4 | # PROBLEM STATEMENT :
# Given two words str1 and str2, find the minimum number of operations required to convert str11 to str22.
# You have the following 3 operations permitted on a word:
# 1.Insert a character
# 2.Delete a character
# 3.Replace a character
# This is very Famous Dynamic Programming Problem called is Edit distance or Levenshtein algorithm
def editdistance(str1 , str2):
m = len(str1)
n = len(str2)
# intialize with zeros
dp = [[0 for x in range(n+1)] for x in range(m + 1)]
for i in range(m + 1):
for j in range(n+1):
# if first string empty then add all character of second string
if i==0:
dp[i][j] = j
# if second string is empty then we heva one option to remove all charcetrs from second string.
elif j==0:
dp[i][j] = i
# if both string last character are same then ignore and skip it
elif str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1]
# not if character does not match then we have to check for all possibilites insert, remove and replace
else:
dp[i][j] = 1 + min(dp[i][j-1], # insert
dp[i-1][j], # remove
dp[i-1][j-1]) # replace
return dp[m][n]
str_1 = input()
str_2 = input()
print(editdistance(str_1 , str_2))
|
89994bd9a42798d11b46f6427eb811bfb0192fab | SoumyaMalgonde/AlgoBook | /python/string algorithms/Suffix_Array.py | 2,358 | 3.765625 | 4 |
class SuffixArray(object):
def __init__(self,array,n):
self.array = self.array #initial array
self.n = n #size of array
#dividing a word into its suffixes
def divideWordToSuffixes(self,word):
suffixes = []
n = len(word)
suffixes.append("$") #end terminal, starting symbol
for i in range(n):
suffixes.append(word[i::] + "$")
return suffixes
#sorting suffixes
def sortSuffixes(self,suffixes):
return sorted(suffixes)
def createSuffixArray(self):
suffix_array = []
for i in range(self.n):
suffix_array.append(self.divideWordsToSuffixes(self.array[i]))
return self.sortSuffixes(suffix_array)
#searching element in O(logn) for pattern matching purposes
def binarySearch(self,data,lo,hi,target):
if(lo < hi):
return False
mid = (lo + hi)//2
if(data[mid] == target):
return mid
elif(data[mid] < target):
self.binarySearch(data,mid+1,hi,target)
else:
self.binarySearch(data,lo,mid-1,target)
#finding out whether some pattern P matches our word
def is_P_Matches(self,P,suffix_array):
m = len(P)
lo = 0
hi = m-1
found = self.binarySearch(suffix_array,lo,hi,P)
if(!found):
return False
else:
return found
#finding all branching words
def collectBrachingWords(self,suffix_array):
n = len(suffix_array)
braching_words = []
for i in range(n):
j = i+1
branching_word = ""
while(j < n):
k = 0
while(k < len(suffix_array[i])):
if(suffix_array[i][k] == suffix_array[j][k]):
braching_word += suffix_array[i][k]
else:
break
k += 1
branching_words.append(braching_word)
j += 1
return braching_words
#finding longest common prefix
def LCP(self,suffix_array):
pass
def longestSubstring(self,suffix_array):
return self.LCP(suffix_array)
def main():
array = ["SDU","is","located","in","Kaskelen"]
SuffixArray = SuffixArray(array,len(array)) |
8ede8fe5b57dd3e897f6a08cc4ae9d0edfa80d98 | SoumyaMalgonde/AlgoBook | /python/Matrix/Spiral_Print.py | 875 | 3.984375 | 4 | def Spiralprint(matrix):
top = left = 0 # initializing with top
bottom = len(matrix) - 1
right = len(matrix[0]) - 1
while True:
if left > right:
break
# print top row
for i in range(left, right + 1):
print(matrix[top][i], end=' ')
top = top + 1
if top > bottom:
break
# print right column
for i in range(top, bottom + 1):
print(matrix[i][right], end=' ')
right = right - 1
if left > right:
break
# print bottom row
for i in range(right, left - 1, -1):
print(matrix[bottom][i], end=' ')
bottom = bottom - 1
if top > bottom:
break
# print left column
for i in range(bottom, top - 1, -1):
print(matrix[i][left], end=' ')
left = left + 1
rows = int(input())
cols = int(input())
matrix = []
for i in range(0, rows):
arr = list(map(int, input().split()[:cols]))
matrix.append(arr)
Spiralprint(matrix) |
3b68f1f217fd64cc0428e93fbfe17745c664cb2e | SoumyaMalgonde/AlgoBook | /python/maths/jaccard.py | 374 | 4.1875 | 4 |
a = set()
b = set()
m = int(input("Enter number elements in set 1: "))
n = int(input("Enter number elements in set 2: "))
print("Enter elements of set 1: ")
for i in range(m):
a.add(input())
print("Enter elements of set 2: ")
for i in range(n):
b.add(input())
similarity = len(a.intersection(b))/len(a.union(b))
print("Similarity index: {} ".format(similarity)) |
df7feb3e68df6d0434ed16f02ce3fcf0fd1dbf99 | SoumyaMalgonde/AlgoBook | /python/maths/Volume of 3D shapes.py | 2,970 | 4.1875 | 4 | import math
print("*****Volume of the Cube*****\n")
side=float(input("Enter the edge of the cube "))
volume = side**3
print("Volume of the cube of side = ",side," is " ,volume,)
print("\n*****Volume of Cuboid*****\n")
length=float(input("Enter the length of the cuboid "))
breadth=float(input("Enter the breadth of the cuboid "))
height=float(input("Enter the height of the cuboid "))
volume=length * breadth * height
print("Volume of the cuboid of length = ",length,", breadth = ",breadth,", height = ",height," is " ,volume)
print("\n*****Volume of cone*****\n")
radius = float(input("Enter the radius of the cone "))
height = float(input("Enter the height of the cone "))
volume = round((((math.pi)*(radius**2)*height)/3),2)
print("Volume of cone of radius = ",radius,", height = ", height, " is ", volume)
print("\n*****Volume of right circular cone*****\n")
radius = float(input("Enter the radius of the right circular cone "))
height = float(input("Enter the height of the right circular cone "))
volume = round((((math.pi)*(radius**2)*height)/3),2)
print("Volume of right circular cone of radius = ",radius,", height = ", height, " is ", volume)
print("\n*****Volume of a prism*****\n")
base_length = float(input("Enter the length of the base "))
base_breadth = float(input("Enter the breadth of the base "))
height = float(input("Enter the height of the prism"))
base_area = base_length * base_breadth
volume = base_area * height
print("Volume of prism of base area =",base_area,", height = ",height, " is ",volume)
print("\n*****Volume of different types of pyramid*****\n")
apothem = float(input("Enter the apothem length of the pyramid "))
base = float(input("Enter the base length of the pyramid "))
height = float(input("Enter the height of the pyramid "))
volume_square = ((base**2)*height)/3
volume_triangle = (apothem * base * height)/6
volume_pentagon = (5 * apothem * base * height)/6
volume_hexagon = apothem * base * height
print("\nVolume of a square pyramid of base = ",base,", height = ",height, " is ", volume_square)
print("Volume of a triangular pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_triangle)
print("Volume of a pentagonal pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_pentagon)
print("Volume of a hexagonal pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_hexagon)
print("\n*****Volume of Sphere*****\n")
radius = float(input("Enter the radius of the sphere "))
volume = round((4 * (math.pi) * (radius**3))/3)
print("Volume of the sphere of radius = ",radius," is ",volume)
print("\n*****Volume of circular cylinder*****\n")
radius = float(input("Enter the radius of the circular cylinder "))
height = float(input("Enter the height of the circular cylinder "))
volume = round((math.pi) * (radius**2) * height)
print("Volume of the circular cylinder of radius = ",radius,", height = ",height," is ",volume) |
79ba3736029a2bc29aa10adafc50ef24b92be115 | SoumyaMalgonde/AlgoBook | /python/string algorithms/kmp_string_matching.py | 2,451 | 4.09375 | 4 | '''
For details on the working of the algorithm, refer this video by Abdul Bari:
https://www.youtube.com/watch?v=V5-7GzOfADQ
'''
'''
Defining the KMP Search function
'''
def KMPSearchfn(pattern, input_text):
len_pattern = len(pattern)
len_input = len(input_text)
pi = [0]*len_pattern #pi is the piArray that is used in KMP computation
j = 0 #j is the iterator for pattern
# computing the pi array of prefix-suffix values
piArray(pattern, len_pattern, pi)
i = 0 #iterator for input_text
while i < len_input:
#if the current letters match, we move both in text & pattern
if pattern[j] == input_text[i]:
i += 1
j += 1
#if we reach the end of the pattern, that means that the whole pattern
#is matched. Hence, we can return the index
if j == len_pattern:
print ("Found pattern at index " + str(i-j) + " of the string")
j = pi[j-1]
#if neither of the above case AND the chars don't match,
#we move j backwards acc. to the pi array values
elif i < len_input and pattern[j] != input_text[i]:
if j != 0:
j = pi[j-1]
#in this subcase, j cannot be moves backwards, so we move i forwards
else:
i += 1
#if we complete our search and final value of j<len_pattern, then we
#can conclude that we didn't find the string
if(j<len_pattern):
print("The pattern is not present in the string")
'''
Defining the piArray auxillary function, which constructs the piArray
used during KMP searching
'''
def piArray(pattern, len_pattern, pi):
l = 0 # length of the previous longest prefix suffix
pi[0] # pi[0] is 0, since it is the starting
i = 1
# the loop calculates pi[i] for i = 1 to (len_pattern-1)
while i < len_pattern:
if pattern[i]== pattern[l]:
l += 1
pi[i] = l
i += 1
else:
if l != 0:
l = pi[l-1]
else:
pi[i] = 0
i += 1
if __name__ == "__main__":
print("_______This is the Knuth-Morris-Pratt pattern searching algo________\n\n")
print("Enter the text body to be searched IN:")
input_text = input()
print("Enter the string to be searched")
pattern = input()
KMPSearchfn(pattern, input_text) |
bb114c561547aa3adbcf855e3e3985e08c748a01 | SoumyaMalgonde/AlgoBook | /python/sorting/Recursive_quick_sort.py | 834 | 4.1875 | 4 | def quick_sort(arr, l, r): # arr[l:r]
if r - l <= 1: # base case
return ()
# partition w.r.t pivot - arr[l]
# dividing array into three parts one pivot
# one yellow part which contains elements less than pivot
# and last green part which contains elements greater than pivot
yellow = l + 1
for green in range(l+1, r):
if arr[green] <= arr[l]:
arr[yellow], arr[green] = arr[green], arr[yellow]
yellow += 1
# move pivot into place
arr[l], arr[yellow - 1] = arr[yellow - 1], arr[l]
quick_sort(arr, l, yellow-1) # recursive calls
quick_sort(arr, yellow, r)
return arr
print("Enter elements you want to sort: ")
array = list(map(int, input().split()))
sorted_array = quick_sort(array, 0, len(array))
print("Sorted array is: ", *sorted_array) |
0be537def5f8cc9ba9218267bf774b28ee44d4c7 | SoumyaMalgonde/AlgoBook | /python/graph_algorithms/Dijkstra's_Shortest_Path_Implementation_using_Adjacency_List.py | 2,933 | 3.921875 | 4 | class Node_Distance :
def __init__(self, name, dist) :
self.name = name
self.dist = dist
class Graph :
def __init__(self, node_count) :
self.adjlist = {}
self.node_count = node_count
def Add_Into_Adjlist(self, src, node_dist) :
if src not in self.adjlist :
self.adjlist[src] = []
self.adjlist[src].append(node_dist)
def Dijkstras_Shortest_Path(self, source) :
# Initialize the distance of all the nodes from source to infinity
distance = [999999999999] * self.node_count
# Distance of source node to itself is 0
distance[source] = 0
# Create a dictionary of { node, distance_from_source }
dict_node_length = {source: 0}
while dict_node_length :
# Get the key for the smallest value in the dictionary
# i.e Get the node with the shortest distance from the source
source_node = min(dict_node_length, key = lambda k: dict_node_length[k])
del dict_node_length[source_node]
for node_dist in self.adjlist[source_node] :
adjnode = node_dist.name
length_to_adjnode = node_dist.dist
# Edge relaxation
if distance[adjnode] > distance[source_node] + length_to_adjnode :
distance[adjnode] = distance[source_node] + length_to_adjnode
dict_node_length[adjnode] = distance[adjnode]
for i in range(self.node_count) :
print("Source Node ("+str(source)+") -> Destination Node(" + str(i) + ") : " + str(distance[i]))
def main() :
g = Graph(6)
# Node 0: <1,5> <2,1> <3,4>
g.Add_Into_Adjlist(0, Node_Distance(1, 5))
g.Add_Into_Adjlist(0, Node_Distance(2, 1))
g.Add_Into_Adjlist(0, Node_Distance(3, 4))
# Node 1: <0,5> <2,3> <4,8>
g.Add_Into_Adjlist(1, Node_Distance(0, 5))
g.Add_Into_Adjlist(1, Node_Distance(2, 3))
g.Add_Into_Adjlist(1, Node_Distance(4, 8))
# Node 2: <0,1> <1,3> <3,2> <4,1>
g.Add_Into_Adjlist(2, Node_Distance(0, 1))
g.Add_Into_Adjlist(2, Node_Distance(1, 3))
g.Add_Into_Adjlist(2, Node_Distance(3, 2))
g.Add_Into_Adjlist(2, Node_Distance(4, 1))
# Node 3: <0,4> <2,2> <4,2> <5,1>
g.Add_Into_Adjlist(3, Node_Distance(0, 4))
g.Add_Into_Adjlist(3, Node_Distance(2, 2))
g.Add_Into_Adjlist(3, Node_Distance(4, 2))
g.Add_Into_Adjlist(3, Node_Distance(5, 1))
# Node 4: <1,8> <2,1> <3,2> <5,3>
g.Add_Into_Adjlist(4, Node_Distance(1, 8))
g.Add_Into_Adjlist(4, Node_Distance(2, 1))
g.Add_Into_Adjlist(4, Node_Distance(3, 2))
g.Add_Into_Adjlist(4, Node_Distance(5, 3))
# Node 5: <3,1> <4,3>
g.Add_Into_Adjlist(5, Node_Distance(3, 1))
g.Add_Into_Adjlist(5, Node_Distance(4, 3))
g.Dijkstras_Shortest_Path(0)
print("\n")
g.Dijkstras_Shortest_Path(5)
if __name__ == "__main__" :
main() |
67733ad845f63525ba2aa25faf37fb35b5456eb8 | SoumyaMalgonde/AlgoBook | /ml/Perceptrons/perceptronasand.py | 883 | 3.609375 | 4 | import numpy as np
## step-function
def step(vec):
""" returns 1 when true and 0 when false """
if vec >= 0 :
return 1
else:
return 0
## perceptron model
def perceptron(x, w, b):
""" defining the perceptron model
x = Inputs
w = weights
b = bias
"""
vec = np.dot(w, x) + b
y = step(vec)
return y
## AND function
def AND_gate(x):
""" defining the AND Logic Gate
w1 = 1.0
w2 = 1.0
b = -2.0
"""
w = np.array([1,1])
b = -2.0
return perceptron(x, w, b)
## TESTING
t1 = np.array([0, 1])
t2 = np.array([1, 1])
t3 = np.array([0, 0])
t4 = np.array([1, 0])
## Displaying Results
print("AND({}, {}) = {}".format(0, 1, AND_gate(t1)))
print("AND({}, {}) = {}".format(1, 1, AND_gate(t2)))
print("AND({}, {}) = {}".format(0, 0, AND_gate(t3)))
print("AND({}, {}) = {}".format(1, 0, AND_gate(t4))) |
c181d9bec769479718d31c01abb07f457f36a512 | SoumyaMalgonde/AlgoBook | /python/sorting/slow_sort.py | 394 | 3.859375 | 4 | def SlowSort(A, i, j):
if i >= j:
return
m = ((i + j) // 2)
SlowSort(A, i, m)
SlowSort(A, m + 1, j)
if A[m] > A[j]:
A[m], A[j] = A[j], A[m]
SlowSort(A, i, j - 1)
return A
# Example run of SlowSort
def main():
arr = [2, 7, 9, 3, 1, 6, 5, 4, 12]
print("Result: " + str(SlowSort(arr, 0, len(arr) - 1)))
if __name__ == "__main__":
main()
|
54bda362f5d8412257a1587629eeefa7e912e3fc | ajayram515/SearchString | /project.py | 1,566 | 4.09375 | 4 | #operating system dependent functionality
import os
# Ask the user to enter directory path
search_path = raw_input("Enter directory path to search : ")
# Ask the user to enter type of file
file_type = raw_input("File Type : ")
# Ask the user to enter string to be searched
search_str = raw_input("Enter the search string : ")
# Add a directory separator if user didn't gave it in input
if not (search_path.endswith("/") or search_path.endswith("\\") ):
search_path = search_path + "/"
# If path does not exist, set search path to Home directory
if not os.path.exists(search_path):
search_path ="/home/aj/"
# Repeat for each file in the directory
for fname in os.listdir(search_path):
# open only file with given extension
if fname.endswith(file_type):
# Open file
fo = open(search_path + fname)
# Read the first line from the file
line = fo.readline()
# counter for line number
line_no = 1
# Loop until last line of file
while line != '' :
# Search for string in line number
index = line.find(search_str)
if ( index != -1) :
print 'file name:',fname, '[', 'line no',line_no, ',','index',index, ']', line
# Read next line
line = fo.readline()
# Increment line counter
line_no += 1
# Close the file
fo.close()
|
b097d704c215d601a01a227bd6b045c46ba97e68 | maxmarzolf/random-objects | /Coffee.py | 972 | 3.8125 | 4 | class Coffee:
def __init__(self, roast, size, ice, temperature, price):
self.roast = roast
self.size = size
self.ice = ice
self.temperature = temperature
self.price = price
def is_hot(self, current_temperature, contains_ice):
"""your coffee is too cold unless iced"""
if contains_ice is False:
if current_temperature > 100:
return self.temperature == 'warm'
else:
return self.temperature == 'not warm'
def calculate_price(self):
if self.size == 'large':
return self.price * 1.5
@staticmethod
def add_cream():
return True
@staticmethod
def wired(caffeine_content):
if caffeine_content > '350mg':
return 'too much caffeine'
else:
return 'all good'
my_coffee = Coffee('americano', 'large', True, 40, 3.50)
my_price = my_coffee.calculate_price()
print(my_price)
|
9656e8cf77882c4fbdabb5ebb11e3220ff0d4bc3 | scemama/basis_set_exchange | /basis_set_exchange/writers/common.py | 359 | 3.546875 | 4 | '''
Helper functions for writing out basis set in various formats
'''
def find_range(coeffs):
'''
Find the range in a list of coefficients where the coefficient is nonzero
'''
coeffs = [float(x) != 0 for x in coeffs]
first = coeffs.index(True)
coeffs.reverse()
last = len(coeffs) - coeffs.index(True) - 1
return first, last
|
fe5d8d2fd1d1c5561a83bab930d61f36f1311557 | Notgnoshi/research | /haikulib/eda/colors.py | 4,278 | 3.765625 | 4 | """Perform exploratory data analysis to parse colors from the haiku dataset.
find_colors() is used to initialize the haiku dataset, while get_color_counts is used to process
the prepared dataset after it's been initialized.
"""
import colorsys
import itertools
from collections import Counter
from typing import Iterable, List, Tuple
import nltk
import pandas as pd
import webcolors
from haikulib.data import get_data_dir, get_df
def __get_colors() -> pd.DataFrame:
"""Get a DataFrame of color -> HTML colors.
Note that this CSV file uses hex RGB color codes for many of the colors, but falls back to using
HTML named colors for colors without an RGB value.
The colors with RGB values came from https://xkcd.com/color/rgb/ while the colors with the named
values came from
https://medium.com/@eleanorstrib/python-nltk-and-the-digital-humanities-finding-patterns-in-gothic-literature-aca84639ceeb
"""
return pd.read_csv(get_data_dir() / "colors.csv", index_col=0)
def __get_colors_dict() -> dict:
"""Get a dictionary of color -> HTML color mappings."""
df = __get_colors()
return {row["color"]: row["hex"] for index, row in df.iterrows()}
COLORS = __get_colors_dict()
COLOR_POS_TAGS = frozenset({"JJ", "NN"})
def is_color(tagged_word: Tuple[str, str]) -> bool:
"""Determine if the given word is a color based on its part-of-speech.
:param tagged_word: A word that's been tagged with nltk.pos_tag()
"""
word, pos = tagged_word
return pos in COLOR_POS_TAGS and word in COLORS
def find_colors(text: Iterable[Tuple[str, str]]) -> List[str]:
"""Return an unordered list of colors from the given POS-tagged text.
Check for 1, 2, and 3-gram colors like "dark blue".
Attempt to make the 1, 2, 3-grams exclusive so that a text containing "light olive green"
(#a4be5c) will return just
["light olive green"]
instead of
["light", "olive", "green", "olive green", "light olive green"]
:param text: The POS-tagged text to search for colors.
:return: A list of colors appearing in the provided text.
"""
colors = []
# Pad the right of any text that is too short to prevent a nasty crash.
ngrams = nltk.ngrams(text, n=3, pad_right=True, right_pad_symbol=("?", "??"))
for ngram in ngrams:
word = " ".join(w[0] for w in ngram)
# Check the 3-gram
if word in COLORS:
colors.append(word)
# Skip over the rest of this ngram.
next(ngrams)
next(ngrams)
# If the 3-gram wasn't a color, check the 2-gram.
else:
word = " ".join(w[0] for w in ngram[:2])
if word in COLORS:
colors.append(word)
# Skip over the rest of this ngram.
next(ngrams)
# If the 2-gram wasn't a color, check the 1-gram, using the tagged part-of-speech.
elif is_color(ngram[0]):
colors.append(ngram[0][0])
try:
# Check the last 2-gram and the last two 1-grams by hand (skipped by loop)
if ngram[1:] in COLORS:
word = " ".join(w[0] for w in ngram[1:])
colors.append(word)
else:
if is_color(ngram[-2]):
colors.append(ngram[-2][0])
if is_color(ngram[-1]):
colors.append(ngram[-1][0])
except UnboundLocalError:
# As with life, problems are best left ignored.
pass
return colors
def get_colors() -> pd.DataFrame:
"""Get a DataFrame of the haiku color usage counts, hex, RGB, HSV, and HLS representations."""
color_counts = Counter(itertools.chain.from_iterable(get_df()["colors"].tolist()))
colors = __get_colors()
colors["count"] = 0
for index, row in colors.iterrows():
color = row["color"]
colors.at[index, "count"] = color_counts[color] if color in color_counts else 0
colors["rgb"] = colors["hex"].apply(webcolors.hex_to_rgb)
# Normalize RGB values to [0, 1]
colors["rgb"] = colors["rgb"].apply(lambda t: tuple(v / 255 for v in t))
colors["hsv"] = colors["rgb"].apply(lambda t: colorsys.rgb_to_hsv(*t))
colors["hls"] = colors["rgb"].apply(lambda t: colorsys.rgb_to_hls(*t))
return colors
|
a8f650bbdeda5e903dc269d6bbf8ec56ce296aaf | BiYingP/a3 | /cal.py | 3,075 | 4.03125 | 4 | #!/usr/bin/python
# calc.py
# BiYing Pan
# 05.10.18
# This program is to create a calculator that parses an infix expression into postix, then evaluates it
import sys
class Stack:
# empty stack
def __init__(self):
self.s = []
# display the stack
def __str__(self):
return str(self.s)
# add a new element to top of stack
def push(self, x):
self.s.append(x)
# remove the top elment from stack
def pop(self):
return self.s.pop()
# empty the stack
def isEmpty(self):
return self.s == []
# see what elment is on the top of stack
def top(self):
return self.s[-1]
# the precedence of the operators
def precedence(op):
if op == "(" or op == ")":
return 1
if op == "+" or op == "-":
return 2
if op == "*" or op == "/" or op == "%":
return 3
# infix to postfix
def infix2postfix(exp):
stack = Stack()
postfix = []
infix = exp.split()
for op in infix:
# if it is a left (, push it to the stack
if (op == "("):
stack.push(op)
elif (op == ")"):
# pop operators from the stack
top = stack.pop()
while (top != "("):
# append to the postfix
postfix.append(top)
top = stack.pop()
elif (op.isdigit()):
# append int to the postfix
postfix.append(op)
else:
p = precedence(op)
# an operator is encountered
while not stack.isEmpty() and p <= precedence(stack.top()):
postfix.append(stack.pop())
stack.push(op)
while not stack.isEmpty():
postfix.append(stack.pop())
return " ".join(postfix)
# evalPostfix
def evalPostfix(exp):
stack = Stack()
token = exp.split()
for op in token:
if (op.isdigit()):
stack.push(op)
else:
# op1 and op2
op2 = int(stack.pop())
op1 = int(stack.pop())
# cal and push result
if (op == "+"):
stack.push(op1 + op2)
if (op == "-"):
stack.push(op1 - op2)
if (op == "*"):
stack.push(op1 * op2)
if (op == "/"):
stack.push(op1 / op2)
if (op == "%"):
stack.push(op1 % op2)
# print result
print"".join(exp), "=", stack.pop()
if __name__ == "__main__":
if len(sys.argv) < 2:
# read stdin
f = sys.stdin
# read 120 char each line
char = f.read(120)
while char:
postfix = infix2postfix(char)
evalPostfix(postfix)
char = f.read(120)
f.close()
else:
# read file
f = open(sys.argv[1])
for l in f:
lines = l.strip()
# call infix2postfix() to get postfix
postfix = infix2postfix(l)
# call evalPostfix() to get result
evalPostfix(postfix)
f.close()
|
f9daa2cda430545c2e026f8decfdd09440b9cf1f | gregphillips03/Modeling-and-Simulation | /p0/wphilli2_ngram.py | 6,369 | 3.921875 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# p0 ngram
# William (Greg) Phillips
# Finalized
# ------------------------ #
# --- Section 0 - Meta --- #
# ------------------------ #
'''
NLTK was not allowed for use in this exercise
Written in Python 2.7, hence the magic statement on the 1st/2nd lines
Project Gutenberg file contains many characters that fall outside of the ASCII range
UTF-8 encoding is necessary to get rid of pesky 'weird' Shakespearean'istical characters
'''
# --------------------------- #
# --- Section 1 - Imports --- #
# --------------------------- #
import random;
import string;
import sys;
import re;
# ---------------------------------------- #
# --- Section 2 - Function Defintiions --- #
# ---------------------------------------- #
def get_tokens(path):
with open(path, 'r') as shake:
text = shake.read();
lower = text.lower();
cleanse = re.sub('[^a-z \n]+', '', lower)
tokens = cleanse.split();
return tokens;
class Chain:
#constructor to initiate a memory slot for a dictionary
def __init__(self):
self.memory = {};
#check this object for the key value pair
def _learn_key(self, key, value):
if key not in self.memory:
self.memory[key] = [];
self.memory[key].append(value);
#bigrams
def learn_bi(self, tokens):
bigrams = [(tokens[i], tokens[i + 1]) for i in range(0, len(tokens) - 1)];
for bigram in bigrams:
self._learn_key(bigram[0], bigram[1]);
#trigrams
def learn_tri(self, tokens):
trigrams = [(tokens[i], tokens[i + 1], tokens[i + 2]) for i in range(0, len(tokens) - 2)];
for trigram in trigrams:
self._learn_key(trigram[1], trigram[2]);
#quadgrams
def learn_quad(self, tokens):
quadgrams = [(tokens[i], tokens[i + 1], tokens[i + 2], tokens[i + 3]) for i in range(0, len(tokens) - 3)];
for quadgram in quadgrams:
self._learn_key(quadgram[2], quadgram[3]);
#quingrams
def learn_quin(self, tokens):
quingrams = [(tokens[i], tokens[i + 1], tokens[i + 2], tokens[i + 3], tokens[i+4]) for i in range(0, len(tokens) - 4)];
for quingram in quingrams:
self._learn_key(quingram[3], quingram[4]);
#hexagrams
def learn_hexa(self, tokens):
hexagrams = [(tokens[i], tokens[i + 1], tokens[i + 2], tokens[i + 3], tokens[i+4], tokens[i+5]) for i in range(0, len(tokens) - 5)];
for hexagram in hexagrams:
self._learn_key(hexagram[4], hexagram[5]);
#septagrams
def learn_septa(self, tokens):
septagrams = [(tokens[i], tokens[i + 1], tokens[i + 2], tokens[i + 3], tokens[i+4], tokens[i+5], tokens[i+6]) for i in range(0, len(tokens) - 6)];
for septagram in septagrams:
self._learn_key(septagram[5], septagram[6]);
#octagrams
def learn_octa(self, tokens):
octagrams = [(tokens[i], tokens[i + 1], tokens[i + 2], tokens[i + 3], tokens[i+4], tokens[i+5], tokens[i+6], tokens[i+7]) for i in range(0, len(tokens) - 7)];
for octagram in octagrams:
self._learn_key(octagram[6], octagram[7]);
#nonagrams
def learn_nona(self, tokens):
nonagrams = [(tokens[i], tokens[i + 1], tokens[i + 2], tokens[i + 3], tokens[i+4], tokens[i+5], tokens[i+6], tokens[i+7], tokens[i+8]) for i in range(0, len(tokens) - 8)];
for nonagram in nonagrams:
self._learn_key(nonagram[7], nonagram[8]);
#simple way to slide across the dictionary in memory
def _next(self, current_state):
next_poss = self.memory.get(current_state);
if not next_poss:
next_poss = self.memory.keys();
return random.sample(next_poss, 1)[0];
#generate a chain of words
def my_markov(self, amount, state=''):
if not amount:
return state;
next_word = self._next(state);
return state + ' ' + self.my_markov(amount - 1, next_word);
# ------------------------ #
# --- Section 3 - Main --- #
# ------------------------ #
def p0(path):
print(path);
tokens = get_tokens(path);
total_count = len(tokens);
print(total_count);
# ------------------------ #
# --- Section 4 Unigram--- #
# ------------------------ #
unigrams = {};
for word in tokens:
if word in unigrams:
unigrams[word] += 1;
else:
unigrams[word] = 1;
#switch to frequency
for word in unigrams:
unigrams[word] /= float(total_count);
#make a chain of words
out = [];
for _ in range(100):
r = random.random();
accumulator = .0;
for word, freq in unigrams.iteritems():
accumulator += freq;
if accumulator >= r:
out.append(word);
break;
print('Unigram Build: \n')
print ' '.join(out);
print('\n');
# ----------------------- #
# --- Section 5 Bigram--- #
# ----------------------- #
b = Chain();
b.learn_bi(tokens);
print('Bigram Build: \n')
print(b.my_markov(amount=100) + '\n');
# ------------------------ #
# --- Section 6 Trigram--- #
# ------------------------ #
t = Chain();
t.learn_tri(tokens);
print('Trigram Build: \n');
print(t.my_markov(amount=100) + '\n');
# ------------------------- #
# --- Section 7 Quadgram--- #
# ------------------------- #
qua = Chain();
qua.learn_quad(tokens);
print('Quadgram Build: \n');
print(qua.my_markov(amount=100) + '\n');
# ------------------------- #
# --- Section 8 Quingram--- #
# ------------------------- #
qui = Chain();
qui.learn_quin(tokens);
print('Quingram Build: \n');
print(qui.my_markov(amount=100) + '\n');
# ------------------------- #
# --- Section 8 Hexagram--- #
# ------------------------- #
hexa = Chain();
hexa.learn_hexa(tokens);
print('Hexagram Build: \n');
print(hexa.my_markov(amount=100) + '\n');
# ------------------------- #
# --- Section 9 Septagram--- #
# ------------------------- #
septa = Chain();
septa.learn_septa(tokens);
print('Septagram Build: \n');
print(septa.my_markov(amount=100) + '\n');
# ------------------------- #
# --- Section 10 Octagram--- #
# ------------------------- #
octa = Chain();
octa.learn_octa(tokens);
print('Octagram Build: \n');
print(octa.my_markov(amount=100) + '\n');
# ------------------------- #
# --- Section 11 Nonagram--- #
# ------------------------- #
nona = Chain();
nona.learn_nona(tokens);
print('Nonagram Build: \n');
print(nona.my_markov(amount=100) + '\n');
if __name__ == "__main__":
try:
arg1 = sys.argv[1];
except IndexError:
print "Usage: wphilli2_ngram.py <arg1>";
print "Please enter a path to the corpus file to analyze"
sys.exit(1);
# start the program
p0(arg1);
|
95036998e279c645f6124122ae2373a96e18dbaf | AbhiniveshP/Design-4 | /TwitterDesign.py | 4,683 | 4.28125 | 4 | '''
Solution:
1. In order to design Twitter, we need a global timestamp, HashMap to map users to tweets, Hashmap to map users to
their followers.
2. Just to avoid null checks, we call isFirstTime() method to initialize user's info if not present already.
Time and Space Complexities are explained are in each functionality separately
Extra Global Space: O((users * tweets) + (users * followers))
where tweets is maximum number of tweets a particular user has,
where followers is maximum number of followers a particular user has.
--- Passed all testcases successfully on Leetcode
'''
class Tweet:
def __init__(self, tweetId, timeStamp):
self.tweetId = tweetId
self.timeStamp = timeStamp
class Twitter_1:
def __init__(self):
"""
Initialize your data structure here.
"""
# global timestamp, HashMap to map users to tweets, Hashmap to map users to their followers.
self.timeStamp = 0
self.userTweetsMap = {}
self.userFollowsMap = {}
self.maxFeeds = 10
def __isFirstTime(self, userId: int) -> None:
# initialize user's info if not present already
# Time Complexity: O(1)
# Space Complexity: O(1)
if (userId not in self.userTweetsMap):
self.userTweetsMap[userId] = []
if (userId not in self.userFollowsMap):
self.userFollowsMap[userId] = set()
self.userFollowsMap[userId].add(userId)
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
# Time Complexity: O(1)
# Space Complexity: O(1)
self.__isFirstTime(userId) # check user exists
tweet = Tweet(tweetId, self.timeStamp) # create Tweet object
self.userTweetsMap[userId].append(tweet) # append the Tweet object to corresponding userId
self.timeStamp += 1 # update the timestamp
def getNewsFeed(self, userId: int) -> List[int]:
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
"""
# Time Complexity: O(NlogN) -> N is total tweets user and its followers have
# Space Complexity: O(N) -> N is total tweets user and its followers have
# custom less than function for Tweet class object
lessThan = lambda x, y: x.timeStamp < y.timeStamp
Tweet.__lt__ = lessThan
self.__isFirstTime(userId) # check user exists
tweetsList = []
# add all tweets of user's and its follower's
for followerId in self.userFollowsMap[userId]:
self.__isFirstTime(followerId)
tweetsList.extend(self.userTweetsMap[followerId])
tweetsList.sort(reverse=True) # sort the entire list according to timestamp in descending order
tweetIds = []
# put only first 10 feeds
for i in range(self.maxFeeds):
if i < len(tweetsList):
tweetIds.append(tweetsList[i].tweetId)
return tweetIds # return the top 10
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
# Time Complexity: O(1)
# Space Complexity: O(1)
self.__isFirstTime(followerId) # check follower exists
self.__isFirstTime(followeeId) # check followee exists
self.userFollowsMap[followerId].add(followeeId) # add to the follower's list
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
# Time Complexity: O(1)
# Space Complexity: O(1)
self.__isFirstTime(followerId) # check follower exists
self.__isFirstTime(followeeId) # check followee exists
if (followerId != followeeId):
self.userFollowsMap[followerId].discard(followeeId) # remove from the follower's list if not same
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId) |
e3a2bac0b37fe0c1e7349a55f2c77127f6c45b97 | apexfelix/strings | /strigs/modulous.py | 273 | 3.53125 | 4 | s="the croods"
s1="redemption"
print(len(s))
print(len(s1))
x=20
y=75
print("the sum of %d and %d is %d" %(x, y, x+y))
x=20.33
y=75.76
print("the sum of %0.2f and %0.2f is %0.2f" %(x, y, x+y))
x="The "
y="Croods"
print("the sum of %s and %s is %s" %(x, y, x+y)) |
b7c260023e072cbb7b8c71c62ffcb2cd8d748a76 | saisahanar/python-letsupgrade- | /DAY 7 ASSIGNMENT/q1.py | 376 | 3.78125 | 4 | # Use the dictionary,
# port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"},
# and make a new dictionary in which keys become values and values become keys,
# as shown: Port2 = {“FTP":21, "SSH":22, “telnet":23,"http": 80}
port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"}
port2={}
for key,values in port1.items():
port2[values]=key
print(port2) |
b250b1be20c5989d7594f3bbaec28b3c0f6b9c71 | sbrick26/OOP-Design-Challenge | /run.py | 3,266 | 3.6875 | 4 | class Person():
def __init__(self, firstname, lastname):
self.__firstname = firstname
self.__lastname = lastname
def changeName(self, firstname, lastname):
self.__firstname = firstname
self.__lastname = lastname
def returnName(self):
return self.__firstname + " " + self.__lastname
def myInfo(self):
print(self.__firstname + " " + self.__lastname)
class Customer(Person):
def __init__(self, firstname, lastname, orderAmount, orderName):
Person.__init__(self, firstname, lastname)
self.order = Order(orderAmount, orderName)
self.receivedOrder = False
def orderDone(self):
self.receivedOrder = True
def getOrder(self):
return self.order.item
def getAmount(self):
return self.order.amount
def hasReceived(self):
return self.receivedOrder
def myInfo(self):
print(self.returnName())
print("Item: " + self.getOrder())
print("Order Total: " + str(self.getAmount()))
class Order():
def __init__(self, amount, item):
self.amount = amount
self.item = item
def orderInfo(self):
return self.item + ": " + self.amount
def changeItem(self, index):
self.amount = prices[index - 1]
self.item = menu[index - 1]
class Driver(Person):
def __init__(self, firstname, lastname, customer):
Person.__init__(self, firstname, lastname)
self.customer = customer
def delievered(self):
self.customer.orderDone()
def check(self):
print("Delivery Successful: " + str(self.customer.hasReceived()))
def myInfo(self):
print("Driver Info")
print(self.returnName())
print("Customer Info")
self.customer.myInfo()
menu = ["1: Apple Pie", "2: Banana Pie", "3: Mango Pie"]
prices = [10.75, 15.45, 12.42]
check = input("Would you like to put in a delivery order? (y/n): ")
while check == "y":
firstname = input("What is the customer's first name? ")
lastname = input("What is the customer's last name? ")
print()
for item in menu:
print(item)
print()
order = int(input("What is the order number (1-3)? "))
currentCustomer = Customer(firstname, lastname, prices[order-1], menu[order-1])
print()
print("Here is the current customer info: ")
currentCustomer.myInfo()
print()
checkName = input("Is this the correct info? (y/n): ")
if checkName == "n":
firstname = input("What is the customer's first name? ")
lastname = input("What is the customer's last name? ")
currentCustomer.changeName(firstname, lastname)
print()
print("Here is the current customer info: ")
currentCustomer.myInfo()
print("Assigning Driver...")
currentDriver = Driver("Swayam", "Barik", currentCustomer)
print()
currentDriver.myInfo()
driverCheck = "n"
print()
while driverCheck != "y":
driverCheck = input("Has the item been delievered? (y/n): ")
print()
currentDriver.delievered()
currentDriver.check()
print()
check = input("Would you like to put in another delivery order? (y/n): ")
|
edb2d3e1a9f09ce94933b8b223af17dda52143a3 | SunshinePalahang/Assignment-5 | /prog2.py | 327 | 4.15625 | 4 | def min_of_3():
a = int(input("First number: "))
b = int(input("Second number: "))
c = int(input("Third number: "))
if a < b and a < c:
min = a
elif b < a and b < c:
min = b
else:
min = c
return min
minimum = min_of_3()
print(f"The lowest of the 3 numbers is {minimum}") |
a451dc45989107a390e8ac7345d08d24e5566c79 | raghedisae/DEVUTC503_02 | /ex4/Fraction.py | 1,954 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 20 21:12:48 2019
@author: raghed
"""
class Fraction:
'''num: numerateur
denom: denomominateur '''
def __init__(self, n, d):
self.num = int(n)
self.denom=int(d)
if self.denom <0:
self.denom = abs(self.denom)
self.num = -1* self.num
elif self.denom==0:
raise ZeroDivisionError
def decompose(self,n):
res=[]
i=2
while n>1:
while n%i==0:
res += [i]
n=n/i
i=i+1
return res
def __str__(self):
if self.denom==1:
return str(self.num)
else:
return '%s/%s' %(self.num,self.denom)
def __add__(self,other):
if self.denom == other.denom:
self.num = self.num+other.num
#self.num,self.denom
#self.simplifie()
else:
self.num*other.denom + other.num*self.denom,self.denom*other.denom
self.simplifie()
def __mul__(self,other):
self.num*other.num,self.denom*other.denom
self.simplifie()
def simplifie(self):
nums=self.decompose(self.num)
denoms=self.decompose(self.denom)
#print (nums,denoms)
if(nums==denoms):
return "1"
else:
for i in nums:
if i in denoms:
self.num=int(self.num/i)
self.denom=int(self.denom/i)
if __name__ == '__main__':
f1 = Fraction(12,6)
f2 = Fraction(5,6)
f3=f1+f2
f4=f1*f2
#print ()
print (f3)
print (f4) |
e735aec8a13110f611c3e7e1b5b79ebf8529dd64 | Harrison97/CTCI | /ch2/2.4.py | 1,448 | 3.546875 | 4 | import doctest
import LinkedList
LinkedList = LinkedList.SinglyLinkedList
# TC: O(n)
# SC: O(n)
# Bad implemintation
# Could be a little better if we kept trak of front oly nd appended to front of lists.
def partition(ll: LinkedList, x: int) -> LinkedList:
"""
Time: O(n)
Space: O(n)
>>> partition(LinkedList(1, 2, 3, 5, 24, 2 ,567, 3, 45, 0), 20)
[1, 2, 3, 5, 2, 3, 0, 24, 567, 45]
>>> partition(LinkedList(1, 2, 10, 5, 1, 0, 8, 12, 4), 5)
[1, 2, 1, 0, 4, 10, 5, 8, 12]
"""
curr = ll.head
ll_low = None
ll_high = None
last_low = None
last_high = None
while curr:
if curr.val >= x:
if not ll_high:
ll_high = LinkedList.Node(curr.val)
last_high = ll_high
else:
last_high.next = LinkedList.Node(curr.val)
last_high = last_high.next
else:
if not ll_low:
ll_low = LinkedList.Node(curr.val)
last_low = ll_low
else:
last_low.next = LinkedList.Node(curr.val)
last_low = last_low.next
curr = curr.next
partitioned = None
if last_low:
last_low.next = ll_high
partitioned = ll_low
else:
partitioned = ll_high
curr = partitioned
ans = []
while curr:
ans.append(curr.val)
curr = curr.next
return LinkedList(ans)
doctest.testmod()
|
f063169ec81c0e989da04e0e108bb3d776d5cca2 | Harrison97/CTCI | /ch1/1.1.py | 657 | 3.53125 | 4 | import unittest
chars = 128
def has_unique_chars(s: str) -> bool:
memo = chars*[0]
for c in s:
memo[ord(c) % chars] += 1
if memo[ord(c) % chars] > 1:
return False
return True
class Test(unittest.TestCase):
def test_1(self):
self.assertEqual(has_unique_chars('aAsSdDcCvVbBNnMmKkL'), True)
def test_2(self):
self.assertEqual(has_unique_chars('adasf'), False)
def test_3(self):
self.assertEqual(has_unique_chars('1!2#4$dDfFcCvG()'), True)
def test_4(self):
self.assertEqual(has_unique_chars('1!2#4$dDfFcCvG())'), False)
if __name__ == '__main__':
unittest.main()
|
29089e890e62fe8459c2f79a42d715de180fa9c9 | Harrison97/CTCI | /ch2/2.7.py | 2,842 | 3.953125 | 4 | import doctest
import LinkedList
LinkedList = LinkedList.SinglyLinkedList
def intersects(ll1: LinkedList, ll2: LinkedList) -> bool:
"""
Time: O(n)
Space: O(1)
>>> n = LinkedList.Node(99)
>>> ll1 = LinkedList(1, 2, 3)
>>> ll1.append_node_to_tail(n)
>>> ll1.append_to_tail(6)
>>> ll2 = LinkedList(1)
>>> ll2.append_node_to_tail(n)
>>> ll2.append_to_tail(6)
>>> ll2.append_to_tail(0)
>>> intersects(ll1, ll2)
True
>>> n = LinkedList.Node(0)
>>> ll1 = LinkedList(1)
>>> ll1.append_node_to_tail(n)
>>> ll2 = LinkedList(1)
>>> ll2.append_node_to_tail(n)
>>> intersects(ll1, ll2)
True
>>> intersects(LinkedList(1, 2, 3, 4, 5, 4, 3), LinkedList(4, 3, 5, 4, 3, 4, 3))
False
"""
curr1 = ll1.head
curr2 = ll2.head
reverse(curr1)
while curr2.next:
curr2 = curr2.next
if curr1 is curr2:
return True
return False
def intersects_2(ll1: LinkedList, ll2: LinkedList) -> bool:
"""
Time: O(n)
Space: O(1)
>>> n1 = LinkedList.Node(99)
>>> n2 = LinkedList.Node(1)
>>> n3 = LinkedList.Node(4)
>>> n4 = LinkedList.Node(6)
>>> ll1 = LinkedList(1, 2, 3)
>>> ll2 = LinkedList(1)
>>> ll1.append_node_to_tail(n1)
>>> ll1.append_node_to_tail(n2)
>>> ll1.append_node_to_tail(n3)
>>> ll1.append_node_to_tail(n4)
>>> ll2.append_node_to_tail(n1)
>>> intersects_2(ll1, ll2)
99
>>> n1 = LinkedList.Node(99)
>>> n2 = LinkedList.Node(1)
>>> ll1 = LinkedList(1, 2, 3)
>>> ll2 = LinkedList(1, 2, 3, 5, 1, 2, 3, 4, 2, 3, 1)
>>> ll1.append_node_to_tail(n1)
>>> ll1.append_node_to_tail(n2)
>>> ll2.append_node_to_tail(n1)
>>> intersects_2(ll1, ll2)
99
>>> intersects_2(LinkedList(1, 2, 3, 4, 5, 4, 3), LinkedList(4, 3, 5, 4, 3, 4, 3))
"""
curr1 = ll1.head
curr2 = ll2.head
length_1 = 1
length_2 = 1
while curr1.next:
curr1 = curr1.next
length_1 += 1
while curr2.next:
curr2 = curr2.next
length_2 += 1
if curr1 is not curr2:
return None
curr1 = ll1.head
curr2 = ll2.head
if length_1 > length_2:
while length_1 != length_2:
length_1 -= 1
curr1 = curr1.next
elif length_1 < length_2:
while length_1 != length_2:
length_2 -= 1
curr2 = curr2.next
while curr1 is not curr2:
curr1 = curr1.next
curr2 = curr2.next
return curr1.val
def reverse(n: LinkedList.Node) -> LinkedList.Node:
if not n.next:
return n
curr = n
temp1 = curr.next
temp2 = temp1.next
curr.next = None
while temp2:
temp1.next = curr
curr = temp1
temp1 = temp2
temp2 = temp2.next
temp1.next = curr
return temp1
doctest.testmod()
|
270175c897da53c2d3a5f40cafb6adf099bcf017 | vijaysundar2701/python | /be44.py | 85 | 3.546875 | 4 | h=list(range(1,10))
k=int(input())
if k in h:
print("yes")
else:
print("no")
|
7324a5f182521b9a9a0def5c0dc152ce48f7b017 | vijaysundar2701/python | /begi54.py | 56 | 3.546875 | 4 | z=int(input())
if z%2==0:
print(z)
else:
print(z-1)
|
dc40d3454436f0ca1f099fe2ba723f3222a1a5ce | vijaysundar2701/python | /vowrcos.py | 156 | 3.8125 | 4 | v=input()
vow=['a','e','i','o','u','A','E','I','O','U']
if v in vow:
print("Vowel")
elif v.isalpha():
print("Consonant")
else:
print("invalid")
|
604839fd7f7448acd7a87baa5d3a64726280c6ff | vijaysundar2701/python | /beg60.py | 61 | 3.59375 | 4 | a=int(input())
s=1
for i in range(2,a+1):
s=s+i
print(s)
|
3e545854b563b3a1166c7a36dead61b5274ae521 | jlewis2112/CPTS-481 | /HW2/concord | 1,617 | 3.5625 | 4 | #! /usr/bin/env python3
"""
Joseph Lewis
concord script
"""
import sys
import concordance as C
fileNames = sys.argv[1:]
wordStructure = {}
#used to store word and locations
# {word: [(filename,[lines]),(filename,[lines])}
#scans the word structure and prints the results sorted
def printWords(words):
for word in words:
occurences = 0
printer = ""
theWord = word[0]
repeatlines = {} #{linenumber: number of times on line}
for stream in sorted(word[1]):
printer += "\t" + stream[0] + ": "
for lineNumber in stream[1]:
occurences = occurences + 1
if lineNumber in repeatlines:
repeatlines[lineNumber] += 1
else:
repeatlines[lineNumber] = 1
for liner in repeatlines:
if repeatlines[liner] != 1:
printer = printer + str(liner) +"("+str(repeatlines[liner])+")"+", "
else:
printer = printer + str(liner) + ", "
printer = printer[:-2] + "\n"
repeatlines = {}
print(theWord, " (", occurences, "): ", sep = "")
print(printer)
#reads all of the files and adds entries into wordStructure
for file in fileNames:
f = open(file, "r");
concord = C.concordance(f, False)
for word in concord:
if word in wordStructure:
wordStructure[word].append((file,concord[word]))
else:
wordStructure[word] = [(file,concord[word])]
f.close()
wordStructure = sorted(wordStructure.items())
printWords(wordStructure)
|
47a0395d5d99612355328a92bf8f2bcf7bebc2c1 | freemanwang/AlgorithmJS | /Sort/QuickSort.py | 1,987 | 3.71875 | 4 | # coding=utf-8
import random
def quickSort(arr, left, right):
if len(arr) <= 1:
return arr
if left < right:
idx = getPivotIndex(arr, left, right)
quickSort(arr, left, idx-1)
quickSort(arr, idx+1, right)
def getPivotIndex(arr, left, right):
# temp 记录分隔元素
temp = arr[left]
while left < right:
while left < right and arr[right] >= temp:
right -= 1
# 退出循环即出现比 temp 小的,将其放到左边
arr[left] = arr[right]
while left < right and arr[left] <= temp:
left += 1
arr[right] = arr[left]
# 退出循环时left=right,即此处为temp的最终位置
arr[left] = temp
# 返回分隔下标
return left
arr = [2, 5, 3, 13, 8, 6]
quickSort(arr, 0, len(arr)-1)
print(arr)
def randomQuickSort(arr, left, right):
if not arr or len(arr) <= 1:
return
idx = getRandomPivotIndex(arr, left, right)
if idx > left:
randomQuickSort(arr, left, idx-1)
if idx < right:
randomQuickSort(arr, idx+1, right)
def getRandomPivotIndex(arr, left, right):
# temp 记录分隔元素
idx = getRandomIndex(left, right)
swap(arr, left, idx)
temp = arr[left]
while left < right:
while left < right and arr[right] >= temp:
right -= 1
# 退出循环即出现比 temp 小的,将其放到左边
arr[left] = arr[right]
while left < right and arr[left] <= temp:
left += 1
arr[right] = arr[left]
# 退出循环时left=right,即此处为temp的最终位置
arr[left] = temp
# 返回分隔下标
return left
def getRandomIndex(left, right):
return random.randint(left, right) # 生成 left <= N <= right 的随机数
def swap(arr, x, y):
arr[x], arr[y] = arr[y], arr[x]
arr = [2, 5, 3, 13, 8, 6]
randomQuickSort(arr, 0, len(arr)-1)
print(arr)
# quickSort(arr, 0, len(arr)-1)
# print(arr) |
f34219d1ee2ef0268506e136f341cd3f0485d77b | jideedu/DictAutomate | /dicts/cleanDicts.py | 741 | 3.84375 | 4 | ######
#this file takes disctionaries [american-english, british-english] and removes those entries
#that have stopwords, apostrophes or start with capital letters
######
#input dictionary files
inputDicts = ['american-english', 'british-english']
def checkCharacter(c, string):
return c in string
def checkCapitalLetter(string):
return string[0].isupper()
for dict in inputDicts:
outputDict = open(dict+"_clean","w")
openedFile = open(dict, "r")
for line in openedFile:
#print('{} contains {}? {}'.format(line, '\'', checkCharacter('\'', line)))
#print('{} startsWithCapital? {}'.format(line, checkCapitalLetter(line)))
if( not(checkCharacter('\'', line) | checkCapitalLetter(line)) ):
outputDict.write(line)
|
6ba14ff2c930aec459f6a12008d3a853817a1b51 | canw1993/CodeChallenges | /Fibonacci.py | 1,464 | 3.84375 | 4 | # Author: Can Wang, Bowen Deng
# Generate a random Fibonacci number smaller than equal to n (n>0) in O(log(n)) time
import math
import random
def matrix_power(mat, n):
# compute mat^n, mat is a square matrix
N = len(mat)
if n == 0:
zeros = [[0. for _ in range(N)] for _ in range(N)]
for i in range(N):
zeros[i][i] = 1.
return zeros
else:
# compute mat^{[n/2]}
sub_result = matrix_power(mat, int(n/2))
# multiply sub_result
result = [[0. for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
for k in range(N):
result[i][j] += sub_result[i][k] * sub_result[k][j]
# if n is odd, multiply sub_result by mat
if n%2 == 0:
return result
rtn = [[0. for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
for k in range(N):
rtn[i][j] += result[i][k] * mat[k][j]
return rtn
def fib(n):
# give the n-the fibonacci number
mat_pow = matrix_power([[0,1],[1,1]], n)
return mat_pow[0][1]
def GiveRandFibNum(n):
while True:
if n > 2:
m = random.randint(1, min(n, 10+int(5*math.log2(n*5))))
fib_m = fib(m)
if fib_m <= n:
return fib_m
else:
return 1
print(GiveRandFibNum(6))
|
266b83e77c6042daade94de6edbd4e5d362943b2 | chasejwang/lpthw | /ex36.py | 545 | 3.59375 | 4 | from sys import exit
def start():
print "You are a fog prince with a golden key and a sword."
print "You ride into the dark forest"
print "Finding out two ways: a cave and a road to Glory riverside."
print "Which way you would to go, my prince?"
choice = raw_input(" >")
if "cave" in choice:
case()
elif "riverside" in choice:
Glory_riverside()
else:
shame("You lost interest moving forward. On the road, you find a fat princess, \nyou two fall in love with each other.")
|
aa99be7f1e3a51d2d5c0281516a3ef443c4fc0c0 | chasejwang/lpthw | /pr1.py | 375 | 3.515625 | 4 | x = "life can be difference, ppl can live in %d, %d, or %d ways" % (1, 2, 3)
creative= "creative"
will_not = "won't"
y = "so you should be %s, but you %s be pretend to be" % (creative, will_not)
print x
print y
w = "bitch, bitch, and bitches \n"
k = "cunt, cunt , and cunts"
print w + k
f = "you never know what happened next"
print " just what matters with you, %r" % f
|
06b05625e0bdb938587a1ce2df230f3e2ee40277 | PaxMax1/School-Work | /a116_buggy_image_pg_version_5-21.py | 639 | 3.75 | 4 | # a116_buggy_image.py
import turtle as trtl
# instead of a descriptive name of the turtle such as painter,
# a less useful variable name x is used
spider = trtl.Turtle()
spider.pensize(40)
spider.circle(20)
spider_legs = 6
spider_leg_length = 70
leg_angle = 380 / spider_legs
print("Leg Angle =", leg_angle)
spider.pensize(5)
number_of_legs= 0
while (number_of_legs < spider_legs):
spider.goto(0,0)
spider.setheading(leg_angle*number_of_legs)
spider.forward(spider_leg_length)
number_of_legs = number_of_legs + 1
print("Leg Angle*Number Of Legs=", leg_angle*number_of_legs)
spider.hideturtle()
wn = trtl.Screen()
wn.mainloop()
|
34a2bfbe98dfb42c1f3d2a8f444da8e49ca04639 | PaxMax1/School-Work | /fbi.py | 1,610 | 4.25 | 4 | # a322_electricity_trends.py
# This program uses the pandas module to load a 3-dimensional data sheet into a pandas DataFrame object
# Then it will use the matplotlib module to plot comparative line graphs
import matplotlib.pyplot as plt
import pandas as pd
# choose countries of interest
my_countries = ['United States', 'Zimbabwe','Cuba', 'Caribbean small states', "Cameroon", "Burundi"]
# Load in the data with read_csv()
df = pd.read_csv("elec_access_data.csv", header=0) # header=0 means there is a header in row 0
# get a list unique countries
unique_countries = df['Entity'].unique()
# Plot the data on a line graph
for c in unique_countries:
if c in my_countries:
# match country to one of our we want to look at and get a list of years
years = df[df['Entity'] == c]['Year']
# match country to one of our we want to look at and get a list of electriciy values
sum_elec = df[df['Entity'] == c]['Access']
plt.plot(years, sum_elec, label=c,)
plt.ylabel('Percentage of Country Population')
plt.xlabel('Year')
plt.title('Percent of Population with Access to Electricity')
plt.legend()
plt.show()
# CQ1- A countrys access to electricity can affect its access to computing innovations because computers require electricity and power to opperate.
# If you don't have electricity to run a computer, than you can't use your computer and have access to it's innovations.
# CQ2- Analyzing data like this can affect global change because we can see what countrys have issues in the world so that other countrys that are more advanced can help get them up on their feet.
|
1ab03f22da176b7d8502d563c100f3f0eec65387 | 1aaronscott/cs-sprint-challenge-hash-tables | /hashtables/ex4/ex4.py | 602 | 3.90625 | 4 | def has_negatives(a):
"""
YOUR CODE HERE
"""
# Your code here
# create empty list and join with "a" to make a dict
b = [0]*len(a)
cache = dict(zip(a, b))
result = []
for k in cache:
if k > 0: # for every positive key
# print(k)
try: # check to see if it's negative also exists
if cache[k] is not None and cache[-k] is not None:
result.append(k)
except:
pass
return result
if __name__ == "__main__":
print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
|
00e2d68e451511c443f96d1d27ac6e7820f4ab58 | GiovanaPalhares/python-introduction | /testes.py | 433 | 3.640625 | 4 | import re
texto = "joooooãooo, jooãooo e maria moravam na roça e então decidiram se mudar para cidade, pensaram em se mudar para São Paulo"
print(re.findall(r"[Jj]oão", texto))
print(re.findall(r"jOãO|MARIA", texto, flags=re.I))
# print(re.sub(r"jo+ão+", "felipe", texto, flags=re.I))
# print(re.sub(r"joão"))
print(re.findall(r"jO{2}ãO", texto, flags=re.I))
sentencas = re.split(r' ["d"]+', texto)
print(sentencas)
|
524773cbc9374ee413f4e99d9ca0fff324ffe044 | GiovanaPalhares/python-introduction | /NIM.py | 350 | 3.96875 | 4 | print("Bem-vindo ao jogo do NIM! Escolha:")
print("1 - para jogar uma partida isolada ")
print("2 - para jogar um campeonato ")
escolha = int(input(" Escolha o tipo de jogo: "))
if "escolha" == 1:
print("você escolheu uma partida isolada")
if "escolha" == 2:
print("você escolheu um campeonato")
else:
print("opção inválida")
|
aa0e0d75269d67427d08f20fc9cdb8b376f850a0 | shohei-ojs/math- | /probability/otoku.py | 597 | 3.546875 | 4 | # coding: UTF-8
# 数字の書かれたカードを引いた時の期待値
# ①:カードの数字*100円
# ②:5が出た場合1000円
from numpy.random import *
CARDS = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
TOTAL = 100000
def draw():
return choice(CARDS)
def mean(l):
return sum(l) /TOTAL
def main():
a = mean([draw() * 100 for _ in range(TOTAL)])
b = mean([1000 if draw() == 5 else 0 for _ in range(TOTAL)])
print('1さんは%s円くらい' % a)
print('2さんは%s円くらい' % b)
if __name__ == '__main__':
main() |
4645c1449ee00c1b86c60d26f3e7abfd1cc6aef6 | rolundb/Labb1 | /Labb1.py | 4,263 | 3.703125 | 4 | import time
import os
from operator import attrgetter
# Reads from .txt-file and extracts relevant lines which becomes attributes for objects that are
#placed in an array.
#
#parameter1 a_filename Name of a txt-file.
# return: the_array_list List of objects created based on content of .txt file.
def readFile(a_filename):
with open(a_filename, "r", encoding="utf-8") as f:
the_array_list = []
the_reset = 0
i= the_reset
for line in f:
if line.strip() != "" and not line.startswith("#"):
i+=1
if i == 1:
name = line
elif i == 2:
description = line
elif i == 3:
latitude = line
elif i == 4:
longitude = line
elif i == 5:
date = line
the_array_list.append(Place(name, description, latitude, longitude, date))
i = the_reset
return the_array_list
# Matches the users input with object in list and runs the __str__-method for said object
#
# parameter1 an_intext User input that is matched with attribute "name" of objects in an_array.
# parameter2 an_array An array with objects.
# return: None
def findPlace(an_intext, an_array):
the_time_start = time.time()
for an_object in an_array:
if an_object.getName().lower() == an_intext.lower():
print(an_object)
the_time_end = time.time()
the_time_passed = the_time_end-the_time_start
print("Time for search:" + str(the_time_passed)+ " seconds.\n")
return
print("\n" + an_intext +" could not be found. Please restart the program to try again.\n\n")
os._exit(0)
# Sorts an array with objects for attribute "longitude" and runs the __str__ method for object with lowest number for "longitude".
#
# parameter1 an_arrray An array with objects that has the attribute "longitude".
# return: None
def southernPlace(an_array):
all_places_sorted = sorted(an_array, key=attrgetter('latitude'))
print("However, the most southern place is " + str(all_places_sorted[0]) + "If you want to search for another location, please restart the program.\n\n")
for i in range(10):
print(all_places_sorted[i])
class Place:
'''Creates a class with attributes; name, description, latitude, longitude, date'''
def __init__(self, name, description, latitude, longitude, date):
self.name = name.strip()
self.description = description.strip()
self.latitude = int(latitude.strip())
self.longitude = longitude.strip()
self.date = date.strip()
def __str__(self):
'''Returns a string of the name and description of the object'''
return str(self.name)+ ", often refferd to as " +str(self.description)
def getName(self):
'''Returns the name of the object'''
return self.name
def getDate(self):
'''Returns the longitude of the object'''
<<<<<<< Updated upstream
return int(self.longitude)
def getDate(self):
"""Returns the Date of the object"""
return int(self.date)
=======
<<<<<<< HEAD
return str(self.date)
def getLatitude(self):
'''Returns the description of the object'''
return int(self.latitude)
def __str__(self):
'''Returns a string of the name and description of the object'''
return self.getName()+ ", often refferd to as " +str(self.getLatitude())+ " during the time " + self.getDate() + ".\n"
=======
return int(self.longitude)
def getDate(self):
"""Returns the Date of the object"""
return int(self.date)
>>>>>>> FETCH_HEAD
>>>>>>> Stashed changes
def main():
all_places = readFile("geodataSW.txt")
intext = input("Welcome to Locator! \n You can search for a location and get information about it. As a bonus, we'll throw in the name of the most southern place. Type in a geografic location: ")
findPlace(intext, all_places)
southernPlace(all_places)
main()
|
de2bfbd8bab8b02f529178d3919de0bd49b6e8d1 | happy-bean/python-Demo | /src/com/wgt/lesson4/Class1.py | 8,994 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# Python 文件I/O
# 本章只讲述所有基本的的I/O函数,更多函数请参考Python标准文档。
#
# 打印到屏幕
# 最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式。此函数把你传递的表达式转换成一个字符串表达式,并将结果写到标准输出如下
print "Python 是一个非常棒的语言,不是吗?"
# 读取键盘输入
# Python提供了两个内置函数从标准输入读入一行文本,默认的标准输入是键盘。如下:
# raw_input
# input
# raw_input函数
# raw_input([prompt])
# 函数从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符):
str = raw_input("请输入:")
print "你输入的内容是: ", str
# input函数
# input([prompt]) 函数和 raw_input([prompt])函数基本类似,
# 但是input可以接收一个Python表达式作为输入,并将运算结果返回。
str = input("请输入:")
print "你输入的内容是: ", str
# 打开和关闭文件
# 现在,您已经可以向标准输入和输出进行读写。现在,来看看怎么读写实际的数据文件。
# Python 提供了必要的函数和方法进行默认情况下的文件基本操作。你可以用 file 对象做大部分的文件操作。
# open 函数
# 你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。
# 语法:
# file object = open(file_name [, access_mode][, buffering])
# 各个参数的细节如下:
# file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
# access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
# buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,
# 表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。
# 不同模式打开文件的完全列表:
# 模式 描述
# r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
# rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。
# r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
# rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。
# w 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
# wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
# w+ 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
# wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
# a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
# ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
# a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
# ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
# File对象的属性
# 一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。
# 以下是和file对象相关的所有属性的列表:
# 属性 描述
# file.closed 返回true如果文件已被关闭,否则返回false。
# file.mode 返回被打开文件的访问模式。
# file.name 返回文件的名称。
# file.softspace 如果用print输出后,必须跟一个空格符,则返回false。否则返回true。
# 打开一个文件
fo = open("foo.txt", "w")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace
# close()方法
# File 对象的 close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。
# 当一个文件对象的引用被重新指定给另一个文件时,Python 会关闭之前的文件。用 close()方法关闭文件是一个很好的习惯。
# 语法:
# fileObject.close()
# 读写文件:
# file对象提供了一系列方法,能让我们的文件访问更轻松。来看看如何使用read()和write()方法来读取和写入文件。
# write()方法
# write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
# write()方法不会在字符串的结尾添加换行符('\n'):
# 语法:
# fileObject.write(string)
# 打开一个文件
fo = open("foo.txt", "w")
fo.write("www.runoob.com!\nVery good site!\n")
# 关闭打开的文件
# fo.close()
#
# read()方法
# read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
# 语法:
# fileObject.read([count])
# 在这里,被传递的参数是要从已打开文件中读取的字节计数。该方法从文件的开头开始读入,
# 如果没有传入count,它会尝试尽可能多地读取更多的内容,很可能是直到文件的末尾。
# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10)
print "读取的字符串是 : ", str
# 关闭打开的文件
fo.close()
# 文件定位
# tell()方法告诉你文件内的当前位置, 换句话说,下一次的读写会发生在文件开头这么多字节之后。
# seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。
# 如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。
# 例子:
# 就用我们上面创建的文件foo.txt
# 查找当前位置
position = fo.tell()
print "当前文件位置 : ", position
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0)
str = fo.read(10)
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close()
# 重命名和删除文件
# Python的os模块提供了帮你执行文件处理操作的方法,比如重命名和删除文件。
# 要使用这个模块,你必须先导入它,然后才可以调用相关的各种功能。
# rename()方法:
# rename()方法需要两个参数,当前的文件名和新文件名。
# 语法:
# os.rename(current_file_name, new_file_name)
# 重命名文件test1.txt到test2.txt。
os.rename("test1.txt", "test2.txt")
#
# remove()方法
# 你可以用remove()方法删除文件,需要提供要删除的文件名作为参数。
# 语法:
# os.remove(file_name)
# 删除一个已经存在的文件test2.txt
os.remove("test2.txt")
# Python里的目录:
# 所有文件都包含在各个不同的目录下,不过Python也能轻松处理。os模块有许多方法能帮你创建,删除和更改目录。
# mkdir()方法
# 可以使用os模块的mkdir()方法在当前目录下创建新的目录们。你需要提供一个包含了要创建的目录名称的参数。
# 语法:
# os.mkdir("newdir")
# 创建目录test
os.mkdir("test")
# chdir()方法
# 可以用chdir()方法来改变当前的目录。chdir()方法需要的一个参数是你想设成当前目录的目录名称。
# 语法:
# os.chdir("newdir")
# 将当前目录改为"/home/newdir"
os.chdir("/home/newdir")
# getcwd()方法:
# getcwd()方法显示当前的工作目录。
# 语法:
# os.getcwd()
# 给出当前的目录
print os.getcwd()
# rmdir()方法
# rmdir()方法删除目录,目录名称以参数传递。
# 在删除这个目录之前,它的所有内容应该先被清除。
# 语法:
# os.rmdir('dirname')
# 删除”/tmp/test”目录
os.rmdir( "/tmp/test" ) |
15a5b9e912cd614e9a6cec8c3140a4f254655616 | longlvt/CS50X | /pset6/mario.py | 435 | 3.859375 | 4 | from cs50 import get_int
height = ''
# print(type(height))
# while (height < 1 or height > 8):
# height = get_int("Height: ")
while (height.strip().isdigit() == False or (height.strip().isdigit() == True and (int(height) < 1 or int(height) > 8))):
height = input("Height: ")
for i in range(1, int(height) + 1):
print(" " * (int(height) - i), end="")
print("#" * i, end="")
print(" " * 2, end="")
print("#" * i) |
0eb00f4a770263ea840143cc72a99cd402475dda | ashishjain1988/PythonTest | /com/example/python/test.py | 522 | 3.578125 | 4 | import numpy as ny
import os as os
#s = "uxwrpxlwocnimr";
s="axabc";
count = True;
lstring = "";
length = len(s)
for i in range(0,length):
count = True;
for j in range(i+1,length):
if(s[j-1] > s[j]):
subStr = s[i:j];
if(len(subStr) > len(lstring)):
lstring = subStr;
count = False;
break;
if count:
if len(s[i:length]) > len(lstring):
lstring = s[i:length];
print "Longest substring in alphabetical order is:",lstring; |
3e33624375f413e3d632999e29e71522d0bd2292 | wael-hub/untitled | /if + else+ else if statment.pyif + else+ else if statement.py | 694 | 3.828125 | 4 | username = input(" plase insert your name: ")
password = input(" plase insert your password: ")
if username == 'bohen' and password == 'ffff':
print("welcome to your emaile")
else:
print ('error')
z = 15
y = 10
if (z < y):
print (z)
w = z + y
print (w)
elif(z > y):
print('iam bohen')
w = z - y
print(w)
else:
(x = y)
day = 1
if ( day == 1):
print('Sun')
elif( day == 2):
print('Mon')
elif(day == 3):
print('Tues')
elif(day == 4):
print('Wed')
elif(day == 5):
print( 'Thurs')
elif(day == 6):
print('Fri')
elif(day == 7):
print('Sat')
else:
print('nothing')
|
b983c7c3384fcf521ea6ca79d262e73d3967678e | wael-hub/untitled | /Oop create class and object.py | 186 | 3.515625 | 4 | class car:
speed = 0
color = 'none'
def increment(self):
print('increment')
def decrement(self):
print ('decrement')
BMW = car()
camry = car()
|
d0daa9b74955010179caea96c694e8faab0b3c2d | wael-hub/untitled | /indexed.py | 439 | 3.703125 | 4 | word = 'bohen'
print (word)
print (word[0])
print (word[1])
print (word[2])
print (word[3])
print (word[4])
print (word[-1])
print (word[-2])
print (word[-3])
print (word[-4])
print (word[-5])
print (word[:])
print (word[3:])
print (word[3:])
print (word[0:3])
word = 'bohen', 'bird' , 10 , 20 , 3.5 ,'python', 'mohamad'
print(word)
print (word[0])
print (word[:])
print (word[:4])
print (word[2:5])
|
586d76bd89db756c9add468c98d0b5b6e59091e5 | wael-hub/untitled | /Leen and Upper.py | 236 | 3.71875 | 4 | name = 'Wael Mohamad'
res = name.replace('Wael Mohamad', 'Ward')
print(res)
name = 'Wael Mohamad'
res = name.find('M')
print(res)
name = 'Wael Mohamad'
res = name.__len__()
print(res)
name = 'Wael Mohamad'
res = name.upper()
print(res)
|
c275468117aa43e59ac27afd391e463d0983a979 | gevishahari/mesmerised-world | /integersopr.py | 230 | 4.125 | 4 | x=int(input("enter the value of x"))
y=int(input("enter the value of y"))
if(x>y):
print("x is the largest number")
if(y>x):
print("y is the largest number")
if (x==y):
print("x is equal to y")
print("they are equal") |
c4314c1090df0a7dba6613ea8ddda0f3dd433235 | gcorbin/archive-computational-experiments | /experimentarchiver/__init__.py | 1,255 | 3.609375 | 4 | class Version:
def __init__(self, major=0, minor=0):
if not isinstance(major, int) or not isinstance(minor, int):
raise TypeError('Major and minor version numbers must be integers.')
self._version_tuple = (major, minor)
def major(self):
return self._version_tuple[0]
def minor(self):
return self._version_tuple[1]
def is_release(self):
return self.minor() == 0
def __le__(self, other):
if not isinstance(other, Version):
raise TypeError('Comparing a Version with another object is not supported.')
# use lexicographic ordering of tuples:
return self._version_tuple <= other._version_tuple
def __ge__(self, other):
return other.__le__(self)
def __eq__(self, other):
return self.__le__(other) and other.__le__(self)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.__le__(other) and not other.__le__(self)
def __gt__(self, other):
return other.__lt__(self)
def __str__(self):
return "{0}.{1}".format(self.major(), self.minor())
def get_version_tuple(self):
return self._version_tuple
version = Version(1, 1)
|
bb0ad1ce4f81a23b500ce5b86d92a0fc70241fc4 | loafer18/numBomb | /elifTest.py | 814 | 3.953125 | 4 | import random
numList = list(range(1,101))
#print (numList)
numBomb = random.choice(numList)
print(numBomb)
while True:
try:
#num= float(input("input a number pls."))
number1 = input("Please select a number between 1 and 100:")
number1 = int(number1)
print(number1)
if number1 == numBomb:
print("Congratulations, you picked the BOMB! YOU LOOSE!!!")
elif number1 < numBomb:
#print("input number is positive")
numList = list(range(number1,101))
print(numList)
else:
#print("input number is negative")
numList = list(range(1,number1))
print (numList)
break
except ValueError:
print("input is invalid, please reenter.")
|
cf2193408564c9b3467abc19d590769c7f6f25c2 | jmptiamzon/study-python | /files.py | 2,950 | 3.625 | 4 | import os
os.path.join('folder1', 'folder2', 'folder3', 'file.png') #will join based on OS
os.sep #will show OS separator
os.getcwd() #current working directory, default is python folder
os.chdir('c:\\') #change directory
os.getcwd() #will show c:\\
os.path.abspath('spam.png') #will return current dir, which is c:\\ + spam.png
os.path.abspath('..\\..\spam.png') #will return 2 folders above
os.path.isabs('..\\..\\spam.png') #False
os.path.relpath('c:\\folder1\\folder2\\spam.png', 'c:\\folder1') #parameter 2 is the current dir
#will return folder2\\spam.png
os.path.dirname('c:\\folder1\\folder2\\spam.png') #will return c:\\folder1\\folder2
os.path.basename('c:\\folder1\\folder2') #will return folder2
os.path.exists('c:\\windows\\system32\\calc.exe') #True
os.path.isdir('c:\\windows\\system32') #True
os.path.getsize('c:\\windows\\system32\\calc.exe')
#listdir shows all files inside the said dir
for filename in os.listdir('c:\\documents'):
if not os.path.isfile(os.path.join('c:\\documents', filename)):
continue
totalSize = totalSize + os.path.getsize(os.path.join('c:\\documents', filename))
#shows totalSize of files inside the dir
os.makedirs('c:\\documents\\yes123') #will create a folder
#open files
helloFile = open('c:\\documents\sample.txt')
content = helloFile.read()
print(content) #will return how you see it in text file | 1 string
helloFile.close() # once you close, you need to open again
helloFile.open('c:\\documents\sample.txt')
helloFile.readlines() #this will return array with separator of new line
#write files
helloFile = open('c:\\documents\\hello2.txt', 'w') #parameter 2 (w), means write, if we use this, it will rewrite the entire txt file
helloFile.write('Hello!')
helloFile.write('Hello!')
helloFile.write('Hello!')
#this is only in one line, without new lines
hello.close()
#append
baconFile = open('c:\\documents\\hello2.txt', 'a')
baconFile.write('\nYes!')
baconFile.close()
#shelve
import shelve #shelve is like session or cookie, this saves a file on your current dir
shelfFile = shelve.open('mydata')
shelfFile['cats'] = ['a', 'b', 'c']
shelfFile.close()
shelfFile = shelve.open('mydata')
shelfFile['cats'] #will return the array at the top
#advantages of this is, you can use this data saved on this anytime since it is written on your harddrive
#copy files / moving
import shutil
shutil.copy('c:\\documents\\test1.txt', 'c:\\documents\\yes123') #will copy file to second param
shutil.copytree('c:\\documents\\yes123', 'c:\\documents\\newfol') #will copy entire folder
shutil.move('c:\\documents\\yes123\\test1.txt', 'c:\\documents\\newfol') #will move to new folder
shutil.move('c:\\documents\\newfol\\test1.txt', 'c:\\documents\\newfol\\test2.txt') #rename file
#deleting files
import os
os.getcwd()
os.unlink('filename.ext') #delete single file in current working directory
|
2fb6397026f25ef532c90ca5e1bf7b3539ee3495 | alinyara/course-ud303 | /newsdb.py | 1,852 | 3.5 | 4 | import psycopg2
from datetime import date
DBNAME = "news"
# Its necessary to create 2 different views in order to make the query results
# Question 1 and 2
def createview1():
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("create view question1_table as select name, title, path from (select name, title, slug from articles join authors on articles.author = authors.id) as newtable join log on log.path like concat('%', newtable.slug);")
db.close()
# View for Question 3
def createview2():
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("create view logerror as select date(time) as date, count(*) as total, sum(case when status != '200 OK' then 1 else 0 end) as lista from log group by date(time) order by lista;")
db.close()
def get_three_popular():
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("select title, count(*) as num from question1_table group by title order by num desc limit 3;")
data = c.fetchall()
db.close()
return data
print "What are the three most popular articles of all time?"
print get_three_popular();
def get_most_popular():
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("select name, count(*) as num from question1_table group by name order by num desc limit 3;")
data = c.fetchall()
db.close()
return data
print "Who are the most popular article authors of all time?"
print get_most_popular();
def day_errors():
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("select date, cast (lista as float)/cast (total as float) as perc from logerror group by date, perc order by perc DESC limit 1;")
data = c.fetchall()
db.close()
return data
print "Which days did more than 1% of requests lead to errors?"
print day_errors();
|
d76dfe561f9111effed1b82da602bf6df98f2405 | AdmireKhulumo/Caroline | /stack.py | 2,278 | 4.15625 | 4 | # a manual implementation of a stack using a list
# specifically used for strings
from typing import List
class Stack:
# initialise list to hold items
def __init__(self):
# initialise stack variable
self.stack: List[str] = []
# define a property for the stack -- works as a getter
@property
def stack(self) -> List[str]:
return self._stack
# define a setter for the property
@stack.setter
def stack(self, new_stack: List[str]) -> None:
# ensure proper format
if isinstance(new_stack, List):
# assign private stack wit new value
self._stack = new_stack
else:
# improper input, deny and raise an error
raise ValueError("Must be a list of strings, i.e List[str]")
# push method adds to top of stack
def push(self, item: str) -> None:
if type(item) == str:
self.stack.append(item)
else:
raise ValueError("Must supply a string")
# pop method removes from top of stack
def pop(self) -> str:
# get top item
item: str = self.stack[-1]
# delete top item
del self.stack[-1]
# return top item
return item
# peek method retrieves the item at the top of the stack without removing it
def peek(self) -> str:
return self.stack[-1]
# size returns the number of elements in the stack
def size(self) -> int:
return len(self.stack)
# check if the stack is empty
def is_empty(self) -> bool:
return len(self.stack) == 0
# reverse method
def reverse(self) -> None:
# create a new stack
new_stack: Stack = Stack()
# iterate through current stack and push to new stack
while not self.is_empty():
new_stack.push(self.stack.pop())
# assign new_stack to old_stack
self.stack = new_stack.stack
# dunder methods -- kinda unnecessary here to be honest
# len works the same as size() above
def __len__(self) -> int:
return len(self.stack)
# repr returns a string representation of the stack
def __repr__(self) -> str:
string: str = ''
for item in self.stack:
str += item
return string
|
25240f3e1f3cc702921cca1587df8e57d3adf570 | Muhammad-waqar-uit/HashTable-Own-Implementation- | /Chaining Collision( Hash Table).py | 2,091 | 3.875 | 4 | class HashTable:
def __init__(self,length):
self.length=length#Length of the hashtable
self.data=[[] for i in range(self.length)]#HashMap as an array for Hashing values
def Get_Array(self):#getting the whole hashmap array
return self.data
def __Get_Hash(self,key):#Hashing using key to find the index on the hashmap
Hash_key=0#hashkey to be find
for i in key:
Hash_key+=ord(i)
return Hash_key%self.length#finding hash according to array size
def Get_Item(self,key):#searching using key on hashmap
Hash=self.__Get_Hash(key)#finding location using hash
Get=[]#storing all elements having same key
for i in self.data[Hash]:#itterating to find the element
if i[0]==key:#checking condition for matching key
Get.append(i[1])#append in the get list
return Get#getting the list as output
def Set_Item(self,key,value):#putting value using hash function on the basis of key in the hashmap
Hash=self.__Get_Hash(key)
flag=False
for k,v in enumerate(self.data[Hash]):#itterating through whole hash
if len(v)==1 and v[0]==key:
self.data[Hash][k]=(key,value)#putting both keys and values on the hashmap
flag=True
if not flag:#flag for checking if the value hash location is found or not
self.data[Hash].append((key,value))
def Del_Item(self,key):#deleting values on hashmap using
Hash=self.__Get_Hash(key)
for i in range(len(self.data[Hash])):
k, v = self.data[Hash][i]#Hashmap index point
if k == key:
self.data[Hash][i] = 'del'#after deleting keeping the del value to indicate that value has been deleted
return v#returning the value that has been deleted
obj=HashTable(10)
obj.Set_Item("84","Muhammad_Waqar")
obj.Get_Array()
obj.Set_Item("116","Muneeb_Mirza")
obj.Get_Array()
obj.Get_Item("116")
obj.Del_Item("116")
obj.Get_Array()
|
177bdc4ce61be25d10a3b6bda220fd7c93210777 | EcaterinaSchita/Siruri-de-caractere | /problema8.py | 567 | 3.765625 | 4 | s=str(input('Introdu sirul dorit:'))
a=s.count(('A'))
print('Numarul de aparitii a caracetrului A',a)
print('Sirul obtinut prin substiruirea caracterului A in *' )
s1=list(s)
s1.remove('B')
s1= ''.join(s1)
print('Sirul obţinut prin radierea din şirul S a tuturor apariţiilor caracterului ’B’:', s1)
print('Numărul de apariţii ale silabei MA în şirul S:', s.count('MA'))
print('Sirul obţinut prin substituirea tuturor apariţiilor în şirul S a silabei MA prin silaba TA:', s.replace('MA','TA'))
print('Scrierea inversă a şirului S:', s[::-1]) |
8b7da9557874db581b38432a28b41f9058e9dadf | cpelaezp/IA | /1. Python/ejemplos/3.projects/1.contactos/contactoBook.py | 831 | 4.15625 | 4 | class Contacto:
def __init__(self, name, phone, email):
self._name = name
self._phone = name
self._email = email
class ContactoBook:
def __init__(self):
self._contactos = []
def add(self):
name = str(input("Ingrese el nombre: "))
phone = str(input("Ingrese el telefono: "))
email = str(input("Ingrese el email: "))
contacto = Contacto(name, phone, email)
self._contactos.append(contacto)
print('name: {}, phone: {}, email: {}'.format(name, phone, email))
def showAll(self):
for contacto in self._contactos:
_print_contato(contacto)
def _print_contato(self, _contacto):
print('name: {}, phone: {}, email: {}'.format(_contacto.name, _contacto.phone, _contacto.email))
|
63a30ff68c69f15b62bb59bfbb3b68cffc59c697 | paul-ivan/genetic_project | /vector.py | 702 | 3.8125 | 4 | #!/usr/bin/env python
import math
def dist(p1, p2):
return math.hypot(p2[1] - p1[1], p2[0] - p1[0])
class Vector:
def __init__(self, p1, p2):
self.x = p2[0] - p1[0]
self.y = p2[1] - p1[1]
def compare(self, v2):
return Vector(self.x, self.y, v2.x, v2.y)
def show(self):
print (str(self.x) + ", " + str(self.y))
def norme(self):
pass;
def angle(self, v2):
a = (math.atan2(v2.y, v2.x) - math.atan2(self.y, self.x)) * 180 / math.pi
if (a > 180):
a -= 360
if (a < -180):
a += 360
return a
'''
v = Vector([0, 0], [0, 0])
p = Vector([0, 0], [1, 0])
print (p.angle(v))
'''
|
a650c4d0cb7bcc4a95037519046efce47d0e7dc8 | abhatt95/LeetCode | /Medium/350.py | 692 | 3.640625 | 4 | """
Given two arrays, write a function to compute their intersection.
"""
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
index1 = 0
index2 = 0
output = []
while index1 < len(nums1) and index2 < len(nums2):
if nums1[index1] == nums2[index2]:
output.append(nums1[index1])
index1 += 1
index2 += 1
continue
if nums1[index1] < nums2[index2]:
index1 += 1
else:
index2 += 1
return output
|
d5b520af7a8ff1e7c7c5fbdd8c6d0169e7265731 | abhatt95/LeetCode | /Medium/743.py | 1,136 | 3.671875 | 4 | """
There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.
"""
import heapq
from collections import defaultdict
class Solution:
def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
graph = collections.defaultdict(list)
for s,d,c in times:
graph[s].append((d,c))
queue = [(0,K)]
covered_nodes = {}
while queue:
c,d = heapq.heappop(queue)
if d in covered_nodes: continue
covered_nodes[d] = c
for neighbour,c_e in graph[d]:
if neighbour not in covered_nodes:
heapq.heappush(queue,(c+c_e,neighbour))
return max(covered_nodes.values()) if len(covered_nodes) == N else -1
|
205837a1e1191374562287c9eff0b4ce9bf7a5b4 | abhatt95/LeetCode | /Medium/55.py | 843 | 3.640625 | 4 | """
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
https://leetcode.com/problems/jump-game/
"""
class Solution:
def canJump(self, nums: List[int]) -> bool:
indexOfZero = []
for i,x in enumerate(nums[:len(nums)-1]):
if x == 0:
indexOfZero.append(i)
for index in indexOfZero:
crossed = False
for i,x in enumerate(nums[0:index]):
print(x > index - i)
if x > index - i:
crossed = True
if not crossed:
return False
return True
|
71021e7cf21f47c13df7be87afe4e169eb945ab5 | jessicazhuofanzh/Jessica-Zhuofan--Zhang | /assignment1.py | 1,535 | 4.21875 | 4 | #assignment 1
myComputer = {
"brand": "Apple",
"color": "Grey",
"size": 15.4,
"language": "English"
}
print(myComputer)
myBag = {
"color": "Black",
"brand": "MM6",
"bagWidth": 22,
"bagHeight": 42
}
print(myBag)
myApartment = {
"location": "New York City",
"type": "studio",
"floor": 10,
"color": "white and wood"
}
print(myApartment)
myBreakfast = {
"cost": "5 dollars",
"drink": "pink drink",
"food": "egg and bacon",
"calorie": 500
}
print(myBreakfast)["food"]
#assignment 2
{
"name": "amy",
"location": "garden",
"genus": "flower",
"species": "rose",
"count": 5,
"spined": False
}
#assignment 3
print ("Welcome to New York City")
print ("Answer the questions below to create your story in NYC")
print ("-------------------------")
adjective1 = raw_input("Enter an adjective: ")
color1 = raw_input("What is your favorite color?: ")
country1 = raw_input("Which country you come from?: ")
number1 = raw_input("Enter any number between 1-100: ")
place1 = raw_input("Enter your favorite area in NYC: ")
person1 = raw_input("Enter your favorite movie star: ")
person2 = raw_input("Enter your favorite singer: ")
story = " I arrived New York City on a" + adjective1 + "day," \
"carrying a" + color1 + "suitcase which I bought in" + country1 + "." \
"It will take" + number1 + "minutes to my apartment, " \
"which located in" + place1 + "." \
"I fount out that" + person1 + "and" + person2 + "is my neighbor. " \
print(story)
|
e724a913db3ddec93e12d1b422ec3b65b9015565 | gsy/leetcode | /design_hashset.py | 986 | 3.765625 | 4 | # -*- coding: utf-8 -*-
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.buckets = [None] * 10
def add(self, key):
while len(self.buckets) <= key:
self.buckets = self.buckets + [None] * len(self.buckets)
self.buckets[key] = key
def remove(self, key: int) -> None:
if key < len(self.buckets):
self.buckets[key] = None
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
if key < len(self.buckets):
return self.buckets[key] is not None
return False
if __name__ == "__main__":
obj = MyHashSet()
obj.add(1)
obj.add(2)
r = obj.contains(1)
assert r is True
r = obj.contains(3)
assert r is False
obj.add(2)
r = obj.contains(2)
assert r is True
obj.remove(2)
r = obj.contains(2)
assert r is False
|
85ed57e4097c51af6ad3e628bd274e4ec4509fa1 | gsy/leetcode | /path_sum.py | 3,056 | 3.53125 | 4 | __author__ = 'guang'
from bst import TreeNode
class Solution(object):
def is_leaf(self, node):
return node and node.left is None and node.right is None
def path_sum(self, node):
"""
>>> s = Solution()
>>> s.path_sum(None)
(0, -2147483648)
>>> s.path_sum(TreeNode(2))
(2, 2)
>>> s.path_sum(TreeNode(-2))
(-2, -2)
>>> tree = TreeNode(None).from_string("1,2,3")
>>> s.path_sum(tree.left)
(2, 2)
>>> s.path_sum(tree.right)
(3, 3)
>>> tree = TreeNode(None).from_string("5,1,-10,2,3,-5,-6")
>>> s.path_sum(tree.left)
(4, 6)
>>> s.path_sum(tree.right)
(-10, -5)
>>> tree = TreeNode(None).from_string("-10,-5,-6,-3,-7,-8,-9")
>>> s.path_sum(tree)
(-10, -3)
>>> tree = TreeNode(None).from_string("-2,-1")
>>> s.path_sum(tree)
(-2, -1)
>>> tree = TreeNode(None).from_string("5,4,8,11,#,13,4,7,2,#,#,#,1")
>>> s.path_sum(tree.left)
(22, 22)
>>> s.path_sum(tree.right)
(21, 26)
>>> tree = TreeNode(None).from_string("7,-2000,#,500,#,1500,2000")
>>> s.path_sum(tree.left.left)
(2500, 4000)
"""
if self.is_leaf(node):
return node.val, node.val
if node is None:
return 0, -2147483648
left, sub1 = self.path_sum(node.left)
right, sub2 = self.path_sum(node.right)
left = left if left > 0 else 0
right = right if right > 0 else 0
if left > right:
maximum_path = node.val + left
else:
maximum_path = node.val + right
sub_result = max(max(sub1, sub2), node.val + left + right)
return maximum_path, sub_result
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
>>> s = Solution()
>>> s.maxPathSum(None)
0
>>> s.maxPathSum(TreeNode(2))
2
>>> s.maxPathSum(TreeNode(-2))
-2
>>> s.maxPathSum(TreeNode(None).from_string("2,-1"))
2
>>> s.maxPathSum(TreeNode(None).from_string("1,2,#"))
3
>>> s.maxPathSum(TreeNode(None).from_string("1,2,3"))
6
>>> s.maxPathSum(TreeNode(None).from_string("5,1,-10,2,3,-5,-6"))
9
>>> s.maxPathSum(TreeNode(None).from_string("5,4,8,11,#,13,4,7,2,#,#,#,1"))
48
>>> s.maxPathSum(TreeNode(None).from_string("-10,-5,-6,-3,-7,-8,-9"))
-3
>>> s.maxPathSum(TreeNode(None).from_string("-5,7,#,8,9"))
24
>>> tree = TreeNode(None).from_string("7,-2000,#,500,#,1500,2000")
>>> s.maxPathSum(tree)
4000
"""
if root is None:
return 0
left, left_max = self.path_sum(root.left)
right, right_max = self.path_sum(root.right)
left = left if left > 0 else 0
right = right if right > 0 else 0
return max(root.val + left + right, max(left_max, right_max))
|
fab592507bc207929192d4fdc5902a7c5567f4cc | gsy/leetcode | /linklist/removeDuplicateNodes.py | 619 | 3.6875 | 4 | #!/usr/bin/env python3
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
seen = set()
sentinel = ListNode(0)
sentinel.next = head
prev = sentinel
node = prev.next
while node:
if node.val in seen:
prev.next = node.next
node = prev.next
continue
else:
seen.add(node.val)
prev = prev.next
node = prev.next
return sentinel.next
|
0cfafbcde85537dd0e3b5af7e74779e3cf975681 | gsy/leetcode | /binarytree/numUniqueEmails.py | 553 | 3.625 | 4 | class Solution:
def convert(self, email):
localname, domain = email.split("@")
name = ""
for char in localname:
if char == '.':
continue
elif char == '+':
break
else:
name = name + char
return name + "@" + domain
def numUniqueEmails(self, emails):
result = set()
for email in emails:
address = self.convert(email)
print(address)
result.add(address)
return len(result)
|
33e32c81c4fea430a10d15206e4b4cfc17b13618 | gsy/leetcode | /preorder_traversal.py | 985 | 3.734375 | 4 | from bst import TreeNode
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
>>> s = Solution()
>>> root = TreeNode(None).from_string("1,2,3")
>>> s.preorderTraversal(root)
[1, 2, 3]
>>> root = TreeNode(None).from_string("1,2")
>>> s.preorderTraversal(root)
[1, 2]
>>> root = TreeNode(None).from_string("1,#,3")
>>> s.preorderTraversal(root)
[1, 3]
>>> root = TreeNode(None).from_string("1,2,3,4,5,6,7")
>>> s.preorderTraversal(root)
[1, 2, 4, 5, 3, 6, 7]
"""
if root is None:
return []
result = []
path = [root]
while path:
node = path.pop(-1)
if node.right:
path.append(node.right)
if node.left:
path.append(node.left)
result.append(node.val)
return result
|
c30d7af1efe131fade73d0279f926064ec1aba23 | gsy/leetcode | /generate_parenthese2.py | 655 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class Solution:
def generateParenthesis(self, n):
if n == 1:
return ["()"]
elif n == 2:
return ["()()", "(())"]
else:
result = set()
for parenthesis in self.generateParenthesis(n-1):
result.add("({})".format(parenthesis))
result.add("(){}".format(parenthesis))
result.add("{}()".format(parenthesis))
return list(result)
if __name__ == '__main__':
s = Solution()
r = s.generateParenthesis(3)
print(r)
r = s.generateParenthesis(4)
print(r, len(r))
assert len(r) == 14
|
2299604747cc781fa3025e710db75be29cadf1bb | gsy/leetcode | /valid_palindrome.py | 987 | 3.609375 | 4 | __author__ = 'guang'
class Solution(object):
def palindrome(self, s):
"""
:param s:
:return:
>>> s = Solution()
>>> s.palindrome("A")
True
>>> s.palindrome("")
True
"""
if len(s) == 0:
return True
i, j = 0, len(s) - 1
while i < j:
if not s[i] == s[j]:
return False
else:
i += 1
j -= 1
return True
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
>>> s = Solution()
>>> s.isPalindrome("A man, a plan, a canal: Panama")
True
>>> s.isPalindrome("race a car")
False
>>> s.isPalindrome("")
True
>>> s.isPalindrome("0P")
False
"""
words = []
for c in s:
if c.isalnum():
words.append(c.lower())
return self.palindrome(words)
|
9fdbeee26ef114f7dd7f7a0ee424c7949ad3e4de | gsy/leetcode | /linklist/copyRandomList.py | 1,369 | 3.6875 | 4 | #!/usr/bin/env python3
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def indexof(self, head, node):
current = head
index = 0
while current:
if current == node:
return index
else:
current = current.next
index += 1
def get(self, head, index):
current = head
for i in range(index):
current = current.next
return current
def copyRandomList(self, head):
if head is None:
return None
copy = Node(0)
node, prev = head, copy
while node:
newNode = Node(node.val, None, None)
prev.next = newNode
prev = newNode
node = node.next
node, prev = head, copy
while node:
current = prev.next
if node.random is None:
current.random = None
elif node.random == node:
current.random = current
else:
index = self.indexof(head, node.random)
current.random = self.get(copy.next, index)
node = node.next
prev = current
return copy.next
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.