blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
d12abc250671e0de9f9a0e2eda5c64f364a77968 | Veena-Wanjari/My_Programs | /multiplication_table.py | 449 | 4.1875 | 4 | user_number = input("Enter a number: ")
while (not user_number.isdigit()) or (int(user_number) < 1) or (int(user_number) > 12):
print("Must be an integer between 1 to 12")
user_number = input("Enter a number: \n")
user_number = int(user_number)
print("====================")
print(f"This is the multiplication table for {user_number}")
print()
for i in range(1,13):
print(f" {user_number} x {i} = {user_number * i} ")
print()
|
7407571d242fbbce0ee8acbff83e8335fe6cbd28 | ravipatel0113/My_work_in_Bootcamp | /Class Work/3rd Week_Python/1st Session/04-Stu_DownToInput/Unsolved/DownToInput.py | 491 | 4.125 | 4 | # Take input of you and your neighbor
name = input("What is your name?")
ne_name = input("What is the neighbor name?")
# Take how long each of you have been coding
Time_code = int(input("How long have you been coding?"))
netime_code = int(input("How long your neighbour " +ne_name+" have been coding?"))
# Add total month
sum = Time_code+netime_code
# Print results
print(f"your name is {name} and my neighbour name is {ne_name}")
print("Total month coded together " +str(sum) + " months!") |
404d29d59fde6207d08f07a77969c53336626d67 | ravipatel0113/My_work_in_Bootcamp | /Home Work/Python Assignment-03/Instructions/PyBank/main.py | 4,488 | 3.8125 | 4 | # First we will import the .csv file to the script..
import csv
#import the os of running the code on all the operating system
import os
'''max_v =[]
min_v =[]'''
#Read the csv file for the location into the script
csvpath = os.path.join('Resources','budget_data.csv')
with open(csvpath) as csvfile: # for total month count using aa list
csvreader = csv.reader(csvfile)
#For printing the object of the csv.reader file use below code.....
#print(csvreader)
csv_header= next(csvreader) # For skiping the header name of the file....
#If you want to print the header of the sheets below is the code....
#print(f'csv header: {csv_header}')
#For the total analysis printing part.....
print("Final Analysis")
print("---------------------------------------------------------")
row = list(csvfile)
#total = sum(csvfile)
print(f'Total Months: {len(row)}') #Print the total months in the output...
with open(csvpath) as csvfile: #for total profit/losses without list method
csvreader = csv.reader(csvfile)
total = 0
csv_header= next(csvreader) #Skipping the header row or the first row of the .csv file....
total = sum(int(row[1]) for row in csvreader) # For summing the Total Profit/Losses...
print(f'Total Profit/Losses is: $ {total}') # Print the Total Profit/Losses...
with open(csvpath) as csvfile: #for getting the change in profit/losses and average..
#define variables
rowcount = 0
first_value = 0
next_value = 0
average = 0
great_increase =0
great_month = 0
great_decrease = 0
low_month = 0
change = 0
total_change = 0
csvreader =csv.reader(csvfile)
csv_header = next(csvreader)
for row in csvreader:
rowcount += 1 #count row another method
#max_v.append (float(row[1])) #To list the maximun value of the Profit/losses column
#min_v.append (float(row[1])) # To list the minimum value of the Profit/losses column
if first_value == 0: #For taking the first value of column..
first_value = int(row[1])
else:
next_value = int(row[1]) #select the next value in the column..
change = next_value - first_value #Get the change in Profit/Losses for a period of a month
total_change = change + total_change #Get the total change in Profit/Losses for the entire data.
if great_increase < change: #Check for the greatest increase in Profit..
great_month = row[0] #Get the month of the Greatest Profit..
great_increase = change # Save the greatest change into a variable..
if great_decrease > change: #Check for the greatest loss..
low_month = row[0] #Get the month with greatest loss..
great_decrease = change #Save the greatest loss into a variable...
first_value = next_value #Check if the first value and next value are same stop the loop..
print(f'The Total Change in Profit is: $ {total_change}') #Print the Total change..
#print(change)
average = round(total_change/(rowcount-1),2) #Get the average of the Total Profit/Losses..
print(f'The average change is: $ {average}') #Print the average change..
print (f'The Greatest increase in Profit: {great_month} , $ ({great_increase})') #Print the greatest profit along with its month..
print(f'The Greatest decrease in Profit: {low_month}, $ ({great_decrease})') #Print the greatest loss along with its month..
'''print(f'The Maximun Profit/Losses {max(max_v)}')
print(f'The Minimum Profit/Losses {min(min_v)}')''' #Extra Work for Minimum and MAximum Values form the PRofit/Losses Column..
# For Printing the output into the text file..
output_path = os.path.join('Analysis','PyBank_Result.txt')
with open(output_path, 'w', newline='') as txtfile:
txtfile.write("Final Analysis \n")
txtfile.write("--------------------------------------------------------- \n")
txtfile.write(f'Total Months: {rowcount} \n')
txtfile.write(f'Total Profit/Losses is: $ {total} \n')
txtfile.write(f'The Total Change in Profit is: $ {total_change} \n')
txtfile.write(f'The average change is: $ {average} \n')
txtfile.write(f'The Greatest increase in Profit: {great_month} , $ ({great_increase}) \n')
txtfile.write(f'The Greatest decrease in Profit: {low_month}, $ ({great_decrease}) \n')
|
97d79fa185b7bf5702ac6350d9d187cc067180d8 | Andriiiiiiii/Python | /Черепаха_2/1.py | 353 | 3.546875 | 4 | import numpy as np
import random
import math
import turtle as t
i=0
x=0
y=0
while i < 2000:
x += random.randint(-30, 30)
y += random.randint(-30, 30)
t.goto(x,y)
i+=1
if (x > 200 or x < -200):
t.goto(0,0)
x=0
y=0
if (y > 200 or y < -200):
t.goto(0,0)
x=0
y=0
|
597023e28d4b38161e6a5fad504c54278e1389d6 | johnarley2007/UPB | /PYTHON/SumaDosNumeros.py | 1,725 | 4.125 | 4 | print ("Bienvenido al programa inicial, que calcula la suma de dos números.")
print ("********************************************************************")
a=input ("Por favor escriba el primer número: ")
b=input ("Por favor escriba el segundo número: ")
a1=int(a)
b1=int(b)
resultado=a1+b1
print ("Esta es la suma de los números ingresados: ",resultado)
#***********************************************************************"
print ("Bienvenido al programa inicial, que calcula la suma de dos números.")
print ("********************************************************************")
a=int(input ("Por favor escriba el primer número: "))#Int se utiliza para enteros
b=int(input ("Por favor escriba el segundo número: "))
resultado=a+b
print ("Esta es la suma de los números ingresados: ",resultado)
#***********************************************************************"
print ("Bienvenido al programa inicial, que calcula la suma de dos números.")
print ("********************************************************************")
a=float(input ("Por favor escriba el primer número: "))#Float se utiliza para décimal
b=float(input ("Por favor escriba el segundo número: "))
resultado=a+b
print ("Esta es la suma de los números ingresados: ",resultado)
#***********************************************************************"
print ("Bienvenido al programa inicial, que calcula la suma de dos números.")
print ("********************************************************************")
a=str(input ("Por favor escriba el primer número: "))#Float se utiliza para décimal
b=str(input ("Por favor escriba el segundo número: "))
resultado=a+b
print ("Esta es la suma de los números ingresados: ",resultado) |
f6997d2845f5921984156e90b331e6ab255f2610 | johnarley2007/UPB | /PYTHON/RETO 4/reto4.py | 14,892 | 3.765625 | 4 | from os import system
import os
import time
import random
from math import asin,cos,sin,sqrt,radians,degrees
system("clear")
x = 51661
y = 16615
coordenada = []
listadistancias=[]
radio=6372.795477598
restauranteactual=None
distanciaparatiempo=None
listacoordenadaspredet=[[5.273,-76.579,390],
[5.311,-76.413,333],
[5.354,-76.204,240],
[5.306,-76.332,793]]
def ingresarCoordenada (coordenadaInicial):
coordenadaDuplicada = list(coordenadaInicial)
for x in range (0,3):
coordenadaDuplicada.append([])
lat = input("Ingrese la latitud: ")
while lat == "" or lat == " ":
print("Error")
exit()
lat = float(lat)
if lat <= 5.413 and lat >= 5.119:
lon = input("Ingrese la longitud: ")
while lon == "" or lon == " ":
print("Error")
exit()
lon = float(lon)
if lon <= -76.132 and lon >= -76.619:
coordenadaDuplicada[x].insert(0,lat)
coordenadaDuplicada[x].insert(1,lon)
else:
print("Error coordenada")
exit()
else:
print("Error coordenada")
exit()
print("Coordenadas ingresadas correctamente")
time.sleep(2)
return coordenadaDuplicada
def ordenarLatitudes(coordenadaInicial):
print(f"La coordenada que está mas al sur es: {min(coordenadaInicial, key=lambda posicion:posicion[0])}")
print(f"La coordenada que está mas al norte es: {max(coordenadaInicial, key=lambda posicion:posicion[0])}")
def ordenarLongitudes(coordenadaInicial):
print(f"La coordenada que está mas al oriente es: {max(coordenadaInicial, key=lambda posicion:posicion[1])}")
print(f"La coordenada que está mas al occidente es: {min(coordenadaInicial, key=lambda posicion:posicion[1])}")
def promedioCoordenadas(coordenadaInicial):
print(f"El promedio de las latitudes es: {(coordenadaInicial[0][0]+coordenadaInicial[1][0]+coordenadaInicial[2][0])/3}")
return
print(f"El promedio de las longitudes es: {(coordenadaInicial[0][0]+coordenadaInicial[0][1]+coordenadaInicial[0][2])/3}")
def imprimirCoordenada(coordenadaInicial):
coordenadaDuplicada=list(coordenadaInicial)
print("Las coordenadas guardadas actualmente son:")
for x in range(0,len(coordenadaDuplicada)):
print(f"{x+1}. Coordenada Latitud:'{coordenadaDuplicada[x][0]}' Longitud: ' {coordenadaDuplicada[x][1]}'")
ordenarLatitudes(coordenadaDuplicada)
ordenarLongitudes(coordenadaDuplicada)
promedioCoordenadas(coordenadaDuplicada)
choice=int(input("Por favor ingrese la opción que desea modificar"))
if choice!=1 and choice!=2 and choice!=3:
print("Error actualización")
exit()
else:
actualizarCoordenadas(choice,coordenadaInicial)
def actualizarCoordenadas(choice, coordenadaInicial):
coordenadaDuplicada = list(coordenadaInicial)
choice=choice-1
lat = input("Ingrese la latitud: ")
while lat == "" or lat == " ":
print("Error")
exit()
lat = float(lat)
if lat <= 5.413 and lat >= 5.119:
lon = input("Ingrese la longitud: ")
while lon == "" or lon == " ":
print("Error")
exit()
lon = float(lon)
if lon <= -76.132 and lon >= -76.619:
coordenadaDuplicada[choice][0]=lat
coordenadaDuplicada[choice][1]=lon
else:
print("Longitud fuera del rango")
coordenadaDuplicada=[coordenadaInicial] #En caso de error retornamos la lista original (sin cambios)
return coordenadaDuplicada
else:
print("Latitud fuera del rango")
coordenadaDuplicada=[coordenadaInicial]
return coordenadaDuplicada
return coordenadaDuplicada #En caso éxito retornamos la nueva lista
#RETO4
def MostrarRestaurantesFav(coordenadaInicial):
if coordenadaInicial==[]:
print("Error sin registro de coordenadas")
exit()
else:
ImprimirRestauratesFav(coordenadaInicial)
def ImprimirRestauratesFav(coordenadaInicial):
coordenadaDuplicada = list(coordenadaInicial)
print("Las coordenadas guardadas actualmente son: ")
for x in range(0,len(coordenadaDuplicada)):
print(f"{x+1}. Coordenada Latitud:'{coordenadaDuplicada[x][0]}' Longitud: ' {coordenadaDuplicada[x][1]}'")
opcion=int(input("Por favor seleccione su restaurante actual: "))
if opcion == 1 or opcion ==2 or opcion ==3:
global restauranteactual
restauranteactual=coordenada[opcion-1]
PrepararDatos(opcion,coordenadaDuplicada,listacoordenadaspredet)
else:
print("Error ubicación")
exit()
def PrepararDatos(IndRestauranteactual,coordenadaInicial,coordenadasfijas):
coordenadaDuplicada=list(coordenadaInicial)
listaduplicadafijas=list(coordenadasfijas)
lat1=coordenadaDuplicada[IndRestauranteactual-1][0]
lon1=coordenadaDuplicada[IndRestauranteactual-1][1]
lat1=convertiraRadianes(lat1)
lon1=convertiraRadianes(lon1)
for x in range(0,len(listaduplicadafijas)):
for y in range (0,2):
listaduplicadafijas[x][y]=convertiraRadianes(listaduplicadafijas[x][y])
AplicarFormulaDistancia(lat1,lon1,listaduplicadafijas)
pass
def convertiraRadianes(valoraconvertir):
return radians(valoraconvertir)
pass
def AplicarFormulaDistancia(lat1, lon1, listaenradianes):
for x in range(0,4):
lat2=listaenradianes[x][0]
lon2=listaenradianes[x][1]
latdelta=lat2-lat1
londelta=lon2-lon1
auxiliarcalculo=sin(londelta/2)**2
auxiliarcalculo=auxiliarcalculo*(cos(lat1)*cos(lat2))
auxiliarcalculo=(sin(latdelta/2)**2)+auxiliarcalculo
auxiliarcalculo=sqrt(auxiliarcalculo)
auxiliarcalculo=asin(auxiliarcalculo)
auxiliarcalculo=(2*radio)*auxiliarcalculo
auxiliarcalculo=auxiliarcalculo*1000
auxiliarcalculo=round(auxiliarcalculo)
listadistancias.append(auxiliarcalculo)
OrdenarDistancias(listadistancias)
def OrdenarDistancias(distancias):
distanciasduplicadas=list(distancias)
min1=distanciasduplicadas.index(min(distanciasduplicadas))
distanciasduplicadas.pop(min1)
min2=distancias.index(min(distanciasduplicadas))
ImprimirMensajeCercanias(min1,min2,listacoordenadaspredet,distancias)
def ImprimirMensajeCercanias(min1,min2, basededatos,listadistancias ):
for x in range (0,4):
basededatos[x][0]=degrees(basededatos[x][0])
basededatos[x][1]=degrees(basededatos[x][1])
for x in range (0,len(listacoordenadaspredet)):
if listacoordenadaspredet[min1][0]==listacoordenadaspredet[x][0] and listacoordenadaspredet[min1][1] == listacoordenadaspredet[x][1]:
if listacoordenadaspredet[x][2]>listacoordenadaspredet[min1][2]:
min1=listacoordenadaspredet.index(listacoordenadaspredet[x])
global distanciaparatiempo
if basededatos[min1][2] > basededatos[min2][2]:
print(f"1. El restaurante más cercano está en la latitud: '{basededatos[min1][0]}' longitud: '{basededatos[min1][1]}', está a {listadistancias[min1]} metros, y tiene {basededatos[min1][2]} platos.")
print(f"2. El segundo restaurante más cercano está en la latitud: '{basededatos[min2][0]}' longitud: '{basededatos[min2][1]}', está a {listadistancias[min2]} metros, y tiene {basededatos[min2][2]} platos.")
opcdestino=int(input("Por favor seleccione el restaurante al cual desea ir, para recibir indicaciones: "))
if opcdestino==1:
distanciaparatiempo = listadistancias[min1]
DarIndicaciones(restauranteactual,basededatos[min1])
elif opcdestino==2:
distanciaparatiempo = listadistancias[min2]
DarIndicaciones(restauranteactual,basededatos[min2])
else:
print("Error zona wifi")
exit()
else:
print(f"1. El restaurante más cercano está en la latitud: '{basededatos[min2][0]}' longitud: '{basededatos[min2][1]}', está a {listadistancias[min2]} metros, y tiene {basededatos[min2][2]} platos.")
print(f"2. El segundo restaurante más cercano está en la latitud: '{basededatos[min1][0]}' longitud: '{basededatos[min1][1]}', está a {listadistancias[min1]} metros, y tiene {basededatos[min1][2]} platos.")
opcdestino=int(input("Por favor seleccione el restaurante al cual desea ir, para recibir indicaciones: "))
if opcdestino==1:
distanciaparatiempo= listadistancias[min2]
DarIndicaciones(restauranteactual,basededatos[min2])
elif opcdestino==2:
distanciaparatiempo= listadistancias[min1]
DarIndicaciones(restauranteactual,basededatos[min1])
else:
print("Error zona wifi")
exit()
def DarIndicaciones(restactual,restdestino):
latorigen=restactual[0]
lonorigen=restactual[1]
latdestino=restdestino[0]
londestino=restdestino[1]
if latorigen>latdestino:
txt1="el sur"
elif latorigen<latdestino:
txt1="el norte"
else:
txt1=""
if lonorigen>londestino:
txt2="el occidente"
elif lonorigen<londestino:
txt2="el oriente"
else:
txt2=""
if txt1=="" and txt2!="":
print(f"Debe ir hacia {txt2}")
elif txt2=="" and txt1!="":
print(f"Debe ir hacia {txt1}")
elif txt1=="" and txt2=="":
print("Usted ya está en el destino")
time.sleep(3)
else:
print(f"Debe dirigirse primero hacia {txt1} y luego hacia {txt2}")
time.sleep(2)
CalcularTiempoRecorrido()
def CalcularTiempoRecorrido():
tiempo1="segundos"
tiempo2="segundos"
if distanciaparatiempo==0:
pass
else:
auto=distanciaparatiempo/16.67
moto=distanciaparatiempo/0.483
if auto > 60:
auto=auto/60
tiempo1="minutos"
if moto > 60:
moto=moto/60
tiempo2="minutos"
moto=round(moto,2)
auto=round(auto,2)
print(f"Se tardará aproximadamente {auto} {tiempo1} en auto; y {moto} {tiempo2} en moto")
#Fin reto 4
print("Bienvenido al sistema de ubicación para zonas públicas WIFI”")
usuario = int(input("Digite el usuario: "))
if usuario == x:
system("clear")
contraseña = int(input("Digite la contraseña: "))
if contraseña == y:
system("clear")
termino1=661
termino2=(2*1)+5-1
captcha = str(print(termino1," + ",termino2,"=",))
valor=str(input())
if valor==str((termino1+termino2)):
system("clear")
print("Sesión iniciada")
menu = ["Cambiar contraseña", "Ingresar coordenadas actuales", "Ubicar zona wifi más cercana", "Guardar archivo con ubicación cercana", "Actualizar registros de zonas wifi desde archivo", "Elegir opción de menú favorita", "Cerrar sesión."]
cont = 0
while True:
if cont >= 3:
print ("Error")
exit()
for i in range(7):
print(str(i+1),". ",menu[i])
try:
opcion = int(input("Elija una opción"))
if opcion < 1 or opcion > 7:
print("Error")
cont += 1
elif opcion == 1:
claveAnterior = int(input("Digite la contraseña anterior: "))
if y != claveAnterior:
print("Error")
exit()
else:
nuevaClave = int(input("Digite la nueva contraseña: "))
while nuevaClave == y:
print("Error")
nuevaClave = int(input("Digite la nueva contraseña: "))
nuevaClave2 = int(input("Confirmar nueva contraseña: "))
if nuevaClave == nuevaClave2:
y = nuevaClave
print("Cambio de contraseña exitoso")
else:
print("Error")
elif opcion == 2:
if coordenada==[]:
coordenada = ingresarCoordenada(coordenada)
else:
imprimirCoordenada(coordenada)
elif opcion == 3:
MostrarRestaurantesFav(coordenada)
elif opcion == 6:
try:
favorita = int(input("Seleccione opción favorita"))
cont = 0
if favorita < 1 or favorita > 5:
print("Error")
exit()
else:
try:
digito1 = int(input("Cantidad esquinas de un triángulo: "))
if digito1 == 3:
digito2 = int(input("Cuantos lados tiene un cuadrado:"))
if digito2 == 4:
favorita -= 1
temporal = menu[favorita]
menu.pop(favorita)
menu.insert(0,temporal)
else:
print("Error")
else:
print("Error")
except ValueError:
print("Error")
except ValueError:
print("Error")
exit()
elif opcion >=1 and opcion <=5:
print ("Usted ha elegido la opción "+str(opcion)+"")
exit()
elif opcion == 7:
print("Hasta pronto")
exit()
except ValueError:
print("Error")
cont += 1
else:
system("clear")
print("Error")
else:
system("clear")
print("Error")
else:
system("clear")
print("Error") |
c387ab39222951cbb6e3067f8b5ccdce0104a55d | UWPCE-PythonCert/Py300 | /Examples/logging/example.py | 1,706 | 3.5625 | 4 | #!/usr/bin/env python3
"""
Example code for using logging in a complex system
"""
import sys
import logging
import random
import time
import worker
# The logging configuration:
# In real life, you might be pulling this from a config file, or ...
# each level of logging gives more information
# uncomment the level you want
# log_level = logging.CRITICAL
# log_level = logging.ERROR
# log_level = logging.WARNING
# log_level = logging.INFO
log_level = logging.DEBUG
# pretty simple format -- time stamp and the message
# this can get fancy:
# https://docs.python.org/3/library/logging.html#logrecord-attributes
format = '%(asctime)s %(levelname)s - %(module)8s - line:%(lineno)d - %(message)s'
# configure the logger
# basicConfig configures the "root logger" -- usually the one you want.
# this sets it up to write to a file
logging.basicConfig(filename='example.log',
filemode='a', # use 'a' if you want to preserve the old log file
format=format,
level=log_level)
# and this will make it write to stdout as well
# you would turn this off in production...
if True: # turn this off with False
std_handler = logging.StreamHandler(sys.stdout)
# give this a different formatter:
formatter = logging.Formatter('%(levelname)9s - %(module)s - %(message)s')
std_handler.setFormatter(formatter)
std_handler.setLevel(logging.DEBUG)
logging.getLogger().addHandler(std_handler)
# Run the "application":
while True: # keep it running "forever"
# do something random:
logging.debug("calling a random worker")
random.choice(worker.workers)()
# wait a random length of time :
time.sleep(random.random())
|
ba2882102f31acd7da5f9eea04d77bbb4acd7649 | UWPCE-PythonCert/Py300 | /Examples/testing/coverage/calculator.py | 643 | 3.984375 | 4 | #!/usr/bin/env python
"""calculator
Usage:
calculator.py 1 + 3
"""
import sys
import calculator_functions as functions
if len(sys.argv) != 4:
error_message = """
Invalid arguments.
Usage:
calculator.py 1 + 3
"""
sys.stderr.write(error_message + "\n")
sys.exit(-1)
x = sys.argv[1]
operator = sys.argv[2]
y = sys.argv[3]
if operator == "+":
print(functions.add(x, y))
elif operator == "-":
print(functions.subtract(x, y))
elif operator == "*":
print(functions.multiply(x, y))
elif operator == "/":
print(functions.divide(x, y))
else:
print("invalid input")
|
7514b28c0c4ea8c0af673674770d872e3b997b38 | UWPCE-PythonCert/Py300 | /Examples/sql/little_bobby_tables.py | 806 | 3.5 | 4 | #!/usr/bin/env python
# http://xkcd.com/327/
import sqlite3
DB_NAME = ":memory:"
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
create_query = 'CREATE TABLE Students(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)'
insert_query = 'INSERT INTO Students(name) VALUES (?)'
select_query = 'SELECT COUNT(*) FROM Students'
cursor.execute(create_query)
student_data = (
("Don",),
("Sally",),
("Robert');DROP TABLE Students;--",)
)
cursor.executemany(insert_query, student_data)
# now get pwned
bad_insert_query = """INSERT INTO Students(name) VALUES ('%s')"""
for name in student_data:
cursor.executescript(bad_insert_query % name)
print "DB contains %s rows" % cursor.execute(select_query).fetchone()[0]
|
22fc0bf0574183a12aa565e4a04a4ce249964db8 | UWPCE-PythonCert/Py300 | /Examples/advancedOO/shapes.py | 548 | 3.890625 | 4 | class Shape:
def __str__(self):
return "Shape:{}".format(self.__class__.__name__)
class Rectangle(Shape):
def __init__(self, width, height):
# validate inputs:
assert(width > 0)
assert(height > 0)
self.width = width
self.height = height
def area(self):
"""returns the area of this Rectangle"""
return self.width * self.height
class Square(Rectangle):
def __init__(self, length):
self.width = length
self.height = length
print(Square(10).area())
|
c6e6c20ea41c75cb758aea6233106b0c4026912e | UWPCE-PythonCert/Py300 | /Examples/debugging/long_loop.py | 479 | 3.796875 | 4 | # Exceptions and Debugging
# How would you step through this function to get to the exception
# You should not have to enter any command 777 or more times to get there. :-)
def long_loop():
for i in range(int(1e04)):
i+1
if i == 777:
# can customize exception messages
raise Exception("terrible bug")
result = 1 + 1
return result
print(long_loop())
s = "next statement"
# Will this print? Why or why not?
print(s)
|
e09bce791b70df00727e8594b1f60cdd6e27aa9d | FranzDiebold/covfefe-flow | /api/src/covfefe_flow/util.py | 1,847 | 3.53125 | 4 | """Utility functions."""
import string
from typing import Tuple, List, Dict
import numpy as np
def get_vocabulary_and_dictionaries() -> Tuple[List[str], Dict[str, int], Dict[int, str], int]:
"""Get the vocabulary and
dictionaries for converting between characters and one-hot encoding."""
printable_chars = [
char for char in string.printable if char not in ('\t', '\r', '\x0b', '\x0c')
]
extra_chars = ['✅', '🏆', '📈', '📉', '🎥', '💰', '📸', '…']
vocabulary = sorted(printable_chars + extra_chars)
char_to_id = dict((char, i + 1) for i, char in enumerate(vocabulary))
char_to_id[''] = 0
id_to_char = dict((char_to_id[char], char) for char in char_to_id)
vocabulary_size = len(char_to_id)
return vocabulary, char_to_id, id_to_char, vocabulary_size
def vectorize_sentences(sentences: List[str], maxlen: int, vocabulary_size: int,
char_to_id: Dict[str, int]) -> np.ndarray:
"""Vectorize a list of senctences using a one-hot encoding on character level."""
vectorized_sentences = np.zeros((len(sentences), maxlen, vocabulary_size), dtype=np.float32)
for i, sentence in enumerate(sentences):
index_offset = maxlen - len(sentence)
for j, char in enumerate(sentence):
vectorized_sentences[i, index_offset + j, char_to_id[char]] = 1
return vectorized_sentences
def sample(input_predictions: np.ndarray, temperature=1.0) -> np.ndarray:
"""Sample from a given `input_predictions` distribution."""
predictions = np.asarray(input_predictions).astype('float64')
exp_predictions = np.exp(np.log(predictions) / temperature)
normalized_predictions = exp_predictions / np.sum(exp_predictions)
probabilities = np.random.multinomial(1, normalized_predictions, 1)
return np.argmax(probabilities)
|
e7f1ce3f02cd4fc9f319ae93fe894dcebfa0a9d0 | kabir-shah/cloud9-python | /1.3.5/Shah_1.3.5.py | 2,136 | 4.09375 | 4 | from __future__ import print_function
"""Procedure (1-12)"""
slogan = 'My school is the best'
# 5 int, float, and long can represent the number 6 million
# 6 The second input produces an error because the "+" operator doesn't accept
# different types of inputs, and the inputs given were a string and an integer.
# In the first example, both were strings, even though different quotes were
# used.
# 7 An index n accesses the (n+1)th character of the string because the first
# character corresponds to the index of 0. When the index is 26, it attempts
# to access the 27th character, which doesn't exist. Negative indexes start at
# the last character, and go back from the end. -1 corresponds to the last
# character, -2 corresponds to the second to last, and so on. slogan[-7] returns
# "h" because it is the 7th to last character.
# 8 Slicing
print(slogan[17:21])
# 9 Slicing & Concatenation
print(slogan[:13] + "DHS, and it " + slogan[10:] + "!")
# 10
activity = 'theater'
len(activity) # -> 7
# 10a Explain
# The word "theater" has seven letters, so the length is 7.
activity[0 : len(activity)-1]
# 10b Explain
# This slices from the first character *until* the last index, which is found
# by the length minus one because indexes start at zero. This means that the
# slice contains everything except the last character, "theate"
# 11 Explain
'test goo' in 'Greatest good for the greatest number!' # -> True
# The code returns true because the string contains the text
# 'Greatest good for the greatest number!'
# ^^^^^^^^
# 12 How Eligible Function
def how_eligible(essay):
"""
Returns 0-4 based on how many requirement characters are within the essay
"""
score = 0
for char in ["?", "\"", ",", "!"]:
if char in essay:
score += 1
return score
def how_eligible_one_line(essay):
return sum([1 if char in essay else 0 for char in ["?", "\"", ",", "!"]])
#1.3.5 Function Test
print(how_eligible('This? "Yes." No, not really!')) # -> 4
print(how_eligible('Really, not a compound sentence.')) # -> 2
# Yes. I believe I did it correctly. |
e26b90bd80b6e66c5c1f373d2aa0bff6fa283a31 | HARIDARUKUMALLI/devops-freshers | /Anashka_folder/file_eg1.py | 239 | 3.5625 | 4 | #!/usr/bin/python
# Open a file
f = open ("abc","r+")
#writing into a file
f.write("Hi, How are you...")
#reading contents into a variable
content = f.read(18);
#displaying the contents
print(content)
f.tell()
#close a file
f.close() |
eb6add38810dabf73d2f48f1e332a5a80d841ae6 | HARIDARUKUMALLI/devops-freshers | /Anashka_folder/mark_grade.py | 284 | 4.0625 | 4 | name = input("Enter your name :")
mark = int(input("Enter your mark : "))
if mark>90:
print("{} got A grade".format(name))
elif mark>80:
print("{} got B grade".format(name))
elif mark>70:
print("{} got C grade".format(name))
else:
print("{} got D grade".format(name)) |
682029f90434b9087e0c6cb55cf9b51e262d5f2b | HARIDARUKUMALLI/devops-freshers | /Bhaskar_Folder/python scripting/pallindrome.py | 279 | 4.21875 | 4 | print("enter a number")
num=int(input())
temp=num
pnum=0
r=0
while temp>0:
r=temp%10
pnum=pnum*10+r
temp=temp//10
if(num==pnum):
print("the given number "+ str(num) +" is a pallindrome")
else:
print("the given number "+ str(num) +" is not a pallindrome") |
e2a33ba5bdd35fb8a4ea05c451874d3c2f1f47ea | HARIDARUKUMALLI/devops-freshers | /Anashka_folder/div_by_zero.py | 234 | 3.75 | 4 | a = int(input("Enter the number to be divided:"))
b = int(input("Enter the number to divide:"))
try:
c=a/b
except(ZeroDivisionError, NameError):
print("Error has occured & handled..")
print("Result of division is : {}".format(c)) |
b687e09865140395274f7342eb3744da3e890cc8 | HARIDARUKUMALLI/devops-freshers | /Bhaskar_Folder/python scripting/data_abstraction.py | 296 | 3.625 | 4 | class Object_Count:
__count = 0;
def __init__(self):
Object_Count.__count = Object_Count.__count+1
def display(self):
print("The number of objects created for this class:",Object_Count.__count)
ob1 = Object_Count()
ob2 = Object_Count()
ob1.display()
|
04c17e20a53029297bf701220eb35e60ece204f4 | HARIDARUKUMALLI/devops-freshers | /Anashka_folder/Class_eg.py | 313 | 3.5 | 4 | class Details:
def __init__(self,name,age,mark,tutor): # class definition
self.name = name
self.age = age
self.mark = mark
self.tutor = tutor
ob = Details('Aan',18,90,'Deepa') # Object creation
print(ob.name)
print(ob.age)
print(ob.mark)
print(ob.tutor) |
035c47a7d4de47baffb8bf0ef2430b9872bc3212 | teemusy/AOC2019 | /06/python/main.py | 3,338 | 3.875 | 4 | def main():
f = open("../6_input.txt", "r")
planet_list = f.readlines()
f.close()
# create tuple from integers in int file
planet_list = [n.rstrip() for n in planet_list]
planet_list_copy = planet_list.copy()
# central object that all other objects orbit
central_object = "COM"
# insert central object in 2d list as starting point
celestial_objects = [[central_object]]
# find all objects that loop around central object and add them to next index, than do the same to them
index = 0
while len(planet_list):
orbiters, planet_list = find_orbiters(celestial_objects[index], planet_list)
celestial_objects.append(orbiters)
index += 1
# count orbits
orbits = calculate_orbits(celestial_objects)
print("Number of combined orbits:", orbits)
# find shortest route to santa
planet_list = planet_list_copy.copy()
shortest_route = find_route(planet_list)
print("Minimum orbital transfers required:", shortest_route)
def find_route(planet_list):
planet_list_copy = planet_list.copy()
# find your route to start
starting_point = "YOU"
you = []
i = 0
while starting_point != "COM":
if starting_point in planet_list[i].split(")")[1]:
you.append(planet_list[i])
starting_point = planet_list[i].split(")")[0]
# remove from list to make loops faster
planet_list.pop(i)
i = 0
else:
i += 1
# find santas route to start
planet_list = planet_list_copy.copy()
starting_point = "SAN"
santa = []
i = 0
while starting_point != "COM":
if starting_point in planet_list[i].split(")")[1]:
santa.append(planet_list[i])
starting_point = planet_list[i].split(")")[0]
# remove from list to make loops faster
planet_list.pop(i)
i = 0
else:
i += 1
# split lists so only starting points are left, then reverse lists
you = [item.split(")")[0] for item in you]
santa = [item.split(")")[0] for item in santa]
you.reverse()
santa.reverse()
# loop lists and find the last common origo
for i in range(len(you)):
if you[i] != santa[i]:
break
else:
common_origo = you[i]
# reverse lists again and count steps until common origo
you.reverse()
santa.reverse()
your_steps = you.index(common_origo)
santas_steps = santa.index(common_origo)
step_count = your_steps + santas_steps
return step_count
def find_orbiters(celestial_objects, planet_list):
orbiters = []
# for loop in reverse so we can remove values from it
for i in range(len(planet_list) - 1, -1, -1):
left, right = planet_list[i].split(")")
if left in celestial_objects:
orbiters.append(right)
planet_list.pop(i)
return orbiters, planet_list
def calculate_orbits(celestial_objects):
orbits = 0
for i in range(1, len(celestial_objects)):
# exclude YOU and SAN
if "YOU" in celestial_objects[i] or "SAN" in celestial_objects[i]:
orbits += (len(celestial_objects[i]) - 1) * i
else:
orbits += len(celestial_objects[i]) * i
return orbits
if __name__ == '__main__':
main() |
26b555ce40fec377f30e19cf0d8be4559c9333a3 | rajgubrele/hakerrank_ds_linkedlist_python | /GitHub Uploaded(6).py | 1,341 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# ##
# Linked Lists ---> Insert a Node at the Tail of a Linked List
#
# You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty.##
# In[ ]:
import math
import os
import random
import re
import sys
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def print_singly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
# Complete the insertNodeAtTail function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def insertNodeAtTail(head, data):
new_list = SinglyLinkedListNode(data)
if head is None:
head = new_list
else:
temp = head
while temp.next is not None:
temp = temp.next
temp.next = new_list
return head
if __name__ == '__main__':
|
872729e9b08c70da293d35e4951aa930c3026a49 | bopopescu/shri_repository | /A My Practice/PycharmProjects/Python_Practice/ass8.py | 517 | 4.03125 | 4 | class Stack():
def __init__(self):
self.items=[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items==[]
def peek(self):
if not self.is_empty():
return self.items[-1]
def get_stack(self):
return self.items
s1=Stack()
s1.push("S")
s1.push("h")
s1.push("r")
s1.push("i")
print(s1.get_stack())
s1.push("p")
print(s1.get_stack())
s1.pop()
print(s1.get_stack()) |
a90f742ed8cd70ba46abdb9876383682dad413a3 | bopopescu/shri_repository | /A My Practice/PycharmProjects/Python_Practice/ass7.py | 662 | 3.53125 | 4 | class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def __str__(self):
return f'Account owner:{self.owner}\nAccount balance: ${self.balance}'
def deposit(self, dep_amt):
self.balance += dep_amt
print(f'${dep_amt} Deposit Accepted')
def withdraw(self, wd_amt):
if self.balance >= wd_amt:
self.balance -= wd_amt
print(f'${wd_amt} Withdrawal Accepted')
else:
print('Funds Unavailable!')
acct1 = Account('Shri',800)
print(acct1)
acct1.deposit(200)
acct1.withdraw(500)
print(f'Current balance :{acct1.balance}') |
736020d979b17c3313dfee8415b16a500ed9127d | Mushinako/ICPC-CSULB2-2019 | /Practice/2017 Regional/06-8183/sol8183.py | 356 | 3.515625 | 4 | #!/usr/bin/env python3
def syl(word):
word = word.lower()
syl = 0
return
def haiku(s):
sent = s.split()
def main():
while True:
try:
s = input().strip()
except EOFError:
return
else:
res = haiku(s)
print('\n'.join(res))
if __name__ == '__main__':
main()
|
8ed76937bbab7118a3d11a695aac96cfccb8ecd6 | Mushinako/ICPC-CSULB2-2019 | /Practice/20191021-Qual/01-1585/sol.py | 343 | 3.640625 | 4 | #!/usr/bin/env python3
def score(s):
tot = 0
i = 1
for c in s:
if c == 'O':
tot += i
i += 1
else:
i = 1
return tot
def main():
t = int(input())
for _ in range(t):
s = input()
res = score(s)
print(res)
if __name__ == '__main__':
main()
|
d432b6cc812ecc33f472ef64da7f7baf77de4e47 | PaulFranssen/info | /time.py | 546 | 3.75 | 4 | import datetime
d = datetime.datetime.now()
print(type(d)) # >>> objet datetime.datetime
print(d) # >>>2020-12-27 19:35:51.013790
print(datetime.datetime.strftime(d,"%Y-%m-%d")) # >>>2020-12-27 (argument2 est le format)
print(datetime.datetime.strftime(d + datetime.timedelta(days=1), "%Y-%m-%d")) # timedelta ajoute un intervalle de temps
# https://docs.python.org/fr/3/library/datetime.html#strftime-strptime-behavior
x = datetime.datetime(d.year, d.month, d.day)-datetime.timedelta(days=1) # jour précédent à 0h
print(x, d) |
071257cb1b4d48596a33736dc019efa68b75a599 | omarv94/Python | /HelloWord.py | 1,302 | 4.1875 | 4 | # print ("hello word")
# numero1 =int(input('Ingrese numero 1 : '))
# numero2 =int(input('Ingrese numero 2 : '))
# numero3 =int(input('Ingrese numero 3 : '))
# if numero1 == numero2 and numero1 == numero3:
# print('Empate')
# elif numero1 == numero2 and numero1 > numero3:
# print('numero uno y numero dos son mayores')
# elif numero2 ==numero3 and numero2 > numero1:
# print('numero dos y numero 3 son mayores ')
# elif numero1 == numero3 and
#for structure
suma=0
for i in range(5):
suma = suma + int(input('ingrese un nuevo numero : '))
print(suma)
#while structure
suma = 0
while True:
suma = suma + int(input('ingrse numero : '))
stop = input('Desea cuntinuar S/si N/no')
if stop != "S" and stop != "s":
break
print(suma)
suma =0
num1 =0
num2 =0
while True:
while True:
num1 = int(input('ingrese un numero de el 1-5'))
if num1 > 1 and num1 < 5:
break
else:
print('numero Erroneo debe ser un numero de 1 a 5')
while True:
num2 = int(input('ingrese un numero de el 5-9'))
if num2 > 6 and num2 <10:
break
else:
print('numero incorrecto, Debe ser un numero entre 6 y 10')
suma = suma +num1 +num2
stop = input('Desea cuntinuar S/si N/no') |
8df12ba6002d3dcf68d73c313afc0a82c9a9f95f | nmichiels/adventofcode2019 | /day7/advent7.py | 5,065 | 3.546875 | 4 | import numpy as np
def runProgram(instructions, inputs):
outputs = []
pc = 0 # program counter
instruction = instructions[pc]
while instruction != 99:
# for i in range(3):
#print("PC %d: %d"%(pc, instruction))
opcode = instruction
digits = [int(d) for d in str(opcode)]
maxDigits = 5
digits = np.pad(digits, (maxDigits-len(digits),0), mode='constant', constant_values=(0, 0))
opcode = digits[-2]*10 + digits[-1]
digits = digits[:-2] #remove opcode from digits
if opcode == 1 or opcode == 2:
if digits[-1]:
val1 = instructions[pc+1]
else:
val1 = instructions[instructions[pc+1]]
if digits[-2]:
val2 = instructions[pc+2]
else:
val2 = instructions[instructions[pc+2]]
if digits[-3]:
print("not sure what to do")
outputPos = instructions[pc+3]
else:
outputPos = instructions[pc+3]
if opcode == 1:
instructions[outputPos] = val1 + val2
if opcode == 2:
instructions[outputPos] = val1 * val2
pc += 4
if opcode == 3:
num = inputs.pop(0)#int(input())
if digits[-1]:
print("not sure what to do for opcode 3 position")
instructions[instructions[pc+1]] = num
else:
instructions[instructions[pc+1]] = num
pc += 2
if opcode == 4:
if digits[-1]:
val = instructions[pc+1]
else:
val = instructions[instructions[pc+1]]
inputPos = instructions[pc+1]
outputs.append(val)
#print("out", val)
pc += 2
if opcode == 5:
if digits[-1]:
val = instructions[pc+1]
else:
val = instructions[instructions[pc+1]]
if val != 0:
if digits[-2]:
pc = instructions[pc+2]
else:
pc = instructions[instructions[pc+2]]
else:
pc += 3
if opcode == 6:
if digits[-1]:
val = instructions[pc+1]
else:
val = instructions[instructions[pc+1]]
if val == 0:
if digits[-2]:
pc = instructions[pc+2]
else:
pc = instructions[instructions[pc+2]]
else:
pc += 3
if opcode == 7:
if digits[-1]:
val1 = instructions[pc+1]
else:
val1 = instructions[instructions[pc+1]]
if digits[-2]:
val2 = instructions[pc+2]
else:
val2 = instructions[instructions[pc+2]]
if digits[-3]:
print("not sure what to do for opcode 7")
outPos = instructions[pc+3]
else:
# print("not sure what to do for opcode 7")
outPos = instructions[pc+3]
#outPos = instructions[instructions[pc+3]]
if val1 < val2:
instructions[outPos] = 1
else:
instructions[outPos] = 0
pc += 4
if opcode == 8:
if digits[-1]:
val1 = instructions[pc+1]
else:
val1 = instructions[instructions[pc+1]]
if digits[-2]:
val2 = instructions[pc+2]
else:
val2 = instructions[instructions[pc+2]]
if digits[-3]:
print("not sure what to do for opcode 8")
outPos = instructions[pc+3]
else:
#print("not sure what to do for opcode 8")
outPos = instructions[pc+3]
#outPos = instructions[instructions[pc+3]]
if val1 == val2:
instructions[outPos] = 1
else:
instructions[outPos] = 0
pc += 4
instruction = instructions[pc]
return outputs
instructions = np.loadtxt('input_7.txt', delimiter=',', dtype='int')
code = instructions.copy()
import itertools
combinations = list(itertools.permutations([0,1, 2, 3,4]))
print(combinations)
amplifiers = [instructions.copy() for i in range(5)]
maxOutput = 0.0
for combination in combinations:
phases = combination
inputs = [phases[0], 0]
totalOutput = 0
for i in range(1,6):
#code = instructions.copy()
outputs = runProgram(amplifiers[i-1],inputs)
print("outputs ", outputs)
if i < 5:
inputs = [phases[i], outputs[-1]]
totalOutput = outputs[-1]
print("totalOutput", totalOutput)
if totalOutput > maxOutput:
maxOutput = totalOutput
print("max output: ", maxOutput)
|
2718f59df908357c28b37c92b25015db07105e68 | Jiwon-Woo/Baekjoon | /20_ divide/19_8.py | 678 | 3.609375 | 4 | import sys
n = int(sys.stdin.readline().strip())
matrix = [[1, 1], [1, 0]]
def matrix_multi(a, x):
ret = [[0 for _ in range(2)] for _ in range(2)]
for row in range(2):
for col in range(2):
for i in range(2):
ret[row][col] += a[row][i] * x[i][col]
ret[row][col] %= 1000000007
return (ret)
def matrix_power(a, b):
if b == 1:
return a
if b == 2:
return matrix_multi(a, a)
temp = matrix_power(matrix_power(a, b // 2), 2)
if (b % 2 == 0):
return (temp)
else:
return (matrix_multi(temp, a))
def fibonacci(n, matrix):
if n== 0:
return 0
if n == 1 or n == 2:
return 1
temp = matrix_power(matrix, n)
return temp[1][0]
print(fibonacci(n, matrix))
|
66a2b506db91648cfdee44bf217ffd09260d1126 | Jiwon-Woo/Baekjoon | /17_c_n/16_3.py | 536 | 3.53125 | 4 | import sys
n1, n2 = map(int, sys.stdin.readline().split())
def inter(x, y):
maxi = 1
i = 2
while (x > 1 and y > 1 and min(x, y) >= i):
while (x % i == 0 and y % i == 0 and min(x, y) >= i):
maxi *= i
x = x // i
y = y // i
i += 1
return maxi
def union(x, y):
mini = 1
i = 2
while (x > 1 or y > 1) and max(x, y) >= i:
while (x % i == 0 or y % i == 0) and max(x, y) >= i:
mini *= i
if x % i == 0:
x = x // i
if y % i == 0:
y = y // i
i += 1
return mini
print(inter(n1, n2))
print(union(n1, n2)) |
20d1413c6fb7fc87af8f0f5cc7f76bd46e0e6830 | gusVLZ/PythonLabs | /if.py | 87 | 3.71875 | 4 | a=1
if(a==0):
print("zero")
elif(a%2==0):
print("par")
else:
print("impar") |
05b4366198cb9b1dd5376e24bd5170b03ba40a73 | KonstantinSKY/skybot | /databases.py | 3,387 | 3.53125 | 4 | import sqlite3
from decorators import try_decor
from say import Say
from abc import ABC, abstractmethod
from logger import Logger
log = Logger(__name__)
# class ConnectDB(sqlite3.Connection): # The class expands the possibilities of working with the database
# count = 0
#
# def __init__(self, db_file):
# super().__init__(db_file)
# self.cur = self.cursor()
# ConnectDB.count += 1
#
# """Create table in Data base with try-exception
# EXAMPLE IN
# create_table('table_name',
# '''
# id INTEGER PRIMARY KEY,
# name TEXT UNIQUE NOT NULL,
# url TEXT UNIQUE NOT NULL,
# description TEXT
# '''
# """
class DataBases(ABC):
def __init__(self):
self.cur = None
@try_decor
def create_table(self, table, fields):
self.cur.execute(f"CREATE TABLE IF NOT EXISTS {table} ({fields})")
Say(f"Created the table: {table}").prn_ok()
return True
@try_decor
def select_all(self, table):
self.cur.execute(f"SELECT * FROM {table}")
records = self.cur.fetchall()
Say(f"Got records: {len(records)}").prn_ok()
return records
@try_decor
def select_max(self, table, max_field):
self.cur.execute(f"SELECT MAX({max_field}) FROM {table}")
return self.cur.fetchall()[0][0]
@try_decor
def select_from_to_max(self, table, field, from_value) -> list:
"""
Select all field records from DB with from value of 'field' to max value
:param table: string: DB Table Name
:param field: string: Field for data select
:param from_value: int or float: Value of field for Select from which to
:return: List of Tuples: DB Records
"""
self.cur.execute(f"SELECT * FROM {table} WHERE {field} >= {from_value}")
return self.cur.fetchall()
@try_decor
def insert(self, table, data_obj):
"""
Insert to table in Data Base from object to one record
:param table: string: DB Table Name
:param data_obj: obj: Data for insertField for data select
:param from_value: int or float: Value of field for Select from which to
:return int: last id of new DB record
:example
insert('table_name',
[{
"login": "test_login",
"password": "test_passwd",
"id_service": 1,
"id_person": None
},
{
"login": "test_login",
"password": "test_passwd",
"id_service": 2,
"id_person": None
},
...
]
"""
fields = ''
values = []
binds = '?, ' * (len(data_obj[0]) - 1) + '?'
for key, value in data_obj.items():
fields += f'{key}, '
values.append(value)
fields = fields.rstrip(", ")
query = f'INSERT OR IGNORE INTO {table} ({fields}) VALUES ({binds})'
return self.cur.execute(query, values).lastrowid
if __name__ == "__main__":
print("CHECK ZONE")
db_path = 'DB/oanda.sqlite'
conn = ConnectDB(db_path)
help(conn.select_from_to_max)
records = conn.select_from_to_max('EUR_USD', 'timestamp', 1601485325)
print(records)
|
1fbc7fdba3fca3653618bb18771528debfdaa46a | zagalom/DNA-to-mRNA-to-AA | /DNA_RNA_Protein.py | 3,005 | 3.90625 | 4 | #DNA->RNA->Protein
print ('Are you using a DNA ou RNA string?')
RNAS= 'RNA'
Resp=input().upper()
if "DNA" in Resp: #convert DNA to RNA
print('Is the strand sense or antisense? Meaning, from 5 to 3 or from 3 to 5?')
Resp2= input().upper()
if "ANTISENSE" in Resp2: #reverse
print ('Please input the string')
DNAs=input().upper()
RNAs = DNAs.replace('A', 'u').replace('T', 'a').replace('C', 'g').replace('G', 'c').upper()[::-1]
print (' ')
print ('The complementar RNA strand is:')
print (RNAs)
else:
print ('Please input the string')
DNAs=input().upper()
RNAs = DNAs.replace('A', 'u').replace('T', 'a').replace('C', 'g').replace('G', 'c').upper()
print (' ')
print ('The complementar RNA strand is:')
print (RNAs)
if "RNA" in Resp:
print ('Please input the string')
RNAs=input().upper()
def readable(seq, n): #chunks
for i in range(0, len(seq), n):
yield seq[i:i+n]
def method(seq, start=['AUG'], stop=['UAA','UAG','UGA']): #readable regions
response = ''
started = False
for x in readable(seq, 3):
if x in start:
started = True
response += ' '
if x in stop:
started=False
if started:
response += x
yield response
for result in method(RNAs):
b=result
print (' ')
print ('The readable part of the RNA is:')
print(result)
print (' ')
print ('Considering a minimum of 30 nucleotides, the readable part of the RNA is:')
f=result.split()
readable_regionslist=[x for x in f if len(x)>=int(30)] #minimum of 30 nucleotides
separator = ' '
readable_regions=(separator.join(readable_regionslist))
print(readable_regions)
def translate(seq): #translate the readable regions
table = {
'AUA':'I', 'AUC':'I', 'AUU':'I', 'AUG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACU':'T',
'AAC':'N', 'AAU':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGU':'S', 'AGA':'R', 'AGG':'R',
'CUA':'L', 'CUC':'L', 'CUG':'L', 'CUU':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCU':'P',
'CAC':'H', 'CAU':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGU':'R',
'GUA':'V', 'GUC':'V', 'GUG':'V', 'GUU':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCU':'A',
'GAC':'D', 'GAU':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGU':'G',
'UCA':'S', 'UCC':'S', 'UCG':'S', 'UCU':'S',
'UUC':'F', 'UUU':'F', 'UUA':'L', 'UUG':'L',
'UAC':'Y', 'UAU':'Y', 'UGG':'W', 'UGU':'C',
'UGC':'C', ' ':' '}
protein =""
if len(b)%3 == 0:
for i in range(0, len(seq), 3):
codon = seq[i:i + 3]
protein+= table[codon]
return protein
p = translate(b)
p = translate(readable_regions)
print (' ')
print ('The aa sequence is:')
print (p)
print('')
print('')
print ('Ready to close programm?')
Close=input().upper()
|
d3ccfaab64b22cefdd3589106a1d0af93e948748 | bruiken/nonograms | /nonogramsolver/board/boardreader.py | 1,750 | 3.703125 | 4 | from nonogramsolver.board.board import Board
from json import loads
from nonogramsolver.exceptions import InvalidBoardFile
class BoardReader:
"""
A board reader that reads a board from a json file. The json file needs to be structured as follows:
{
"width": int,
"height": int,
"constraints": {
"columns": [[int]],
"rows": [[int]]
},
"values": [
{
"x": int,
"y": int,
"value": bool // true -> cross, false -> empty
}
]
}
"""
def __init__(self, path):
"""
Constructor for a BoardReader.
:param path: The path to the .json file.
"""
self.path = path
def _get_board_data(self):
"""
Gets the board data from the given file.
:return: a dictionary representation of the data in the file.
"""
with open(self.path, 'r') as f:
return loads(f.read())
def get_board(self):
"""
Get a Board instance that represents the board in the given file.
:return: The Board of the file.
:raise: InvalidBoardFile: If there is a field missing in the file.
"""
data = self._get_board_data()
try:
board = Board(data['width'], data['height'], data['constraints']['rows'], data['constraints']['columns'])
for val in data['values']:
board_val = Board.Cross if val['value'] else Board.Empty
board.set_position(val['x'], val['y'], board_val)
return board
except KeyError as e:
raise InvalidBoardFile('The file does not contain the value \'{}\''.format(e.args[0]))
|
d9cc74f7d8ae69abf33aaefdfd08a0610707181a | bruiken/nonograms | /nonogramsolver/solvingstrategies/utilities.py | 5,428 | 3.703125 | 4 | from nonogramsolver.board import Board
class Utilities:
"""
Various utility functions used in the solving strategies.
"""
@staticmethod
def _get_positions_with_value(values, value):
"""
Function to get all the positions with the given value in a list of values.
:param values: The List of values to look in.
:param value: The value to look for.
:return: A list of tuples that contain the start- and end-indices of the blocks.
"""
val_pos_start = None
positions = []
for idx, v in enumerate(values):
if v == value and val_pos_start is None:
val_pos_start = idx
elif val_pos_start is not None and v != value:
positions.append((val_pos_start, idx - 1))
val_pos_start = None
if val_pos_start is not None: # when the block stops at the end of the value array
positions.append((val_pos_start, len(values) - 1))
return positions
@staticmethod
def get_positions_of_scores(values):
"""
Get all the positions in the given array where the crosses are.
:param values: The array of values.
:return: A list of tuples that contain the start- and end-indices of the blocks.
"""
return Utilities._get_positions_with_value(values, Board.Cross)
@staticmethod
def get_unknown_positions(values):
"""
Get all the positions in the given array where the unknown positions are.
:param values: The array of values.
:return: A list of tuples that contain the start- and end-indices of the blocks.
"""
return Utilities._get_positions_with_value(values, Board.Unknown)
@staticmethod
def all_blocks_present(values, constraints):
"""
Check if we definitely know that all the separate blocks are there already.
:param values: The array of values.
:param constraints: The constraints put on the array of values.
:return: True if all the blocks of scores are present, False if not or if we cannot know.
"""
scores = Board.get_score(values)
if scores == constraints: # simplest case where the scores are all done already
return True
if len(scores) == len(constraints):
return not Utilities._blocks_may_join(values, scores, constraints)
return False
@staticmethod
def _blocks_may_join(values, scores, constraints):
"""
Checks if existing blocks of crosses may join in an array of values.
:param values: The array of values to check.
:param scores: The scores of the values.
:param constraints: The constraints put on the values.
:return: True if it may be the case that two blocks are going to join, False otherwise.
"""
last_score_end = -999 # large negative integer for a minimum index
score_pos = Utilities.get_positions_of_scores(values)
unknown_pos = Utilities.get_unknown_positions(values)
for idx, (s_s, s_e) in enumerate(score_pos):
if Utilities.constraint_fit_in_unknown(constraints[idx], unknown_pos, last_score_end + 1, s_s - 2) and \
idx < len(scores) - 1 and \
Utilities._block_may_join(
constraints[idx + 1], score_pos[idx + 1][0], s_e, scores[idx], scores[idx + 1], unknown_pos):
return True
last_score_end = s_e + 1
return False
@staticmethod
def _block_may_join(next_constraint, start_next_score, end_current_score, current_score, next_score, unknowns):
"""
Checks if a block may join with another one. We do this by comparing the current score/block to the next one.
:param next_constraint: The constraint put on the next block.
:param start_next_score: The start index of the next block.
:param end_current_score: The end index of the current block.
:param current_score: The score of the current block.
:param next_score: The score of the next block.
:param unknowns: A list of pairs indicating the positions of unknown blocks.
:return: True if the two blocks may join, False otherwise.
"""
next_score_dist = start_next_score - end_current_score - 1
if Utilities.constraint_fit_in_unknown(next_score_dist, unknowns, end_current_score + 1,
start_next_score - 1):
if next_constraint - current_score - next_score_dist - next_score == 0:
return True
return False
@staticmethod
def constraint_fit_in_unknown(constraint, unknown_positions, from_idx, to_idx):
"""
Checks if a constraint may fit in unknown values based on a start- and end-index.
:param constraint: The constraint we want to fit.
:param unknown_positions: The list of pairs indicating the unknown positions.
:param from_idx: The start index to look for.
:param to_idx: The end index to look for.
:return: True if the constraint can fit inside a block of unknown values.
"""
for (u_s, u_e) in unknown_positions:
if from_idx <= u_s <= to_idx:
if u_e - u_s + 1 >= constraint and to_idx - from_idx + 1 >= constraint:
return True
return False
|
0d989ec465fe41be5fe3d6606e76c4bae1b586fe | tacostreets/bifrons | /template.py | 290 | 3.578125 | 4 | #!/usr/bin/env python3
def main(): # colon marks the beginning of a block of code
while True:
task = input("wat? ")
if task == "quit":
break
print(f"Did {task}")
if __name__ == '__main__': # this calls the script from the command line
main()
|
9e5f6e576e0ec2e1895a27681b0d978f08578e78 | bestofQ/python_Projects | /20200115/Numbers_and_Math.py | 769 | 4.03125 | 4 | '''
1、下列数字哪些是浮点,哪些是整数?
0.1 1.2 0 0.0 -1 -2.5 3
浮点数:0.1、1.2、0.0、-2.5
整数:0、-1、3
2、1 + 3.0 的结果是浮点还是整数?
浮点数
3、type()有什么功能?
一个函数——返回函数中的参数的数据类型
eg:
# >>>type(2)
# >>>int
3、在Python 3中,1 / 3 等于多少?
0.333333333333....
4、3**3 等于多少?
3^3=27
5、1 // 3 等于多少? 1 // 3.0 呢?
// 整除
1//3=0
1//3.0=0.0
6、3 % 2 等于多少?
答案:1 【'%' 取模运算,两数相除求余数;拓展-百度百科:取模运算】
7、6 * 8 / 2 ** (4 - 2) * 2 % 3 等于多少?
存在除法 就获取 浮点数
'''
print(type(3))
# <class 'int'>
print(3**3) |
2f270cbf763c393a700896801f290cb1fa52faf7 | andreschamorro/LAST | /L1_length/seq_length_hist.py | 1,781 | 3.609375 | 4 | # seq_length_hist.py
# Author: Juan O. Lopez (juano.lopez@upr.edu)
# Creation date: March 24, 2018
# Modification date: March 30, 2018
#
# This program receives an input file (FASTA or text) as an argument
# and generates a histogram of the lengths of the sequences.
# Sometimes the extrema render the graph useless because the data is
# spread out too thin. That's why we also allow the user to specify how
# many length entries should be skipped at the start and at the end.
import matplotlib.pyplot as plt
import os
import sys
# Default values in case arguments are not used
SKIPATSTART = 0
SKIPATEND = 0
if len(sys.argv) < 2:
print("Usage:", sys.argv[0], " <filename> [<numSkipStart> <numSkipEnd>]")
exit()
elif len(sys.argv) == 4:
SKIPATSTART = int(sys.argv[2])
SKIPATEND = int(sys.argv[3])
# Read the sequences from the input file and store the lengths in a list
filename = sys.argv[1]
with open(filename) as fh:
lengthList = [ len(line) for line in fh if not line.startswith(">") ]
# We print the "histogram" to an output text file before we display the graph.
# Output file will have the same name as the input file, but we'll add
# "_length" at the end.
myHist = dict()
for l in lengthList:
myHist[l] = myHist.get(l,0) + 1
fh = open(os.path.splitext(sys.argv[1])[0]+"_length.txt","w")
for key in sorted(myHist.keys()):
fh.write(str(key) + ": " + str(myHist[key])+"\n")
fh.close()
# Now we generate and display the graph
lengthList.sort()
N, bins, patches = plt.hist(lengthList, bins='auto', range=(lengthList[SKIPATSTART],lengthList[len(lengthList)-1-SKIPATEND]))
plt.gca().minorticks_on()
plt.title(sys.argv[1])
# We'll save the graph to the same name as the text file, but .png
plt.savefig(os.path.splitext(sys.argv[1])[0]+"_length.png")
plt.show()
|
4d375df74abf5ab4144f3b0c1f03d1ab0a1bd7b9 | zhouyangf/ichw | /pyassign1/planets.py | 2,088 | 4.375 | 4 | """planets.py:'planets.py' is to present a animation of a simplified planetary
system.
__author__ = "Zhou Yangfan"
__pkuid__ = "1600017735"
__email__ = "pkuzyf@pku.edu.cn"
"""
import turtle
import math
def planets(alist):
"""This fuction can be used to present a animation of a simplified planetary
system.The formal parameter of this function should be a list of turtles wh-
-ich you wanna use to represent planets,such as[turtle1,turtle2,...].And the
list can contain any number of turtles.However,you must put the fixed star
as the first one and put the rest in order of distance to the fixed star.
"""
num = len(alist)
for i in range(num):
t = alist[i]
t.shape("circle")
t.speed(0)
t.pu()
x = i * (i + 20) ** 1.2 # set the scale of the orbit of each planet.(the fuction is assumed casually...)
if i % 2 == 1: # set the initial position for each planet according to whether the ordinal number of it is odd or even.
t.goto(-x * 4 / 5, -x)
else:
t.goto(x / 1.2, 0)
t.lt(90)
t.pd()
for i in range(1000):
for x in range(1, num):
t = alist[x]
r = 2 * x * (x + 20) ** 1.2 # set the scale of the orbit of each planet.
a = 2 * math.pi * i / (360 / (num - x)) # "num - x" is to control the speed of each planet.
l = 2 * math.pi * r / (360 / (num - x))
if x % 2 == 1:
t.fd(abs(math.cos(a)) * l)
else:
t.fd(abs(math.sin(a)) * l)
t.lt(num - x)
def main():
sun, mercury, venus, earth, mars, saturn, jupiter = turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle()
alist0=[sun, mercury, venus, earth, mars, saturn, jupiter]
sun.color("orange")
mercury.color("grey")
venus.color("yellow")
earth.color("blue")
mars.color("red")
saturn.color("brown")
jupiter.color("violet")
planets(alist0)
if __name__ == '__main__':
main()
|
66b3b8a47fcf3a5605aef8dca82caa0845b44fba | theprogbash/sorting_algorithms | /counting_sort.py | 544 | 4.0625 | 4 | def counting_sort(array, maxvalue):
length_of_empty_array = maxvalue + 1
empty_array = [0] * length_of_empty_array
for element in array:
empty_array[element] += 1
# empty_array - her elementden neche denedir. 0-dan bashlayaraq
print(empty_array)
index = 0
for i in range(length_of_empty_array):
for j in range(empty_array[i]):
print(f'i {i}')
array[index] = i
index += 1
return array
mylist = [4, 4, 4, 5, 1, 1, 2, 3, 4, 5]
print(counting_sort(mylist, 5)) |
8754a3e85dbecebd7d1291de784c1cb63c446b5d | Asurada2015/Python-Data-Analysis-Learning-Notes | /NumpyAndPandas/demo_00/17_pandasmerge_demo.py | 4,036 | 4.0625 | 4 | """merge是一种更加高级的合并方式,对于key也能做出操作"""
import pandas as pd
# merging two df by key/keys.(may be used in databases)
# simple example
left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
print(left)
print(right)
"""基于一个key值将两者合并在一起"""
res = pd.merge(left, right, on='key')
print(res)
# A B key C D
# 0 A0 B0 K0 C0 D0
# 1 A1 B1 K1 C1 D1
# 2 A2 B2 K2 C2 D2
# 3 A3 B3 K3 C3 D3
"""基于两个key将数组合并到一起"""
# consider two keys
left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
print(left)
print(right)
# A B key1 key2
# 0 A0 B0 K0 K0
# 1 A1 B1 K0 K1
# 2 A2 B2 K1 K0
# 3 A3 B3 K2 K1
# C D key1 key2
# 0 C0 D0 K0 K0
# 1 C1 D1 K1 K0
# 2 C2 D2 K1 K0
# 3 C3 D3 K2 K0
res = pd.merge(left, right, on=['key1', 'key2'], how='inner') # default for how='inner'
print(res)
# A B key1 key2 C D
# 0 A0 B0 K0 K0 C0 D0
# 1 A2 B2 K1 K0 C1 D1
# 2 A2 B2 K1 K0 C2 D2
"""内连接,只有所有key一模一样的时候才能连接成功~"""
res = pd.merge(left, right, on=['key1', 'key2'], how='outer')
print(res)
""""外连接,从笛卡尔积中查找"""
# A B key1 key2 C D
# 0 A0 B0 K0 K0 C0 D0
# 1 A1 B1 K0 K1 NaN NaN
# 2 A2 B2 K1 K0 C1 D1
# 3 A2 B2 K1 K0 C2 D2
# 4 A3 B3 K2 K1 NaN NaN
# 5 NaN NaN K2 K0 C3 D3
"""当 how是inner时表示内连接,outer时表示外连接,left表示左连接,right表示右连接"""
res = pd.merge(left, right, on=['key1', 'key2'], how='left')
print(res)
"""左连接"""
# A B key1 key2 C D
# 0 A0 B0 K0 K0 C0 D0
# 1 A1 B1 K0 K1 NaN NaN
# 2 A2 B2 K1 K0 C1 D1
# 3 A2 B2 K1 K0 C2 D2
# 4 A3 B3 K2 K1 NaN NaN
# indicator
df1 = pd.DataFrame({'col1': [0, 1], 'col_left': ['a', 'b']})
df2 = pd.DataFrame({'col1': [1, 2, 2], 'col_right': [2, 2, 2]})
print(df1)
print(df2)
res = pd.merge(df1, df2, on='col1', how='outer', indicator=True)
# 当indicator表示成为True的时候,显示连接方式
# give the indicator a custom name,给予连接方式一个名称
res = pd.merge(df1, df2, on='col1', how='outer', indicator='indicator_column')
print(res)
"""left index和right index index其实是最左边的一列
一般的都是考虑key属性,但是如果是利用index合并的话,考虑的是index
"""
# left_index and right_index
res = pd.merge(left, right, left_index=True, right_index=True, how='outer')
# res = pd.merge(left, right, left_index=True, right_index=True, how='inner')
print(res)
# A B key1_x key2_x C D key1_y key2_y
# 0 A0 B0 K0 K0 C0 D0 K0 K0
# 1 A1 B1 K0 K1 C1 D1 K1 K0
# 2 A2 B2 K1 K0 C2 D2 K1 K0
# 3 A3 B3 K2 K1 C3 D3 K2 K0
# handle overlapping
boys = pd.DataFrame({'k': ['K0', 'K1', 'K2'], 'age': [1, 2, 3]})
girls = pd.DataFrame({'k': ['K0', 'K0', 'K3'], 'age': [4, 5, 6]})
res = pd.merge(boys, girls, on='k', suffixes=['_boy', '_girl'], how='inner')
print(boys)
print(girls)
print(res)
# handle overlapping
boys = pd.DataFrame({'k': ['K0', 'K1', 'K2'], 'age': [1, 2, 3]})
girls = pd.DataFrame({'k': ['K0', 'K0', 'K3'], 'age': [4, 5, 6]})
res = pd.merge(boys, girls, on='k', how='inner')
print(res) |
6e9165db8a54894db9b33b4d26e98bdfc2011aeb | Asurada2015/Python-Data-Analysis-Learning-Notes | /Pythontutorials/34_pickle.py | 505 | 3.984375 | 4 | """用于将上次的数据加以保存方便下次进行计算和操作"""
import pickle
a_dict = {'da': 111, 2: [23,1,4], '23': {1:2,'d':'sad'}}
# pickle a variable to a file
file = open('pickle_example.pickle', 'wb') # b表示二进制形式,wb表示写入二进制
pickle.dump(a_dict, file)
file.close()
# reload a file to a variable
with open('pickle_example.pickle', 'rb') as file: # with语句就是当执行完毕后自动将其关闭
a_dict1 = pickle.load(file)
print(a_dict1)
|
9c79e63ff8c923c52683c1240826dc31b91ad22d | Asurada2015/Python-Data-Analysis-Learning-Notes | /Matplotlib/demo_00Mofandemo/07_legend_demo.py | 1,606 | 3.546875 | 4 | """图例-在图中区别不同曲线的名称"""
import matplotlib.pyplot as plt # 大部分情况下不需要加载matplotlib所有的包,比如这里只需要加载pyplot这个包就足够了
import numpy as np
"""制造数据"""
"""Figure指的是图层的显示框每个数据可以在不同的数据框中显示"""
x = np.linspace(-3, 3, 50) # 意为将-1~1之间评平分成50个点
y1 = 2 * x + 1
y2 = x**2 # 表示x的2次幂
# plt.figure(num=3, figsize=(8, 5)) # num设置的是figure序号,figsize设置的是长和宽度
# plt.figure()
plt.xlim((-1, 2)) # 设置x坐标轴的范围
plt.ylim((-2, 3)) # 设置y坐标轴的范围
"""设置x,y轴的lable即坐标轴上将要显现的文字"""
plt.xlabel("I am x")
plt.ylabel("I am y")
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad\ \alpha$', r'$normal$', '$good$', '$really\ good$']) # 数学表示的美观字体
"""线的lable属性标记线的名字"""
l1 = plt.plot(x, y2, label='up') # 默认颜色是蓝色,利用这个方法可以将两条图线装载到一个figure中
l2 = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='down') # 这里设置颜色为红色,设置线宽度为1
# plt.legend(handles=[l1, l2, ], labels=['straight', 'curve'], loc='best')
plt.legend()
# 设置图例,loc='best'意味着自动找一个好的地方生成图例,loc中可以添加许多种形式
# handle可以添加进入线的例子
# 如果这里设置了lables的话,那么原先单独设定的lables就会被覆盖掉
plt.show() |
70fde40430c1bfb1690917e8723c1dab3eb2ec25 | Asurada2015/Python-Data-Analysis-Learning-Notes | /Pythontutorials/7_8_9ifjudgement_demo.py | 866 | 4.28125 | 4 | # x = 1
# y = 2
# z = 3
# if x < y < z:
# print('x is less tha y ,and y is less than z')
# x is less tha y ,and y is less than z
# x = 1
# y = 2
# z = 0
# if x < y > z:
# print('x is less than y, and y is less than z')
# x is less than y, and y is less than z
# x = 2
# y = 2
# z = 0
#
# if x != y: # x == y
# print('x is equal to y')
x = 4
y = 2
z = 3
if x > y:
print('x is greater than y')
else:
print('x is less or equal to y')
"""多重选择if elif else"""
x = 1
if x > 1:
print('x > 1')
elif x < 1:
print('x < 1')
else:
print('x = 1')
x = -2
if x > 1:
print('x>1')
elif x < 1:
print('x<1')
elif x < -1:
print('x<-1')
else:
print('x=1')
print('finish running')
# 只是会从前面的开始匹配,遇到满足的条件就不会进行下面的判断了
# x is greater than y
# x = 1
# x<1
# finish running
|
e12225a9370f69a16dae31fbf89e58334cdc33d4 | Asurada2015/Python-Data-Analysis-Learning-Notes | /Pythontutorials/21_tupleAndlist_demo.py | 394 | 4.28125 | 4 | """元组和列表"""
# 元组利用()进行表示
# 列表用[]进行表示
a_tuple = (12, 3, 5, 15, 6) # 元祖的表示也可以不加上()
another_tuple = 2, 4, 6, 7, 8
a_list = (12, 3, 67, 7, 82)
# 遍历
for content in a_list:
print(content)
for content in a_tuple:
print(content)
for index in range(len(a_list)):
print('index=', index, 'number of index', a_list[index]) |
549d1193b5e21ffcd1630a5b8682b0308baf44dc | andrew7shen/calculate_gene_size | /correctforsizeBSC.py | 2,367 | 3.625 | 4 | #Andrew Shen
import sys
import re
###To run this program, go to the command line and specify four parameters:
###python correctforsizeBSC.py (input file 1) (input file 2) (output file)
###For this program, (input file 1) is the output file for the program addCodingSize_exons (output_exons.txt) and
###(input file 2) is the file BSCdata.txt (contains data about number of mutations per gene)
###Sets the two input files to different variables: "codingsize" and "BSCdata"
input_file = sys.argv[1]
read = open(input_file, "r")
codingsize = read.read()
input_file = sys.argv[2]
read = open(input_file, "r")
BSCdata = read.read()
###Cleans up the BSC data into a dictionary (mutations) with (key = gene) and (value = total number of mutations per gene)
BSCdata_newline = BSCdata.splitlines()
BSCdata_tab = []
for item in BSCdata_newline:
BSCdata_tab.append(item.split("\t"))
del BSCdata_tab[0]
mutation_count = {}
for item in BSCdata_tab:
del item[1]
item[:] = [x for x in item if x != "."] #keeps only items that aren't periods
mutation_count[item[0]] = [] #creates new dictionary item with gene name as key and empty list as value
for value in item[1:]:
mutation_count[item[0]].append(int(value[0])) #adds all mutation counts to the dictionary
for key in mutation_count:
mutation_count[key] = sum(mutation_count[key])###1113 genes
###Calculates the number of mutations per gene / gene size using the output_exons data file and the mutation_count dictionary
codingsize_newline = codingsize.splitlines()
codingsize_tab = []
for item in codingsize_newline:
codingsize_tab.append(item.split("\t"))
codingsize_dict = {}
for item in codingsize_tab:
item[1] = float(item[1]) / 1000#Converts to kilobase pairs
codingsize_dict[item[0]] = item[1]#1615 genes
corrected = {}
for key in codingsize_dict:
if key in mutation_count:
corrected[key] = round((mutation_count[key] / codingsize_dict[key]), 3) #round to three decimal places
###Formats the data into a text file with two columns: one for the gene name and one for the mutation rate (mutations per gene / gene size).
final_printed = ""
for key in corrected:
final_printed += key + "\t" + str(corrected[key]) + "\n"
###This piece of code writes pairs of gene names and mutation rates to the output file.
output_file = sys.argv[3]
write = open(output_file, "w")
write.write(str(final_printed))
write.close() |
21d14a6c89e219e41dca7f8d204e93248ab691e6 | kingsawyer/python_sqlite_talk | /stock_db.py | 4,375 | 3.875 | 4 | ## slide 4
from contextlib import closing, contextmanager
import sqlite3
from threading import Lock
class Stock(object):
"""Represents a stock holding (symbol, quantity, and price"""
def __init__(self, symbol='', quantity=0, price=0.0):
self.symbol = symbol
self.quantity = quantity
self.price = price
@classmethod
def from_row(cls, row):
return Stock(*row)
class StockDB(object):
def __init__(self):
## 1. ADD check_same_thread... otherwise Python will complain.
## This allows us to use multiple threads on the same connection. Be sure to have sqlite built with
## the Serialized option (default) and version 3.3.1 or later.
## 2. Change the isolation level to deferred so we can control transactions
self._connection = sqlite3.connect('example.db', check_same_thread=False, isolation_level='DEFERRED')
## WAL requires SQLite version 3.7 or later.
self._connection.execute('PRAGMA journal_mode = WAL')
self._lock = Lock()
def create_table(self):
"""Create the stocks table"""
with closing(self._connection.cursor()) as cursor:
cursor.execute("CREATE TABLE stocks (symbol text, quantity real, price real)")
# This is vulnerable to injection. DO NOT execute statements where the string is built from user input
# def insert(self, stock):
# """Insert stock in DB"""
# keys = stock.__dict__.iterkeys()
# values = (sql_value(x) for x in stock.__dict__.itervalues())
# with closing(self._connection.cursor()) as cursor:
# cursor.execute("INSERT INTO stocks({}) VALUES ({})".format(", ".join(keys), ", ".join(values)))
def insert(self, stock):
"""Insert stock in DB. stock cannot already be in the database"""
## Note this is using prepared statement format so it is safe from injection
places = ','.join(['?'] * len(stock.__dict__))
keys = ','.join(stock.__dict__.iterkeys())
values = tuple(stock.__dict__.itervalues())
with closing(self._connection.cursor()) as cursor:
cursor.execute("INSERT INTO stocks({}) VALUES ({})".format(keys, places), values)
def lookup(self, symbol):
"""Return stock if found, else None"""
with closing(self._connection.cursor()) as cursor:
cursor.execute('SELECT * FROM stocks WHERE symbol = ?', (symbol,))
row = cursor.fetchone()
if row:
return Stock.from_row(row)
def update(self, stock):
"""Update an existing stock"""
updates = ','.join(key + ' = ?' for key in stock.__dict__.iterkeys())
values = tuple(stock.__dict__.values() + [stock.symbol])
with closing(self._connection.cursor()) as cursor:
cursor.execute('UPDATE stocks SET {} WHERE symbol = ?'.format(updates), values)
# This is ok if each thread has its own connection. The writes will be serialized by SQLite
# I recommend sharing connections (below) because it it makes bookkeeping easier. If you do go with a separate
# connection per thread, consider overriding Thread.Run so you close the connection when Run completes.
# Otherwise, your unittests can have a hard time creating and deleting lots of temporary databases.
# def transaction(self):
# return self._connection
# This allows threads to share connections. When multiple threads are writing we perform the serialization
# by holding self._lock. No performance penalty here from our lock because SQLite only allows one writer at time.
@contextmanager
def transaction(self):
with self._lock:
try:
yield
self._connection.commit()
except:
self._connection.rollback()
raise
# Some sample usage
def main():
db = StockDB()
db.create_table()
stock = Stock('GOOG', 5, 600.10)
with db.transaction():
db.insert(stock)
stock = db.lookup('GOOG')
stock.quantity += 100
with db.transaction():
db.update(stock)
stock.quantity += 100
stock.price = 550.50
with db.transaction():
db.update(stock)
if __name__ == "__main__":
main()
|
804a2301cb8d78a7001e3a99ad64cc7b56cc4119 | jingwang622/AID1909 | /day04/exercise02.py | 1,438 | 3.5625 | 4 | # 使用Process方法,创建两个子进程去同时复制一个文件的上
# 半部分和下半部分,并分别写入到一个新的文件中。
# 获取文件大小: os.path.getsize()
import os
from multiprocessing import Process
def read_front_file(file_path):
"""
获取源文件大小
:param file_path:
:return:
"""
sum_size = os.path.getsize(file_path)
f = open(file_path,'r')
data_front = ""
data_behind = ""
for line in f.read(os.path.getsize(file_path)//2):
data_front += line
num = f.tell()
f.seek(num)
for line in f:
data_behind += line
f.close()
return (data_front,data_behind)
# def read_behind_file(file_path):
# """
# 获取源文件大小
# :param file_path:
# :return:
# """
# sum_size = os.path.getsize(file_path)
# f = open(file_path,'r')
# f.seek(os.path.getsize(file_path) // 2)
# data = ""
# for line in f:
# data += line
# return data
def write_file(data,file_path):
f = open(file_path,'a')
f.write(data)
f.close()
if __name__ == '__main__':
# 原始路径
p_list = []
file_path = "dict.txt"
file_path_new = "dict_new1.txt"
data_tuple = read_front_file(file_path)
for data in data_tuple:
p = Process(target=write_file,args=(data,file_path_new))
p_list.append(p)
p.start()
for p in p_list:
p.join()
|
0b8576c1b56616cb0c5670e34c219393a4dbb0a3 | robotlightsyou/pfb-resources | /sessions/002-session-strings/exercises/swap_case.py | 1,668 | 4.65625 | 5 | #! /usr/bin/env python3
'''
# start with getting a string from the user
start = input("Please enter the text you want altered: ")
# you have to declare your variable before you can add to it in the loop
output = ""
for letter in start:
# check the case of the character and return opposite if alphabetical
# isupper/islower are implicit isalpha checks as not letters aren't cased.
if letter.isupper():
output += letter.lower()
elif letter.islower():
output += letter.upper()
else:
output += letter
print(output)
'''
#Now lets try putting that into a function so you can call it multiple times
def swap_case(string):
output = ""
for letter in string:
if letter.isupper():
output += letter.lower()
elif letter.islower():
output += letter.upper()
else:
output += letter
return output
print(swap_case(input("Please enter the text you want altered: ")))
'''
Next Steps:
- rewrite function with the built in string.method that produces the same output
- write a new function that returns alternating letters based on even/odd index, or to return the reverse of a string(hint:indexing and slicing)
- Create a function, it should use if/elif/else statements to do at least 3 different outputs based on the user's input. Some examples:
if the user's string has more than one word, capitalize the first letter of the second word.
if the user's string has more than 5 'y's return "That's too many 'y's."
- The goal here is less to write a useful program and more to explore the different methods and get a little experience with control flow.
''' |
1b2f01a13a7a3c06ee81bba16a1e1f48d2395f76 | aishwarydhare/clock_pattern | /circle.py | 816 | 4.375 | 4 | # Python implementation
# to print circle pattern
import math
# function to print circle pattern
def printPattern(radius):
# dist represents distance to the center
# for horizontal movement
for i in range((2 * radius) + 1):
# for vertical movement
for j in range((2 * radius) + 1):
dist = math.sqrt((i - radius) * (i - radius) +
(j - radius) * (j - radius))
# dist should be in the
# range (radius - 0.5)
# and (radius + 0.5) to print stars(*)
if (dist > radius - 0.5 and dist < radius + 0.5):
print("*", end="")
else:
print(" ", end="")
print()
# Driver code
radius = 10
printPattern(radius)
# This code is contributed
# by Anant Agarwal. |
f901c7af862adecd8e1bf5e8eecb6ec31db9dc96 | muskanmahajan37/computacion-2 | /eje5.py | 1,099 | 3.875 | 4 | #Realice un programa que genere N procesos hijos. Cada proceso al iniciar deberá mostrar:
#“Soy el proceso N, mi padre es M” N será el PID de cada hijo, y M el PID del padre.
# padre
# / | \
# hijo1 hijo2 hijo3
#La cantidad de procesos hijos N será pasada mediante el argumento "-n" de línea de comandos.
#------------------------------------------------------------------------------------------------------#
#---------------------------------------COMIENZA EL EJERCICIO------------------------------------------#
#------------------------------------------------------------------------------------------------------#
# !/usr/bin/python3
import getopt
import sys
import os
(opt, arg) = getopt.getopt(sys.argv[1:], 'n:')
num = ''
for (op, ar) in opt:
if (op == '-n'):
num = int(ar)
def child(x):
print("Soy el proceso %d, mi padre es %d" % (os.getpid(), x))
os._exit(0)
def parent():
pid = os.getpid()
for x in range(num):
childProc = os.fork()
if childProc == 0:
child(pid)
parent()
|
d05fa0b45c87f4a7c2dc5c5126007604cfe8a49d | smartkot/desing_patterns | /behavioral/mediator.py | 1,507 | 3.578125 | 4 | """
Mediator (aka Token)
Defines simplified communication between classes.
"""
import inspect
class GameMode(object):
""" Mediator """
def make_pass(self):
raise NotImplementedError()
class Player(object):
""" Colleague """
def __init__(self, mediator):
self._mediator = mediator
def give_puck(self):
raise NotImplementedError()
def get_puck(self):
raise NotImplementedError()
class Training(GameMode):
""" Concrete Mediator """
def __init__(self):
self._first = None
self._second = None
def set_players(self, first, second):
self._first = first
self._second = second
def make_pass(self):
maker = inspect.currentframe().f_back.f_locals['self']
getter = self._first if maker == self._second else self._second
getter.give_puck()
class Defender(Player):
""" Concrete Colleague """
def give_puck(self):
print('Defender give a puck')
def get_puck(self):
print('Defender get a puck')
self._mediator.make_pass()
class Forward(Player):
""" Concrete Colleague """
def give_puck(self):
print('Forward give a puck')
def get_puck(self):
print('Forward get a puck')
self._mediator.make_pass()
if __name__ == '__main__':
assists = Training()
defender = Defender(assists)
forward = Forward(assists)
assists.set_players(defender, forward)
defender.get_puck()
forward.get_puck()
|
c5af48ec69547612a320bdd702e6459ba063fa19 | smartkot/desing_patterns | /creational/abstract_factory.py | 1,073 | 4.46875 | 4 | """
Abstract factory.
Provide an interface for creating families of related or
dependent objects without specifying their concrete classes.
"""
class AbstractFactory(object):
def create_phone(self):
raise NotImplementedError()
def create_network(self):
raise NotImplementedError()
class Phone(object):
def __init__(self, model_name):
self._model_name = model_name
def __str__(self):
return self._model_name
class Network(object):
def __init__(self, name):
self._name = name
def __str__(self):
return self._name
class ConcreteFactoryBeeline(AbstractFactory):
def create_phone(self):
return Phone('SENSEIT_A109')
def create_network(self):
return Network('Beeline')
class ConcreteFactoryMegafon(AbstractFactory):
def create_phone(self):
return Phone('MFLogin3T')
def create_network(self):
return Network('Megafon')
if __name__ == '__main__':
client = ConcreteFactoryBeeline()
print(client.create_phone(), client.create_network())
|
1a2170ee10de1cdf386272cd9ad7b94b37d5de07 | smartkot/desing_patterns | /behavioral/memento.py | 1,266 | 3.578125 | 4 | """
Memento
Provides the ability an object to its previous state (undo via rollback)
"""
class SavedGame(object):
""" Memento """
def __init__(self, state):
self._state = state
def get_state(self):
return self._state
class GamePlayer(object):
""" Caretaker """
def __init__(self):
self._memento = None
def get_memento(self):
return self._memento
def set_memento(self, memento):
self._memento = memento
class GameCampaign(object):
""" Originator """
def __init__(self):
self._state = None
def set_state(self, state):
self._state = state
def get_state(self):
return self._state
def save_game(self):
return SavedGame(self._state)
def undo_game(self, memento):
self._state = memento.get_state()
if __name__ == '__main__':
campaign = GameCampaign()
player = GamePlayer()
campaign.set_state('First Round')
print(campaign.get_state())
campaign.set_state('Second Round')
player.set_memento(campaign.save_game())
print(campaign.get_state())
campaign.set_state('Conference Finals')
print(campaign.get_state())
campaign.undo_game(player.get_memento())
print(campaign.get_state())
|
2857d490aa6bb84b8de7e52d23c787f85e8be90f | KBVKarthik/Python_Miniprojects | /Password_generator.py | 354 | 3.703125 | 4 | import random
chars='abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*'
number=input('Number of passwords? - ')
number=int(number)
length=input('Password length? - ')
length=int(length)
for p in range(number):
password=' '
for c in range(length):
password+=random.choice(chars)
print(password)
|
06a56b52359dfb82dd29757b4cb81a5ae8362e56 | henriavo/learning_python_5e | /part_3/ch10.py | 492 | 3.96875 | 4 |
while True:
reply = input("enter something:")
if reply == "stop": break
print(reply.upper())
while True:
reply = input("enter a number:")
if reply == "stop": break
replyInt = int(reply)
print(replyInt ** 2)
while True:
x = input("enter anything!")
if x == "stop": break
elif not x.isdigit(): print("BAD! " * 3)
else: print(int(x) * 2)
while True:
x = input("enter something:")
if x == "stop": break
try:
num = int(x)
except:
print("BAD! " * 3)
else:
print(num * 2)
|
716a00c586059ea21b993b45fd63484701b35ddb | merlose/python-exercises | /while_loops.py | 1,514 | 4.125 | 4 | # the variable below counts up until the condition is false
number = 1
while number <= 5:
print (number)
number = number + 1
print ("Done...")
# don't forget colons at ends of statements
example2 = 50
while example2 >= 1:
print (example2)
example2 = example2 / 5
print ("Finish")
floatyPythons = 6
while floatyPythons <= 10000:
print ("%.1f" % floatyPythons)
floatyPythons = floatyPythons * 1.5
print ("Enough floatyPythons")
# to print results to a number of decimal places:
# use ' "%.2f" % ' variable
# (2 is to 2 decimal places in this example)
# infinite loop
# these never stop running. their condition is always True
print ("break")
# break
# break ends a while loop prematurely
bork = 0
while 1 == 1: # which is always
print (bork) # prints variable's value
bork = bork + 1 # takes value and adds 1 repeatedly
if bork >= 5: # because of the "while"
print ("Borken") # once value >= 5 print this
break # break command halts loop
print ("Done borked.")
print ("continue")
# continue jumps to the next line of the loop
# instead of stopping it
cont = 0
while True:
cont = cont + 1
if cont == 2:
print ("No twos here...")
continue
if cont == 5:
print ("Borking")
break
print (cont)
print ("Done")
# use of "continue" outside of loops will error |
d09bc0f8728741d7620d58b28896d2e0d05fa223 | amalmhn/PythonDjangoProjects | /functional_programming/map_reduce_filter/map_function.py | 654 | 3.9375 | 4 | lst=[10,11,12,13,14,15]
#if you want to do some function in all elements in the list
#squares
#map(function,iterable)
def squ(no):
return no**2
#
# squares=list(map(lambda no:no**2,lst))
# print(squares)
#
squares=list(map(squ,lst))
print(squares)
#lambda helps to reduce the unwanted functions
cubes=list(map(lambda no:no**3,lst))
print(cubes)
print('------------------------------')
#FILTER
#fetch only even numbers???
even=list(filter(lambda no:no%2==0,lst))
print(even)
#???
names=['ajay','aji','binoy','abhi','anu']
na=list(map(lambda name:name.upper(),names))
print(na)
aname=list(filter(lambda name:name[0]=='a',names))
print(aname)
|
0657559c5a8865000167824edae145ccfd9e886a | amalmhn/PythonDjangoProjects | /gui_programming/gui_pgm_1.py | 307 | 3.96875 | 4 | from tkinter import *
#variable
root=Tk()
root.title('Main window')
label1=Label(root,text='username')
label2=Label(root,text='email address')
label3=Label(root,text='password')
entry1=Entry(root)
label1.pack() #to view the label inside the window
entry1.pack()
label2.pack()
label3.pack()
root.mainloop() |
8ba0ae06c3eee4a3a3b8572c714a9f34566cd78d | amalmhn/PythonDjangoProjects | /diff_function/var_arg_methods.py | 635 | 4.28125 | 4 | # def add(num1,num2):
# res=num1+num2
# print(res)
#
# add(10,20)
#variable length argument methods
def add(*args): # "*" will help to input infinite arguments
total=0
for num in args:
total+=num
print(total) #values will accpet as tuple
add(10,20)
add(10,20,30)
add(10,11,12,13,14)
print('---------------------------------------------------------------')
def printEmp(**arg): # "*" will help to input infinite arguments into dict
print(arg) #values will accpet as dict
printEmp(Home='Kakkanad',Name="Ajay",Working='aluway')
# *arg accpests in tuple format and **args accept in dict format
|
01c3908cbdce041d0af6bd4ae3d1982e0365865d | amalmhn/PythonDjangoProjects | /object_oriented_programming/polymorphism/verride.py | 236 | 3.9375 | 4 | class Person:
def __init__(self,age,name):
self.name=name
self.age=age
def __str__(self):
return self.name
p=Person(25,'Person1')
print(p)
#if we are printing an object __str__() method will execute
|
1987f5460a2092162a5bc9162caf6b604f305e12 | amalmhn/PythonDjangoProjects | /object_oriented_programming/polymorphism/method_overloading.py | 531 | 3.96875 | 4 | class Maths:
def add(self):
print('inside no arg add method')
def add(self,num1):
print('inside single arg add method')
def add(self,num1,num2): #the receiving values called parameters
print('inside two arg add method')
#here same method name, different number of arguments.
#add()
m=Maths()
m.add(10,20) #This passing values are variables
m.add(10)
#in python recently implemented method will work. ie method overloading
#if this overloading outside a class, called function overloading |
a4593c5314c6a7d92107bb72c0165c9c9c0d5696 | amalmhn/PythonDjangoProjects | /object_oriented_programming/polymorphism/method_over_riding.py | 278 | 3.90625 | 4 | class Parent:
def phone(self):
print('have nokia 5310')
class Child(Parent):
def phone(self):
print('have nokia iphone 12')
pass
c=Child()
c.phone()
#This is method overriding
#A Parent and child class relationship should be there for overriding
# |
179a75550dd81cc01f51f943db60b296aadbd43c | amalmhn/PythonDjangoProjects | /file_IO/file_pgm_first.py | 350 | 3.546875 | 4 | #file operations are Read r, Write w and Append a (MAIN OPRTNS)
#step1 create reference
#reference_name=open(filepath,mode_of_operation)
f=open('names','r')
# for lines in f:
# print(lines)
lst=[]
for lines in f:
lst.append(lines.rstrip('\n'))
print(lst)
#rstrip and lstrip function
# data='hello\n'
# data=data.rstrip('\n')
# print(data)
|
30c432876355faee4062ad689efd01e052d70d04 | amalmhn/PythonDjangoProjects | /flow_controls/looping_statements/for_loop/hw_primenumber.py | 244 | 3.59375 | 4 | lower = 10
upper = 50
for num in range(lower, upper + 1): #10 11
if num > 1: #10>1 11>1
for i in range(2, num): #2,10 2,11
if (num % i) == 0: #10%2==0 11%2==0
break
else:
print(num) |
7995ded5977d1ff9af72d6e9e31ec84b39b398da | JuanAntonaccio/Master_Python | /exercises/06-previous_and_next/app.py | 268 | 4.28125 | 4 | #Complete the function to return the previous and next number of a given numner.".
def previous_next(num):
a=num-1
b=num+1
return a,b
#Invoke the function with any interger at its argument.
number=int(input("ingrese un numero: "))
print(previous_next(number)) |
8733e32ae529b1f56f1931d019a70f78ac018ab4 | daru23/my-py-challenges | /finding-percentage.py | 1,267 | 4.1875 | 4 | """
You have a record of N students. Each record contains the student's name, and their percent marks in Maths,
Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names
and marks for N students. You are required to save the record in a dictionary data type. The user then enters
a student's name. Output the average percentage marks obtained by that student, correct to two decimal places.
Input Format
The first line contains the integer N, the number of students. The next N lines contains the name and marks
obtained by that student separated by a space. The final line contains the name of a particular student
previously listed.
Constraints
2 <= N <= 10
0 <= Marks <= 100
Output Format
Print one line: The average of the marks obtained by the particular student correct to 2 decimal places.
"""
if __name__ == '__main__':
n = int(raw_input())
student_marks = {}
for _ in range(n):
line = raw_input().split()
name, scores = line[0], line[1:]
scores = map(float, scores)
student_marks[name] = scores
query_name = raw_input()
avg = reduce(lambda x, y: x + y, student_marks[query_name]) / len(student_marks[query_name])
print("%.2f" % round(avg, 2))
|
27b07cd82570d10e98c5672e1e57f9101f35f31c | markdioszegi/SIW1 | /SIW1/Set A/riskDice.py | 1,882 | 3.765625 | 4 | import random
attackerRolls = []
defenderRolls = []
defLost = 0
atkLost = 0
def printStatus():
print("Dice:")
print(" Attacker: ", end="")
for i in range(len(attackerRolls)):
if i == len(attackerRolls) - 1:
print("{}".format(attackerRolls[i]))
else:
print("{}-".format(attackerRolls[i]), end="")
print(" Defender: ", end="")
for i in range(len(defenderRolls)):
if i == len(defenderRolls) - 1:
print("{}".format(defenderRolls[i]))
else:
print("{}-".format(defenderRolls[i]), end="")
def printOutcome():
print("Outcome:")
print(" Attacker: lost {} units".format(atkLost))
print(" Defender: lost {} units".format(defLost))
def battle():
global defLost, atkLost
min = len(attackerRolls)
if len(attackerRolls) > len(defenderRolls):
min = len(defenderRolls)
for i in range(min):
if attackerRolls[i] > defenderRolls[i]:
defLost += 1
else:
atkLost += 1
def setup():
attackers = input("How many units attack: ")
defenders = input("How many units defend: ")
while not(attackers.isnumeric()) or not(defenders.isnumeric()):
attackers = input("How many units attack: ")
defenders = input("How many units defend: ")
attackers = int(attackers)
defenders = int(defenders)
while (attackers > 3 or attackers < 1) or (defenders > 2 or defenders < 1):
print("Retry please!")
attackers = int(input("How many units attack: "))
defenders = int(input("How many units defend: "))
for i in range(attackers):
attackerRolls.append(random.randrange(1,7))
for i in range(defenders):
defenderRolls.append(random.randrange(1,7))
setup()
printStatus()
battle()
printOutcome() |
e3678a7a4ed50080b2464edee95f0953d2524453 | markdioszegi/SIW1 | /SIW1/Set D/TriangleArea.py | 1,493 | 3.859375 | 4 | import math
def inputSides():
vertices = []
temp = []
j = 0
for i in range(3):
#print("Lefut {}".format(i))
while j < 2:
j += 1
vertex = input("{}. coordinate {}. vertex: ".format(i + 1, j))
try:
vertex = int(vertex)
if vertex > 100 or vertex < -100:
print("Too high/low number!")
j -= 1
else:
temp.append(vertex)
except:
print("Try again!")
j -= 1
vertices.append(temp)
temp = []
j = 0
#print(vertices)
return vertices
def calcSides(coords):
tmp = []
a = math.sqrt(pow(coords[0][0] - coords[1][0], 2) + pow(coords[0][1] - coords[1][1], 2))
b = math.sqrt(pow(coords[1][0] - coords[2][0], 2) + pow(coords[1][1] - coords[2][1], 2))
c = math.sqrt(pow(coords[0][0] - coords[2][0], 2) + pow(coords[0][1] - coords[2][1], 2))
tmp.extend((a, b, c))
return tmp
def calcArea(sides):
s = (sides[0] + sides[1] + sides[2]) / 2
area = math.sqrt(s * (s - sides[0]) * (s - sides[1]) * (s - sides[2]))
print(s)
#area =
result = round(area, 1)
if result.is_integer():
return int(result)
else:
return result
coordinates = inputSides()
sides = calcSides(coordinates)
area = calcArea(sides)
#print(coordinates)
#print(sides)
print(area) |
225331f74a4cb44b5abd3bada064c752599ae0a7 | stevenphan01/AI | /POS Tagging/baseline.py | 1,480 | 3.515625 | 4 | """
Part 1: Simple baseline that only uses word statistics to predict tags
"""
'''
input: training data (list of sentences, with tags on the words)
test data (list of sentences, no tags on the words)
output: list of sentences, each sentence is a list of (word,tag) pairs.
E.g., [[(word1, tag1), (word2, tag2)], [(word3, tag3), (word4, tag4)]]
'''
def baseline(train, test):
words = {} #nested dicionary {word1: tags: {}, word2: tags: {}...}
tags = {}
predicted =[]
for sentence in train:
for word, tag in sentence:
if word not in words:
words[word] = {}
words[word][tag] = 1
else:
if tag not in words[word].keys():
words[word][tag] = 1
else:
words[word][tag] += 1
if tag not in tags:
tags[tag] = 1
else:
tags[tag] += 1
best_tag = findMax(tags)
for sentence in test:
temp = []
for word in sentence:
if word not in words:
temp.append((word, best_tag))
else:
temp.append((word, findMax(words[word])))
predicted.append(temp)
return predicted
def findMax(d):
curr_max = -1
best = ""
for key, val in d.items():
if val > curr_max:
curr_max = val
best = key
return best
|
fe65c908b996f120a7259f7673e131c246654398 | nguyenhuy1209/steganography2021 | /NguyenGiaHuy-OnQuanAn-TranNguyenHuan-Asm1/steganography.py | 5,825 | 3.859375 | 4 | import math as mt
import cv2 # pip install opencv-python
import numpy as np
import random
def primeNum(num, lis):
"""
This function takes:
- num: a number to be checked if it is a prime number or not.
- lst: a list of known prime number, for convenience.
Returns:
- True: if the input number is a prime number, False if otherwise
"""
if not lis:
return True
for i in range(len(lis)):
if num % lis[i] == 0:
return False
for i in range(len(lis), mt.floor(mt.sqrt(num)), 2):
if num % i == 0:
return False
return True
def getRandomQuadraticResidues(prime, alpha):
"""
This function takes:
- prime: the prime number
- alpha: the alpha number
Returns:
- a list of quadratic residues.
"""
lst = []
for i in range(prime // 2):
lst.append((i + alpha) ** 2 % prime)
return lst[0:-alpha+1]
def getAlphaAndPrime(mess_length):
"""
This function takes:
- mess_length: the length of the message needed to find out the appropriate prime, alpha number.
Returns:
- alpha: the appropriate alpha number for the message length.
- prime: the appropriate prime number for the message length.
"""
prime_list = []
prime = 0
alpha = 0
prime_list.append(2)
for i in range(3, 3 * mess_length, 2):
if primeNum(i, prime_list): # lis = list of prime < 3*req_pixels
prime_list.append(i)
for num in prime_list:
if 2 * mess_length <= num:
prime = num
break
alpha = mt.ceil(np.sqrt(prime))
prime = (mess_length + alpha) * 2
for num in prime_list:
if prime < num:
prime = num
break
return alpha, prime
def Encode(src, dest, message):
"""
This function takes:
- src: source directory of the cover image
- dest: destination directory of the decoded image
- message: message needs to be hidden
And encode the message to the new outputed image in PNG format.
"""
# Loading the image
img = cv2.imread(src)
rows, cols, channel = img.shape
total_pixels = img.shape[0] * img.shape[1]
# Extracting prime number and alpha value
message += 'END.'
b_message = ''.join([format(ord(i), '08b') for i in message])
req_pixels = len(b_message)
alpha, prime = getAlphaAndPrime(req_pixels)
# Encoding prime and alpha at the end of the image
key = str(prime) + ',' + str(alpha) + '#'
b_key = ''.join([format(ord(i), '08b') for i in key])
index = 0
for i in range(rows)[::-1]:
for j in range(cols)[::-1]:
if index < len(b_key):
img[i][j][0] = int(format(img[i][j][0], '08b')[:7] + b_key[index], 2)
index += 1
# Encoding message to the image
pixels_list = getRandomQuadraticResidues(prime, alpha)
pixels_list = [(index//cols, index%cols) for index in pixels_list]
if req_pixels > total_pixels:
print('ERROR: Need larger file size')
else:
index = 0
for p in pixels_list:
i, j = p
if index < req_pixels:
img[i][j][0] = int(format(img[i][j][0], '08b')[:7] + b_message[index], 2)
index += 1
cv2.imwrite(dest, img)
print('Successfully encoded message!')
print('Encoded image is stored as:', dest)
def Decode(src):
"""
This function takes:
- src: source directory of the cover image
And print the message from the image if found any.
"""
# Loading the image
img = cv2.imread(src)
rows, cols, channel = img.shape
# Extracting key and alpha
prime = 0
alpha = 0
hidden_key_bits = ''
hidden_key = ''
bit_counter = 0
for i in range(rows)[::-1]:
for j in range(cols)[::-1]:
hidden_key_bits += (bin(img[i][j][0])[2:][-1])
bit_counter += 1
if bit_counter == 8:
letter = chr(int(hidden_key_bits[-8:], 2))
hidden_key += letter
if letter == '#':
break
bit_counter = 0
hidden_key = hidden_key[:-1].split(',')
if len(hidden_key) == 2:
prime = int(hidden_key[0])
alpha = int(hidden_key[1])
else:
print('Cannot extract prime number key and alpha.')
return
# Extract message
hidden_bits = ""
pixels_list = getRandomQuadraticResidues(prime, alpha)
pixels_list = [(index//cols, index%cols) for index in pixels_list]
for p in pixels_list:
i, j = p
hidden_bits += (bin(img[i][j][0])[2:][-1])
hidden_bits = [hidden_bits[i:i+8] for i in range(0, len(hidden_bits), 8)]
message = ''
for i in range(len(hidden_bits)):
if message[-4:] == 'END.':
break
else:
message += chr(int(hidden_bits[i], 2))
if 'END.' in message:
print(f'Hidden Message: {message[:-4]}')
else:
print('No hidden message found!')
if __name__ == '__main__':
# print('1. Encode')
# print('2. Decode')
# prompt = input('Do you want to encode or decode? ')
# if prompt == '1':
# print('Please type in the cover image:')
# src = input()
# print('Please type in the message:')
# mess = input()
# filename = src.split('.')[0]
# dest = filename + '_encoded.png'
# Encode(src, dest, mess)
# elif prompt == '2':
# print('Please type in the image you wish to decode:')
# src = input()
# Decode(src)
# else:
# print('Invalid option.')
# Encrypt message
Encode('./cat.png', './cat_encoded.png', 'TranNguyenHuan-NguyenGiaHuy-OnQuanAn')
# Decrypt message
Decode('./cat_encoded.png')
|
e441d23235c744a5b2d20d239307ddf4d13f3b63 | evelandy/text-based-temperature-Converter | /tempConverter.py | 2,067 | 4.3125 | 4 | #!/usr/bin/env python3
"""evelandy/W.G.
Nov. 29 2018 7:16pm
text-based-temperature-converter
Python36-32
"""
def celsius(fahr):
return "{} degrees fahrenheit converted is {} degrees celsius".format(temp, int((5 / 9) * (fahr - 32)))
def fahrenheit(cel):
return "{} degrees celsius converted is {} degrees fahrenheit".format(temp, round((9 / 5) * cel + 32, 2))
while True:
try:
temp = float(input("\nWhat is the temperature you want to convert? "))
print("What would you like to convert your temperature to?\nF) Fahrenheit\nC) Celsius")
choice = input(": ")
if choice.lower() == 'f':
print(fahrenheit(temp))
print("Would you like to check another temperature?\nY) Yes\nN) No")
ans = input(": ")
if ans.lower() == 'y' or ans.lower() == 'yes':
continue
elif ans.lower() == 'n' or ans.lower() == 'no':
print("Thank you, please come back soon!")
break
elif ans.lower() != 'y' or ans.lower() != 'yes' and ans.lower() != 'n' or ans.lower() != 'no':
print("Sorry that's not a valid choice... Terminating...")
break
elif choice.lower() == 'c':
print(celsius(temp))
print("Would you like to check another temperature?\nY) Yes\nN) No")
ans = input(": ")
if ans.lower() == 'y' or ans.lower() == 'yes':
continue
elif ans.lower() == 'n' or ans.lower() == 'no':
print("Thank you, please come back soon!")
break
elif ans.lower() != 'y' or ans.lower() != 'yes' and ans.lower() != 'n' or ans.lower() != 'no':
print("Sorry that's not a valid choice... Terminating...")
break
else:
print("The ONLY choices are:\nF) for Fahrenheit, and \nC) for Celsius \nPLEASE choose one of those...")
except ValueError:
print("\nA letter is NOT a temperature, Please enter digit values for the temperature\n")
|
21f6a088fde24a0efd2fcb525c4b34726984f53f | BenjaminSmithOregon/DungeonGame | /character.py | 2,671 | 3.71875 | 4 | class Archer(object):
def __init__(self, name, weapon, armor, hitpoints = 75):
self.name = name
self.weapon = weapon
self.armor = armor
self.type = "archer"
self.hitpoints = hitpoints
def pickUpWeapon(self, weapon):
if weapon.damage >= self.weapon.damage:
if weapon.weapon in ("bow", "long bow", "cross bow"):
print "\nYou pick up the enemy's %s" % weapon.weapon
self.weapon = weapon
else:
print "You can not use the %s, since you don't posses the skills to use it." % weapon.weapon
else:
print "You decide to leave the %s there as it is inferior to your %s" % (weapon.weapon, self.weapon.weapon)
def pickUpArmor(self, armor):
if self.armor.protection < armor.protection:
print "\nYou pick up the enemy's %s" % self.armor.armor
self.armor = armor
else:
print "Your armor is superior to the enemy's armor, so you leave it there."
class Swordsman(object):
def __init__(self, name, weapon, armor, hitpoints = 100):
self.name = name
self.weapon = weapon
self.armor = armor
self.type = "swordsman"
self.hitpoints = hitpoints
def pickUpWeapon(self, weapon):
if weapon.damage >= self.weapon.damage:
if weapon.weapon in ("sword", "short sword", "long sword"):
print "\nYou pick up the enemy's %s" % weapon.weapon
self.weapon = weapon
else:
print "You can not use the %s, since you don't posses the skills to use it." % weapon.weapon
else:
print "You decide to leave the %s there as it is inferior to your %s" % (weapon.weapon, self.weapon.weapon)
def pickUpArmor(self, armor):
if self.armor.protection < armor.protection:
print "\nYou pick up the enemy's %s" % self.armor.armor
self.armor = armor
else:
print "Your armor is superior to the enemy's armor, so you leave it there."
class Thief(object):
def __init__(self, name, weapon, armor, hitpoints = 50):
self.name = name
self.weapon = weapon
self.armor = armor
self.type = "thief"
self.hitpoints = hitpoints
def pickUpWeapon(self, weapon):
if weapon.damage >= self.weapon.damage:
if weapon.weapon in ("blow gun", "dagger", "throwing knives"):
print "\nYou pick up the enemy's %s" % weapon.weapon
self.weapon = weapon
else:
print "You can not use the %s, since you don't posses the skills to use it." % weapon.weapon
else:
print "You decide to leave the %s there as it is inferior to your %s" % (weapon.weapon, self.weapon.weapon)
def pickUpArmor(self, armor):
if self.armor.protection < armor.protection:
print "\nYou pick up the enemy's %s" % self.armor.armor
self.armor = armor
else:
print "Your armor is superior to the enemy's armor, so you leave it there."
|
89c31917890b2174b420b01b592fa16bf8e79f7c | edgardoruiz/-FD-_Tareas_de_clases_en_Python_00170019 | /Suma.py | 180 | 3.796875 | 4 |
n = int(input("Ingrese el valor de n:"))
x = int(input("Ingrese el valor de x:"))
m = int(input("Ingrese el valor de m:"))
suma = n + x + m
print('El resultado es: ')
print (suma) |
5824c18167c351b05df91e902a3cc8d833cec98b | hello2655/pw | /pw.py | 229 | 3.71875 | 4 | t = 3
while t > 0 :
pw = input('請輸入密碼')
if pw == 'a123456':
print('登入成功')
break
else:
t = t - 1
if t == 0:
print('沒機會了,再見')
break
print('密碼錯誤!還有' , t , '次機會') |
26c7ace59a7074f0584cd63e7f21eedc2159579e | ephreal/CS | /searching/python/binary_search.py | 549 | 4.21875 | 4 | def binary_search(search_list, target):
""""
An implementation of a binary search in python.
Returns the index in the list if the item is found. Returns None
if not.
"""
first = 0
last = len(search_list) - 1
while first <= last:
midpoint = (first + last) // 2
if search_list[midpoint] == target:
return midpoint
elif search_list[midpoint] < target:
first = midpoint + 1
elif search_list[midpoint] > target:
last = midpoint - 1
return None
|
7bca549a99ffd9472bbdf296219f1966ff115c49 | ephreal/CS | /searching/python/linear_search.py | 231 | 3.921875 | 4 | def linear_search(searchable_list, target):
"""
Basic linear search implemented in python
"""
for i in range(0, len(searchable_list)):
if searchable_list[i] == target:
return i
return None
|
7b6fe96f27ba9f04072a9c81eb1afaf9b13a4717 | tristaaa/lcproblems | /adddigits.py | 679 | 3.953125 | 4 | class Solution:
def addDigits(self, num):
"""
Digit root problem: return the digit root of the input number
Ex: for number 456, the digit root is 6 (4+5+6=15, 1+5=6)
:type num: int
:rtype: int
"""
# for base b, in this case b=10, the digit root of an integer n:
# dr(n)=0 if n==0
# dr(n)=b-1 if n!=0 and n%(b-1)==0
# dr(n)=n%(b-1) if n!=0 and n%(b-1)!=0
# or generally, dr(n) = 1+(n-1)%(b-1)
# For python the mod performs a little bit differently,
# for -a % b(a>0,b>0), the result is b - (a%b)
return 1 + (num-1) % 9 if num>0 else 0 |
ea07d1d759cadfaba46d5da196c900a5a0640cde | tristaaa/lcproblems | /shortestworddis.py | 1,142 | 4 | 4 | class Solution:
def shortestDistance(self, words, word1, word2):
"""
Given a list of words and two words word1 and word2,
Return the shortest distance between these two words in the list.
word1 does not equal to word2, and word1 and word2 are both in the list
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
pos1,pos2=-1,-1
shortestDis=len(words)
for i in range(len(words)):
if words[i] == word1:
pos1=i
if pos2!=-1 and pos1-pos2<shortestDis:
shortestDis = pos1-pos2
elif words[i] == word2:
pos2=i
if pos1!=-1 and pos2-pos1<shortestDis:
shortestDis = pos2-pos1
return shortestDis
sol = Solution()
words = ["practice", "makes", "perfect", "coding", "makes"]
word1,word2 = "makes","coding"
print("the shortest distance of two words: %s and %s in the list: %s is: %d" % (word1,word2,words,sol.shortestDistance(words, word1, word2)))
|
7740f5e7220dea05195d0ab85dcf6f857cc8812d | tristaaa/lcproblems | /findcelebrity.py | 1,759 | 3.765625 | 4 | def knows(a,b):
"""return True when a knows b, else return False"""
return adj[a][b]==1
class Solution:
def findCelebrity(self, n):
"""
Given a helper function knows, and n persons labeled 0 to n-1,
find out if there is a celebrity(he knows nobody and others all know him) in the group,
if yes, return the label; else return -1
:type n: int
:rtype: int
"""
candidate = 0
# Find the candidate.
for i in range(1, n):
if knows(candidate, i):
# Note all candidates tranverse before are not celebrity candidates.
candidate = i
# Verify the candidate.
# if the candidate knows someone or someone don't know the candidate,
# then the candidate cannot be the celebrity
for i in range(candidate):
if i != candidate and (knows(candidate, i) or not knows(i, candidate)):
return -1
# for the person labeled larger than the candidate,
# candidate must not know them, so only need to verify if they know candidate
for i in range(candidate+1,n):
if not knows(i,candidate):
return -1
return candidate
sol=Solution()
adj = [
[1,1,0],
[0,1,0],
[0,1,1]
]
print("given the following group of persons:")
def printAdj(adj):
n=len(adj)
for i in range(n):
for j in range(n):
if adj[i][j]:
print("person %d knows person %d" % (i,j))
else:
print("person %d doesn't know person %d" % (i,j))
printAdj(adj)
print("the group of n=%d persons has a celebrity labeled as: %d(-1 means no celebrity)" % (len(adj), sol.findCelebrity(len(adj))))
|
c2e114cef247fb27f958354c3f0c7dd0fa35c0c9 | tristaaa/lcproblems | /shtbridge.py | 2,261 | 3.671875 | 4 | class Solution:
def shortestBridge(self, A):
"""
In a given 2D binary array A, there are two islands.
(An island is a 4-directionally connected group of ones which are not connected to any other ones.)
Now, we may change 0s to 1s so as to connect the two islands together to form one island.
Return the smallest number of 0s that must be flipped.
(It is guaranteed that the answer is at least 1.)
"""
from collections import deque
def dfs(A,i,j,q):
A[i][j]=2
q.append((i,j))
for d in dirs:
x,y = i+d[0],j+d[1]
if 0<=x<m and 0<=y<n and A[x][y]==1:
dfs(A,x,y,q)
m,n = len(A),len(A[0])
dirs=[(0,1),(0,-1),(1,0),(-1,0)]
q = deque()
# using dfs to find one island, and mark it as 2 (already visited)
found=0
for i in range(m):
for j in range(n):
if A[i][j]==1:
dfs(A,i,j,q)
found=1
break
if found: break
# print("mark one island as 2: ",A)
step = 0
# using bfs to expand the marked island
while q:
size=len(q)
for i in range(size):
cell=q.popleft()
for d in dirs:
x,y = cell[0]+d[0],cell[1]+d[1]
if 0<=x<m and 0<=y<n and A[x][y]!=2:
# found another island
if A[x][y]==1: return step
# the neighbor is still water, A[x][y]==0
q.append((x,y))
A[x][y]=2
step+=1
return step
sol = Solution()
A = [[0,0,0,0,0],
[0,0,1,1,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,1,1,1,0]]
print("Given the map where indicates the location of two islands, 1 represents the land, 0 represents the sea")
print("an island is a 4-directionally connected group of ones which are not connected to any other ones")
print("["+str(A[0]))
for i in A[1:-1]:
print(str(i)+",")
print(str(A[-1])+"]")
print("the shortest length of a bridge that connects the two islands is: ",sol.shortestBridge(A))
|
e8e8fb2bea332103e6163954db83dd33f33fb119 | tristaaa/lcproblems | /addtwonumBitOps.py | 1,803 | 3.6875 | 4 | class Solution(object):
def getSum(self, a, b):
"""
add two numbers without using +,- operations
Bit manipulation.
:type a: int
:type b: int
:rtype: int
"""
# Since Python simulates an infinite-bit representation, not 32-bit or 64-bit
# Ex. bin(-6) actually represented as 0b1...111111111010
# (infinite string of sign bits) 计算机系统中,数值均由其补码(2's complement)表示和存储
# Thus to simulate a 32-bit representation, we need a mask to get the last 32 bits
# 32 bits integer max(using the first bit as sign)
MAX = 0x7FFFFFFF
# mask to get last 32 bits
mask = 0xFFFFFFFF
while b != 0:
# ^ simulate addition, but lose the info of carry
# & discover both 1s positions, where indicate the next position with a carry
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
# if the summation is negative (whereas the `a` appears to be an positive number,
# since we just keep the last 32 bits, i.e. the first sign bit is identified as regular bit)
# Eg. if a=-3 actually, we now represent it as in 32-bit form, which shows that a is 4294967293(2**32-abs(a)), which is the a's positive complement
# and we eventually need to convert it to infinite-bit representation, we just need to add infinite 1s before our current result
# Thus, we need first get `a`'s 32 bits 1's complement positive(对32位的a按位取反)
# then get 32-bit positive's Python 1's complement negative
return a if a <= MAX else ~(a ^ mask)
# test
a,b=-5,3
sol = Solution()
print("a= %d, b= %d, the summation of a and b= %d" % (a,b,sol.getSum(a,b))) |
e84cf7eea4c02a04fd4b72972193934f77332bb6 | tristaaa/lcproblems | /maxstack.py | 1,780 | 4.09375 | 4 | class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.maxstack=[]
self.maxvals=[]
def push(self, x):
'''Push element x onto stack.'''
if not self.maxvals or x>=self.maxvals[-1][1]:
self.maxvals.append((len(self.maxstack),x))
self.maxstack.append(x)
def pop(self):
'''Remove the element on top of the stack and return it.'''
curr = self.maxstack.pop()
if curr==self.maxvals[-1][1]:
self.maxvals.pop()
return curr
def top(self):
'''Get the element on the top.'''
return self.maxstack[-1]
def peekMax(self):
'''Retrieve the maximum element in the stack.'''
return self.maxvals[-1][1]
def popMax(self):
'''Retrieve the maximum element in the stack, and remove it.
If you find more than one maximum elements, only remove the top-most one.'''
# O(n)
pos,curmax = self.maxvals.pop()
if self.top()!=curmax:
for i in range(pos,len(self.maxstack)-1):
self.maxstack[i]=self.maxstack[i+1]
if not self.maxvals or self.maxstack[i]>=self.maxvals[-1][1]:
self.maxvals.append((i,self.maxstack[i]))
self.maxstack.pop()
return curmax
# Note the functions other than `push` won't be called when stack is empty.
# Your MaxStack object will be instantiated and called as such:
obj = MaxStack()
obj.push(5)
obj.push(1)
obj.push(5)
param_1 = obj.top() # return 5
param_2 = obj.popMax() # return 5
param_3 = obj.top() # return 1
param_4 = obj.peekMax() # return 5
param_5 = obj.pop() # reutnr 1
param_5 = obj.top() # return 5
|
eb5b7e6fe9938a9cef72d206e8ed06292e86cc84 | tristaaa/lcproblems | /containdup.py | 583 | 3.90625 | 4 | class Solution:
def containsDuplicate(self, nums):
"""
Given an array of integers, find if the array contains any duplicates.
return true if any value appears at least twice
type nums: List[int]
rtype: bool
"""
seen=set()
flag=False
for num in nums:
if num not in seen:
seen.add(num)
else:
flag=True
return flag
sol = Solution()
nums=[1,2,3,1]
print("the given array: %s contains duplicate numbers: %s" % (nums,sol.containsDuplicate(nums)))
|
a83c3362a529d970c8d74dc9a41e928ad7f6aa12 | tristaaa/lcproblems | /mysortmat.py | 1,274 | 3.578125 | 4 | class Solution(object):
def mySortMat(self, mat):
"""
sort the input matrix, size of n*n, and the output should be in this order
[[9,8,6],
[7,5,3],
[4,2,1]]
:type mat: List[List[int]]
:rtype: List[List[int]]
"""
n = len(mat)
arr = []
for i in range(n):
arr+=mat[i]
arr.sort(reverse=True)
# print(arr)
result=[[0]*n for i in range(n)]
for i in range(n):
fn=i*(i+1)//2
if i!=n-1:
for j in range(i+1):
result[j][i-j] = arr[fn+j]
result[n-1-j][n-1-i+j] = arr[n*n-1-fn-j]
else:
for j in range(i//2+1):
result[j][i-j] = arr[fn+j]
result[n-1-j][n-1-i+j] = arr[n*n-1-fn-j]
return result
sol=Solution()
mat=[
[ 5, 1, 9, 11],
[ 2, 4, 8, 10],
[13, 3, 6, 7],
[15, 14, 12, 0]
]
mat1=[
[ 5, 1, 9],
[ 2, 4, 8],
[13, 3, 6]
]
print("Given the input matrix: [")
for i in range(len(mat)):
print(mat[i])
print("]")
print("the sorted matrix is: [")
res=sol.mySortMat(mat)
for i in range(len(res)):
print(res[i])
print("]")
print("Given the input matrix: [")
for i in range(len(mat1)):
print(mat1[i])
print("]")
print("the sorted matrix is: [")
res=sol.mySortMat(mat1)
for i in range(len(res)):
print(res[i])
print("]")
|
39263492a05a0151d376082385fd545e271237ec | tristaaa/lcproblems | /paintboard.py | 2,249 | 3.859375 | 4 |
# 小Q拿出了一块有NxM像素格的画板, 画板初始状态是空白的,用'X'表示。
# 每次小Q会选择一条斜线, 如果斜线的方向形如'/',小Q会选择这条斜线中的一段格子,都涂画为蓝色,用'B'表示;
# 如果对角线的方向形如'\',小Q会选择这条斜线中的一段格子,都涂画为黄色,用'Y'表示。
# 如果一个格子既被蓝色涂画过又被黄色涂画过,那么这个格子就会变成绿色,用'G'表示。
# 小Q已经有想画出的作品的样子, 请你帮他计算一下他最少需要多少次操作完成这幅画。
def getMinStep(n,m,board):
"""
get the minimum steps to complete the board
:type n: int, number of rows of the board, 1<=n<=50
:type m: int, number of columns of the board, 1<=m<=50
:type board: List[String], final version of the board, each char in string can be 'b','y','g','x'
:rtype: int
"""
step=0
for i in range(n):
for j in range(m):
if board[i][j]=='Y':
paintY(i,j,n,m,board)
step+=1
elif board[i][j]=='B':
paintB(i,j,n,m,board)
step+=1
elif board[i][j]=='G':
paintY(i,j,n,m,board)
paintB(i,j,n,m,board)
step+=2
return step
def paintY(i,j,n,m,board):
if 0<=i<n and 0<=j<m and (board[i][j]=='Y' or board[i][j]=='G'):
if board[i][j]=='Y': board[i][j]='X'
else: board[i][j]='B'
paintY(i-1,j-1,n,m,board)
paintY(i+1,j+1,n,m,board)
def paintB(i,j,n,m,board):
if 0<=i<n and 0<=j<m and (board[i][j]=='B' or board[i][j]=='G'):
if board[i][j]=='B': board[i][j]='X'
else: board[i][j]='Y'
paintB(i+1,j-1,n,m,board)
paintB(i-1,j+1,n,m,board)
# input will be like (first row:n,m; following rows: the final version of the board):
# 4 4
# YXXB
# XYGX
# XBYY
# BXXY
# expected output: 3
n,m=map(int,input("please input the number of rows(n) and columns(m) of the board: n m=").split())
print("And given the final version of the board:")
board=[]
for i in range(n):
board.append(list(input()))
print("\nThe minimum steps to complete the painting will be: %d" % (getMinStep(n,m,board)))
|
32d673c9ca22a4d74c7671b269d1a971628d65eb | tristaaa/lcproblems | /shortestworddisii.py | 1,870 | 3.71875 | 4 | class WordDistance:
def __init__(self, words):
"""
:type words: List[str]
"""
self.n = len(words)
self.word2idx = {}
for i in range(self.n):
if words[i] not in self.word2idx:
self.word2idx[words[i]] = [i]
else:
self.word2idx[words[i]] += [i]
def shortest(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
# method 1, O(M*N) where M=len(word2idx[word1]) and N=len(word2idx[word2])
shortestDis = self.n
for i in self.word2idx[word1]:
for j in self.word2idx[word2]:
if abs(i-j)<shortestDis:
shortestDis = abs(i-j)
return shortestDis
# method 2, O(M+N) where M=len(word2idx[word1]) and N=len(word2idx[word2])
# using two pointers, the pointer only moves on when it points to the lower index
shortestDis = self.n
pos1,pos2 = 0,0
l1,l2 = self.word2idx[word1],word2idx[word2]
while pos1<len(l1) and pos2<len(l2):
if abs(l1[pos1]-l2[pos2])<shortestDis:
shortestDis = abs(l1[pos1]-l2[pos2])
if l1[pos1]<l2[pos2]:
pos1+=1
else:
pos2+=1
return shortestDis
words = ["practice", "makes", "perfect", "coding", "makes"]
wordDistance = WordDistance(words)
# call function
word1,word2 = "makes","coding"
shortestDis = wordDistance.shortest(word1,word2)
print("the shortest distance of two words: %s and %s in the list: %s is: %d" % (word1,word2,words,shortestDis))
# call function again
word1,word2 = "practice","coding"
shortestDis = wordDistance.shortest(word1,word2)
print("the shortest distance of two words: %s and %s in the list: %s is: %d" % (word1,word2,words,shortestDis))
|
7ffeddf503ddecf88b1aeea7e7419cff2442dc3a | EternallyMissed/practicas-python | /suma.py | 153 | 3.671875 | 4 | a = input("ingrese un numero")
b = input("ingrese otro numero")
a = int (a)
b = int (b)
c= a + b
print("la suma de los numeros ingresados es", c)
|
7f8ca8e54858853fb057e7076eed9b9c634b82b6 | PacktPublishing/The-Complete-Python-Course | /1_intro/lectures/15_dictionaries/code.py | 921 | 4.625 | 5 | friend_ages = {"Rolf": 24, "Adam": 30, "Anne": 27}
print(friend_ages["Rolf"]) # 24
# friend_ages["Bob"] ERROR
# -- Adding a new key to the dictionary --
friend_ages["Bob"] = 20
print(friend_ages) # {'Rolf': 24, 'Adam': 30, 'Anne': 27, 'Bob': 20}
# -- Modifying existing keys --
friend_ages["Rolf"] = 25
print(friend_ages) # {'Rolf': 25, 'Adam': 30, 'Anne': 27, 'Bob': 20}
# -- Lists of dictionaries --
# Imagine you have a program that stores information about your friends.
# This is the perfect place to use a list of dictionaries.
# That way you can store multiple pieces of data about each friend, all in a single variable.
friends = [
{"name": "Rolf Smith", "age": 24},
{"name": "Adam Wool", "age": 30},
{"name": "Anne Pun", "age": 27},
]
# You can turn a list of lists or tuples into a dictionary:
friends = [("Rolf", 24), ("Adam", 30), ("Anne", 27)]
friend_ages = dict(friends)
print(friend_ages)
|
8c8020d86d108df7264b3448c4f6cbfa6c6fc7a3 | PacktPublishing/The-Complete-Python-Course | /10_advanced_python/lectures/05_argument_unpacking/code.py | 2,507 | 4.90625 | 5 | """
* What is argument unpacking?
* Unpacking positional arguments
* Unpacking named arguments
* Example (below)
Given a function, like the one we just looked at to add a balance to an account:
"""
accounts = {
'checking': 1958.00,
'savings': 3695.50
}
def add_balance(amount: float, name: str) -> float:
"""Function to update the balance of an account and return the new balance."""
accounts[name] += amount
return accounts[name]
"""
Imagine we’ve got a list of transactions that we’ve downloaded from our bank page; and they look somewhat like this:
"""
transactions = [
(-180.67, 'checking'),
(-220.00, 'checking'),
(220.00, 'savings'),
(-15.70, 'checking'),
(-23.90, 'checking'),
(-13.00, 'checking'),
(1579.50, 'checking'),
(-600.50, 'checking'),
(600.50, 'savings'),
]
"""
If we now wanted to add them all to our accounts, we’d do something like this:
"""
for t in transactions:
add_balance(t[0], t[1])
"""
What we’re doing here something very specific: *passing all elements of an iterable as arguments, one by one*.
Whenever you need to do this, there’s a shorthand in Python that we can use:
"""
for t in transactions:
add_balance(*t) # passes each element of t as an argument in order
"""
In section 9 we looked at this code when we were studying `map()`:
"""
class User:
def __init__(self, username, password):
self.username = username
self.password = password
@classmethod
def from_dict(cls, data):
return cls(data['username'], data['password'])
# imagine these users are coming from a database...
users = [
{ 'username': 'rolf', 'password': '123' },
{ 'username': 'tecladoisawesome', 'password': 'youaretoo' }
]
user_objects = map(User.from_dict, users)
"""
The option of using a list comprehension is slightly uglier, I feel:
"""
user_objects = [User.from_dict(u) for u in users]
"""
Instead of having a `from_dict` method in there, we could do this, using named argument unpacking:
"""
class User:
def __init__(self, username, password):
self.username = username
self.password = password
users = [
{ 'username': 'rolf', 'password': '123' },
{ 'username': 'tecladoisawesome', 'password': 'youaretoo' }
]
user_objects = [User(**data) for data in users]
"""
If our data was not in dictionary format, we could do:
"""
users = [
('rolf', '123'),
('tecladoisawesome', 'youaretoo')
]
user_objects = [User(*data) for data in users]
|
670885f86ec8829de84b4763828e5b98af656c27 | PacktPublishing/The-Complete-Python-Course | /2_intro_to_python/lectures/12_set_dictionary_comprehensions/code.py | 859 | 3.828125 | 4 | friends = ["Rolf", "ruth", "charlie", "Jen"]
guests = ["jose", "Bob", "Rolf", "Charlie", "michael"]
friends_lower = {n.lower() for n in friends}
guests_lower = {n.lower() for n in guests}
present_friends = friends_lower.intersection(guests_lower)
present_friends = {name.capitalize() for name in friends_lower & guests_lower}
print(present_friends)
# Transforming data for easier consumption and processing is a very common task.
# Working with homogeneous data is really nice, but often you can't (e.g. when working with user input!).
# -- Dictionary comprehension --
# Works just like set comprehension, but you need to do key-value pairs.
friends = ["Rolf", "Bob", "Jen", "Anne"]
time_since_seen = [3, 7, 15, 11]
long_timers = {
friends[i]: time_since_seen[i]
for i in range(len(friends))
if time_since_seen[i] > 5
}
print(long_timers)
|
85748dc41cd9db69df420983540035e866d89a7e | PacktPublishing/The-Complete-Python-Course | /2_intro_to_python/lectures/7_else_with_loops/code.py | 591 | 4.34375 | 4 | # On loops, you can add an `else` clause. This only runs if the loop does not encounter a `break` or an error.
# That means, if the loop completes successfully, the `else` part will run.
cars = ["ok", "ok", "ok", "faulty", "ok", "ok"]
for status in cars:
if status == "faulty":
print("Stopping the production line!")
break
print(f"This car is {status}.")
else:
print("All cars built successfully. No faulty cars!")
# Remove the "faulty" and you'll see the `else` part starts running.
# Link: https://blog.tecladocode.com/python-snippet-1-more-uses-for-else/
|
533360c4d458f8e2fc579b60af0441f5ec49ec17 | PacktPublishing/The-Complete-Python-Course | /6_files/files_project/friends.py | 735 | 4.3125 | 4 | # Ask the user for a list of 3 friends
# For each friend, we'll tell the user whether they are nearby
# For each nearby friend, we'll save their name to `nearby_friends.txt`
friends = input('Enter three friend names, separated by commas (no spaces, please): ').split(',')
people = open('people.txt', 'r')
people_nearby = [line.strip() for line in people.readlines()]
people.close()
friends_set = set(friends)
people_nearby_set = set(people_nearby)
friends_nearby_set = friends_set.intersection(people_nearby_set)
nearby_friends_file = open('nearby_friends.txt', 'w')
for friend in friends_nearby_set:
print(f'{friend} is nearby! Meet up with them.')
nearby_friends_file.write(f'{friend}\n')
nearby_friends_file.close()
|
c712a62a9b104cbb2345f00b18dfdee6712d5c0c | PacktPublishing/The-Complete-Python-Course | /2_intro_to_python/lectures/15_functions/code.py | 894 | 4.3125 | 4 | # So far we've been using functions such as `print`, `len`, and `zip`.
# But we haven't learned how to create our own functions, or even how they really work.
# Let's create our own function. The building blocks are:
# def
# the name
# brackets
# colon
# any code you want, but it must be indented if you want it to run as part of the function.
def greet():
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Running this does nothing, because although we have defined a function, we haven't executed it.
# We must execute the function in order for its contents to run.
greet()
# You can put as much or as little code as you want inside a function, but prefer shorter functions over longer ones.
# You'll usually be putting code that you want to reuse inside functions.
# Any variables declared inside the function are not accessible outside it.
print(name) # ERROR!
|
8d9fb01a37256d60c8641179a5c30aec23718d75 | PacktPublishing/The-Complete-Python-Course | /7_second_milestone_project/milestone_2_lists/utils/database.py | 528 | 3.515625 | 4 | books = []
def create_book_table():
pass
def get_all_books():
return books
def insert_book(name, author):
books.append({'name': name, 'author': author, 'read': False})
def mark_book_as_read(name):
for book in books:
if book['name'] == name:
book['read'] = True
def delete_book(name):
global books
books = [book for book in books if book['name'] != name]
# def delete_book(name):
# for book in books:
# if book['name'] == name:
# books.remove(book)
|
097af9ad4ef7e67f11d0194bab1479322b6db035 | PacktPublishing/The-Complete-Python-Course | /13_async_development/sample_code/12_async_await.py | 560 | 3.59375 | 4 | from collections import deque
from types import coroutine
friends = deque(('Rolf', 'Jose', 'Charlie', 'Jen', 'Anna'))
@coroutine
def friend_upper():
while friends:
friend = friends.popleft().upper()
greeting = yield
print(f'{greeting} {friend}')
async def greet(g):
print('Starting...')
await g
print('Ending...')
greeter = greet(friend_upper())
greeter.send(None)
greeter.send('Hello')
greeting = input('Enter a greeting: ')
greeter.send(greeting)
greeting = input('Enter a greeting: ')
greeter.send(greeting)
|
fab51111c8d19f063d67d289cfeef4c9a71bb801 | PacktPublishing/The-Complete-Python-Course | /7_second_milestone_project/milestone_2_files/app.py | 1,197 | 4.1875 | 4 | from utils import database
USER_CHOICE = """
Enter:
- 'a' to add a new book
- 'l' to list all books
- 'r' to mark a book as read
- 'd' to delete a book
- 'q' to quit
Your choice: """
def menu():
database.create_book_table()
user_input = input(USER_CHOICE)
while user_input != 'q':
if user_input == 'a':
prompt_add_book()
elif user_input == 'l':
list_books()
elif user_input == 'r':
prompt_read_book()
elif user_input == 'd':
prompt_delete_book()
user_input = input(USER_CHOICE)
def prompt_add_book():
name = input('Enter the new book name: ')
author = input('Enter the new book author: ')
database.add_book(name, author)
def list_books():
for book in database.get_all_books():
read = 'YES' if book['read'] else 'NO'
print(f"{book['name']} by {book['author']} — Read: {read}")
def prompt_read_book():
name = input('Enter the name of the book you just finished reading: ')
database.mark_book_as_read(name)
def prompt_delete_book():
name = input('Enter the name of the book you wish to delete: ')
database.delete_book(name)
menu()
|
25e9c19c1f886aeec037bb941a756e6b7d9b364b | PacktPublishing/The-Complete-Python-Course | /13_async_development/projects/async_scraping/menu.py | 1,318 | 3.703125 | 4 | import logging
from app import books
logger = logging.getLogger('scraping.menu')
USER_CHOICE = '''Enter one of the following
- 'b' to look at 5-star books
- 'c' to look at the cheapest books
- 'n' to just get the next available book on the page
- 'q' to exit
Enter your choice: '''
def print_best_books():
logger.debug('Finding best books by rating...')
best_books = sorted(books, key=lambda x: x.rating * -1)[:5]
for book in best_books:
print(book)
def print_cheapest_books():
logger.debug('Finding best books by price...')
cheapest_books = sorted(books, key=lambda x: x.price)[:5]
for book in cheapest_books:
print(book)
books_generator = (x for x in books)
def get_next_book():
logger.debug('Getting next book from generator of all books...')
print(next(books_generator))
user_choices = {
'b': print_best_books,
'c': print_cheapest_books,
'n': get_next_book
}
def menu():
user_input = input(USER_CHOICE)
while user_input != 'q':
logger.debug('User did not choose to exit program.')
if user_input in ('b', 'c', 'n'):
user_choices[user_input]()
else:
print('Please choose a valid command.')
user_input = input(USER_CHOICE)
logger.debug('Terminating program...')
menu()
|
42677deb29fcb61c5aeff5b093742d97952c9e27 | PacktPublishing/The-Complete-Python-Course | /10_advanced_python/lectures/10_timing_your_code/code.py | 1,661 | 4.5 | 4 | """
As well as the `datetime` module, used to deal with objects containing both date and time, we have a `date` module and a `time` module.
Whenever you’re running some code, you can measure the start time and end time to calculate the total amount of time it took for the code to run.
It’s really straightforward:
"""
import time
def powers(limit):
return [x**2 for x in range(limit)]
start = time.time()
p = powers(5000000)
end = time.time()
print(end - start)
"""
You could of course turn this into a function:
"""
import time
def measure_runtime(func):
start = time.time()
func()
end = time.time()
print(end - start)
def powers(limit):
return [x**2 for x in range(limit)]
measure_runtime(lambda: powers(500000))
"""
Notice how the `measure_runtime` call passes a lambda function since the `measure_runtime` function does not allow us to pass arguments to the `func()` call.
This is a workaround to some other technique that we’ll look at very soon.
By the way, the `measure_runtime` function here is a higher-order function; and the `powers` function is a first-class function.
If you want to time execution of small code snippets, you can also look into the `timeit` module, designed for just that: [27.5. timeit — Measure execution time of small code snippets — Python 3.6.4 documentation](https://docs.python.org/3/library/timeit.html)
"""
import timeit
print(timeit.timeit("[x**2 for x in range(10)]"))
print(timeit.timeit("map(lambda x: x**2, range(10))"))
"""
This runs the statement a default of 10,000 times to check how long it runs for. Notice how `map()` is faster than list comprehension!
""" |
3d4847649a7ed81e4c01d5667de418b7297f11e9 | PacktPublishing/The-Complete-Python-Course | /1_intro/lectures/16_length_and_sum/code.py | 354 | 3.640625 | 4 | # Imagine you're wanting a variable that stores the grades attained by a student in their class.
# Which of these is probably not going to be a good data structure?
grades = [80, 75, 90, 100]
grades = (80, 75, 90, 100)
grades = {80, 75, 90, 100} # This one, because of no duplicates
total = sum(grades)
length = len(grades)
average = total / length
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.