blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
def301bd04c9524897496e3935cc1b319b47c3dc | fgiraudo/aoc-2019 | /Sources/2019-4.py | 1,219 | 3.671875 | 4 | import math
import os
import copy
#Change Python working directory to source file path
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
def main():
count = 0
print(is_valid(112233))
print(is_valid(123444))
print(is_valid(112223))
for password in range(256310, 732737):
if is_valid(password):
count += 1
print(count)
def is_valid(password):
digits = [int(d) for d in str(password)]
last_digit = digits.pop(0)
has_adjacent = False
adjacent_digit = None
invalid_adjacent = None
has_valid_adjacent = False
for digit in digits:
if digit < last_digit:
return False
if digit > last_digit and has_adjacent:
has_valid_adjacent = True
if digit == last_digit:
if (has_adjacent and adjacent_digit == digit) or invalid_adjacent == digit:
adjacent_digit = None
invalid_adjacent = digit
has_adjacent = False
else:
adjacent_digit = digit
has_adjacent = True
last_digit = digit
return has_adjacent or has_valid_adjacent
main() |
147c00e912fdc1a94a01fdd2b558a67eaf5db87f | jaykaneriya6143/python | /day5/overriding.py | 211 | 3.59375 | 4 | class Parent:
def fun1(self):
print("This method is parent.......")
class Child(Parent):
def fun1(self):
print("This method is child.......")
c1 = Child()
c1.fun1() |
3f3241fe77bdc53edde180117cf4a7943f363411 | jaykaneriya6143/python | /day2/jk5.py | 142 | 3.78125 | 4 | name = "jay kaneriya"
print("Name is :",name)
print(name[0])
print (name[2:5])
print(name[2:])
print(name * 2)
print(name + "Hello") |
85361ac8a3ba55f2cbe9f0420c48f81dfe0127fb | DRV1726018/vehicle-testing | /gui-alpha/gui.py | 17,628 | 3.671875 | 4 | import math
import tkinter as tk
from tkinter import Label, ttk
from tkinter import font
from PIL import ImageTk,Image
from tkinter import filedialog
from tkinter import *
root = tk.Tk()
root.title("Centro de Gravedad")
root.geometry("1000x600")
root.iconbitmap(file="carro.ico")
#Panel para las pestañas
nb = ttk.Notebook(root)
nb.pack(fill="both", expand="yes")
#Pestañas
p1 = ttk.Frame(nb)
p2 = ttk.Frame(nb)
p3 = ttk.Frame(nb)
nb.add(p1, text = "Registro de Operarios")
nb.add(p2, text = "Datos del Vehiculo")
nb.add(p3, text = "Calculo del Centro de Gravedad")
#Pestaña 1
#Funciones de la pestaña 1
def ingresar_operario_uno(registrar):
print("El operario uno es: ", registrar)
def ingresar_operario_dos(registrar):
print("La operario dos es: ", registrar)
label = tk.Label(p1, text="Registro de los Operarios", font=40)
label.place(relx=0.5, rely=0, relwidth=0.75, relheight=0.4, anchor="n" )
label2 = tk.Label(p1, text="Operario 1", font=40)
label2.place(relx=0.3, rely=0.3, relwidth=0.4, relheight=0.1, anchor="n")
label3 = tk.Label(p1, text="Operario 2", font=40)
label3.place(relx=0.3, rely=0.5, relwidth=0.4, relheight=0.1, anchor="n")
operario_uno = tk.Entry(p1, font=40)
operario_uno.place(relx=0.5, rely=0.3, relwidth=0.4, relheight=0.1)
operario_dos = tk.Entry(p1, font=40)
operario_dos.place(relx=0.5, rely=0.5, relwidth=0.4, relheight=0.1)
registro = Button(p1, text="Registrar", command=lambda: [ingresar_operario_uno(operario_uno.get()),ingresar_operario_dos(operario_dos.get())])
registro.place(relx=0.35, rely=0.8, relwidth=0.3, relheight=0.1)
#Pestaña 2
#Funciones de la pestaña 2
def imagen_carro():
global my_image
root.filename = filedialog.askopenfilename(initialdir="C:/Users/David Ramírez/Desktop/CDG", title="Upload the car image")
my_label = Label(p2, text=root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
my_label_image = Label(image=my_image).pack()
def ingresar_matricula(registro):
return print("La matricula del vehículo es: ", registro)
def ingresar_fecha(registro):
return print("La fecha del ensayo es: ", registro)
#Seleccionar la foto del vehiculo
texto_carro = tk.Label(p2, text="Ingrese la foto del Vehículo",font="20",)
texto_carro.place(relx=0.1, rely=0.6, relwidth=0.5, relheight=0.1)
btn_imagen_carro = Button(p2, text="Open File", command=imagen_carro)
btn_imagen_carro.place(relx=0.65, rely=0.6, relwidth=0.3, relheight=0.1)
#Ingresar la matricula del vehiculo
texto_matricula = tk.Label(p2,text="Ingrese la matricula del vehículo", font=40)
texto_matricula.place(relx=0.1, rely=0.4, relwidth=0.5, relheight=0.1)
ent_matricula = tk.Entry(p2, font=40 )
ent_matricula.place(relx=0.65, rely=0.4, relwidth=0.3, relheight=0.1)
#Ingresar la fecha del ensayo.
texto_fecha = tk.Label(p2,text="Ingrese la fecha", font=40)
texto_fecha.place(relx=0.1, rely=0.2, relwidth=0.5, relheight=0.1)
ent_fecha = tk.Entry(p2, font=40 )
ent_fecha.place(relx=0.65, rely=0.2, relwidth=0.3, relheight=0.1)
#Boton para aceptar
registrar = Button(p2, text="Registrar", command=lambda: [ingresar_matricula(ent_matricula.get()),ingresar_fecha(ent_fecha.get())])
registrar.place(relx=0.4, rely=0.8, relwidth=0.3, relheight=0.1)
#Pestaña 3
def get_lift_height(calcular_centro_de_gravedad):
"""Get lift height from user input in mm"""
return print("Please enter the lift height in mm: ",calcular_centro_de_gravedad)
def get_left_wheelbase(calcular_centro_de_gravedad):
"""Get left wheelbase from user input in mm."""
return print("Please enter the left wheelbase in mm: ",calcular_centro_de_gravedad)
def get_right_wheelbase(calcular_centro_de_gravedad):
"""Get right wheelbase from user input in mm."""
return print("Please enter the right wheelbase in mm: ",calcular_centro_de_gravedad)
def get_mean_wheelbase(left_wheelbase, right_wheelbase):
"""Return mean wheelbase from vehicle's left and right wheelbases in mm.
Arguments:
left_wheelbase -- vehicle's left wheelbase in mm.
right_wheelbase -- vehicle's right wheelbase in mm.
Return values:
The mean vehicle wheelbase.
"""
return (left_wheelbase + right_wheelbase) / 2
def get_rear_track(calcular_centro_de_gravedad):
"""Return vehicle rear track from user input in mm."""
return print("Please enter vehicle rear track in mm: ", calcular_centro_de_gravedad)
def get_front_track(calcular_centro_de_gravedad):
"""Return vehicle front track from user input in mm."""
return print("Please enter vehicle front track in mm: ", calcular_centro_de_gravedad)
def get_wheel_diameter(calcular_centro_de_gravedad):
"""Get lifted vehicle wheel diameter from user input in mm."""
return print("Please enter lifted vehicle wheel diameter in mm: ", calcular_centro_de_gravedad)
def get_flattened_wheel_diameter(calcular_centro_de_gravedad):
"""Get lifted vehicle flattened wheel diameter from user input in mm."""
return print("Please enter lifted vehicle flattened wheel diameter in mm: ", calcular_centro_de_gravedad)
def get_static_wheel_radius(wheel_diameter, flattened_wheel_diameter):
"""Return static wheel radius.
Arguments:
wheel_diameter -- lifted vehicle wheel_diameter in mm
flattened_wheel_diameter -- lifted vehicle flattened_wheel_diameter in mm
Return values:
The static wheel radius in mm.
"""
return flattened_wheel_diameter - (wheel_diameter / 2)
def get_rear_left_wheel_mass(calcular_centro_de_gravedad):
"""Get rear left wheel mass from user input in kg."""
return print("Please enter the rear left wheel mass in kg: ", calcular_centro_de_gravedad)
def get_rear_right_wheel_mass(calcular_centro_de_gravedad):
"""Get rear right wheel mass from user input in kg."""
return print("Please enter the rear right wheel mass in kg: ", calcular_centro_de_gravedad)
def get_front_left_wheel_mass(calcular_centro_de_gravedad):
"""Get front left wheel mass from user input in kg."""
return print("Please enter the front left wheel mass in kg: ", calcular_centro_de_gravedad)
def get_front_right_wheel_mass(calcular_centro_de_gravedad):
"""Get front right wheel mass from user input in kg."""
return print("Please enter the front right wheel mass in kg: ", calcular_centro_de_gravedad)
def get_rear_axle_mass(rear_left, rear_right):
"""Return rear axle mass from wheel masses in kg.
Arguments:
rear_left -- rear left wheel mass in kg.
rear_right -- rear right wheel mass in kg.
"""
return rear_left + rear_right
def get_front_axle_mass(front_left, front_right):
"""Return front axle mass form wheel masses in kg.
Arguments:
front_left -- front left wheel mass in kg.
front_right -- front right wheel mass in kg.
Return values:
The frontal axle mass in kg.
"""
return front_left + front_right
def get_vehicle_mass(rear_axle_mass, front_axle_mass):
"""Return vehicle mass from wheel masses in kg.
Arguments:
rear_axle_mass -- vehicle rear axle mass in kg.
front_axle_mass -- vehicle front axle mass in kg.
Return values:
The total vehicle mass in kg.
"""
return rear_axle_mass + front_axle_mass
def get_lifted_angle(lift_height, mean_wheelbase):
"""Return lifted angle from vehicle lift height and mean wheelbase.
Arguments:
lift_height -- lift height in mm.
mean_wheelbase -- mean wheelbase in mm.
Return values:
The lifted angle in radians.
"""
return math.atan(lift_height / mean_wheelbase)
def get_lifted_rear_left_wheel_mass(calcular_centro_de_gravedad):
"""Get lifted rear left wheel mass from user input in kg."""
return print("Please enter the lifted rear left wheel mass in kg: ", calcular_centro_de_gravedad)
def get_lifted_rear_right_wheel_mass(calcular_centro_de_gravedad):
"""Get lifted rear right wheel mass from user input in kg."""
return print("Please enter the lifted rear right wheel mass in kg: ", calcular_centro_de_gravedad)
def get_lifted_rear_axle_mass(lifted_rear_left_wheel_mass, lifted_rear_right_wheel_mass):
"""Return rear axle mass from wheel masses in kg.
Arguments:
rear_left -- rear left wheel mass in kg.
rear_right -- rear right wheel mass in kg.
"""
return lifted_rear_left_wheel_mass + lifted_rear_right_wheel_mass
def get_longitudinal_distance(vehicle_mass, rear_axle_mass, mean_wheelbase):
"""Return longitudinal distance in mm.
Arguments:
vehicle_mass -- vehicle total mass in kg..
rear_axle_mass -- rear axle mass in kg.
mean_wheelbase -- mean wheelbase in mm.
Return values:
The longitudinal distance of the center of gravity in mm.
"""
return (rear_axle_mass / vehicle_mass) * mean_wheelbase
def get_transverse_distance(front_track, rear_track, rear_right_mass,
rear_left_mass, front_left_mass, front_right_mass, vehicle_mass):
"""Return transverse distance in mm.
Arguments:
front_track -- front track in mm.
rear_track -- rear track in .
rear_right_mass -- rear right wheel mass in kg.
rear_left_mass -- rear left wheel mass in kg.
front_left_mass -- front left wheel mass in kg.
front_right_mass -- front right wheel mass in kg.
vehicle_mass -- total vehicle mass in kg.
Return values:
The transverse distance of the center of gravity in mm.
"""
return ((front_track * (front_left_mass - front_right_mass))
+ (rear_track * (rear_left_mass - rear_right_mass))) / (2 * vehicle_mass)
def get_height(mean_wheelbase, lifted_rear_axle_mass, rear_axle_mass, vehicle_mass, lifted_angle, static_wheel_radius):
"""Return height of the center of gravity in mm.
Arguments:
Return values:
The height of the center of gravity in mm.
"""
return ((mean_wheelbase * (lifted_rear_axle_mass - rear_axle_mass))
/ (vehicle_mass * math.tan(lifted_angle))) + static_wheel_radius
def get_center_of_gravity(vehicle_mass, rear_axle_mass, mean_wheelbase, front_track,
rear_track, rear_right_mass, rear_left_mass, front_left_mass,
front_right_mass, lifted_rear_axle_mass, lifted_angle, static_wheel_radius):
"""Return a vehicle's center of gravity.
Argument:
longitudinal_distance -- the longitudinal distance of the center of gravity.
transverse_distance -- the transverse distance of the center of gravity.
height -- the height of the center of gravity.
Return values:
A tuple made up from the XYZ coordinates of the center of gravity in mm.
"""
longitudinal_distance = get_longitudinal_distance(vehicle_mass, rear_axle_mass, mean_wheelbase)
transverse_distance = get_transverse_distance(front_track, rear_track, rear_right_mass,
rear_left_mass, front_left_mass, front_right_mass, vehicle_mass)
height = get_height(mean_wheelbase, lifted_rear_axle_mass, rear_axle_mass,
vehicle_mass, lifted_angle, static_wheel_radius)
return longitudinal_distance, transverse_distance, height
#enter the lift height in mm
lbl_lift_height = tk.Label(p3,text="Please enter the lift height in mm: ")
lbl_lift_height.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.04)
lift_height = tk.Entry(p3)
lift_height.place(relx=0.65, rely=0.1, relwidth=0.1, relheight=0.04)
#enter the left wheelbase in mm
lbl_left_wheelbase = tk.Label(p3,text="Please enter the left wheelbase in mm: ")
lbl_left_wheelbase.place(relx=0.1, rely=0.15, relwidth=0.3, relheight=0.04)
left_wheelbase = tk.Entry(p3)
left_wheelbase.place(relx=0.65, rely=0.15, relwidth=0.1, relheight=0.04)
#Enter the right wheelbase in mm
lbl_right_wheelbase = tk.Label(p3,text="Please enter the right wheelbase in mm: " )
lbl_right_wheelbase.place(relx=0.1, rely=0.2, relwidth=0.3, relheight=0.04)
right_wheelbase = tk.Entry(p3)
right_wheelbase.place(relx=0.65, rely=0.2, relwidth=0.1, relheight=0.04)
#Enter vehicle rear track in mm
lbl_rear_track = tk.Label(p3,text="Please enter vehicle rear track in mm: " )
lbl_rear_track.place(relx=0.1, rely=0.25, relwidth=0.3, relheight=0.04)
rear_track = tk.Entry(p3)
rear_track.place(relx=0.65, rely=0.25, relwidth=0.1, relheight=0.04)
#Enter vehicle front track in mm
lbl_front_track = tk.Label(p3,text="Please enter vehicle front track in mm: ")
lbl_front_track.place(relx=0.1, rely=0.3, relwidth=0.3, relheight=0.04)
front_track = tk.Entry(p3)
front_track.place(relx=0.65, rely=0.3, relwidth=0.1, relheight=0.04)
#Enter lifted vehicle wheel diameter in mm
lbl_wheel_diameter = tk.Label(p3,text="Please enter lifted vehicle wheel diameter in mm: ")
lbl_wheel_diameter.place(relx=0.1, rely=0.35, relwidth=0.3, relheight=0.04)
wheel_diameter = tk.Entry(p3)
wheel_diameter.place(relx=0.65, rely=0.35, relwidth=0.1, relheight=0.04)
#enter lifted vehicle flattened wheel diameter in mm
lbl_flattened_wheel_diameter = tk.Label(p3,text="Please enter lifted vehicle flattened wheel diameter in mm: ")
lbl_flattened_wheel_diameter.place(relx=0.1, rely=0.4, relwidth=0.3, relheight=0.04)
flattened_wheel_diameter = tk.Entry(p3)
flattened_wheel_diameter.place(relx=0.65, rely=0.4, relwidth=0.1, relheight=0.04)
#Enter the rear left wheel mass in kg
lbl_rear_left_wheel_mass = tk.Label(p3,text="Please enter the rear left wheel mass in kg: ")
lbl_rear_left_wheel_mass.place(relx=0.1, rely=0.45, relwidth=0.3, relheight=0.04)
rear_left_wheel_mass = tk.Entry(p3)
rear_left_wheel_mass.place(relx=0.65, rely=0.45, relwidth=0.1, relheight=0.04)
#Enter the rear right wheel mass in kg
lbl_rear_right_wheel_mass = tk.Label(p3,text="Please enter the rear right wheel mass in kg: ")
lbl_rear_right_wheel_mass.place(relx=0.1, rely=0.5, relwidth=0.3, relheight=0.04)
rear_right_wheel_mass = tk.Entry(p3)
rear_right_wheel_mass.place(relx=0.65, rely=0.5, relwidth=0.1, relheight=0.04)
#Enter the lifted rear left wheel mass in kg
lbl_front_left_wheel_mass = tk.Label(p3,text="Please enter the lifted rear left wheel mass in kg: ")
lbl_front_left_wheel_mass.place(relx=0.1, rely=0.55, relwidth=0.3, relheight=0.04)
front_left_wheel_mass = tk.Entry(p3)
front_left_wheel_mass.place(relx=0.65, rely=0.55, relwidth=0.1, relheight=0.04)
#Enter the lifted rear right wheel mass in kg
lbl_front_right_wheel_mass = tk.Label(p3,text="Please enter the lifted rear right wheel mass in kg: ")
lbl_front_right_wheel_mass.place(relx=0.1, rely=0.6, relwidth=0.3, relheight=0.04)
front_right_wheel_mass = tk.Entry(p3)
front_right_wheel_mass.place(relx=0.65, rely=0.6, relwidth=0.1, relheight=0.04)
#Enter the lifted rear left wheel mass in kg
lbl_lifted_rear_left_wheel_mass = tk.Label(p3,text="Please enter the lifted rear right wheel mass in kg: ")
lbl_lifted_rear_left_wheel_mass.place(relx=0.1, rely=0.65, relwidth=0.3, relheight=0.04)
lifted_rear_left_wheel_mass = tk.Entry(p3)
lifted_rear_left_wheel_mass.place(relx=0.65, rely=0.65, relwidth=0.1, relheight=0.04)
#Enter the lifted rear right wheel mass in kg
lbl_lifted_rear_right_wheel_mass = tk.Label(p3,text="Please enter the lifted rear right wheel mass in kg: ")
lbl_lifted_rear_right_wheel_mass.place(relx=0.1, rely=0.7, relwidth=0.3, relheight=0.04)
lifted_rear_right_wheel_mass = tk.Entry(p3)
lifted_rear_right_wheel_mass.place(relx=0.65, rely=0.7, relwidth=0.1, relheight=0.04)
#Boton para calcular el centro de gravedad
calcular_centro_de_gravedad = Button(p3, text="Calcular", command=lambda: [
get_lift_height(lift_height.get()),
get_left_wheelbase(left_wheelbase.get()),
get_right_wheelbase(right_wheelbase.get()),
get_rear_track(rear_track.get()),
get_front_track(front_track.get()),
get_wheel_diameter(wheel_diameter.get()),
get_flattened_wheel_diameter(flattened_wheel_diameter.get()),
get_rear_left_wheel_mass(rear_left_wheel_mass.get()),
get_rear_right_wheel_mass(rear_right_wheel_mass.get()),
get_front_left_wheel_mass(front_left_wheel_mass.get()),
get_front_right_wheel_mass(front_right_wheel_mass.get()),
get_lifted_rear_left_wheel_mass(lifted_rear_left_wheel_mass.get()),
get_lifted_rear_right_wheel_mass(lifted_rear_right_wheel_mass.get())
])
calcular_centro_de_gravedad.place(relx=0.35, rely=0.8, relwidth=0.3, relheight=0.1)
root.mainloop() |
69b00f30de1e437d363502c96cc4e0956416dddb | FelipeTacara/code-change-test | /greenBottles.py | 423 | 3.921875 | 4 | def greenbottles(bottles):
for garrafas in range(bottles, 0, -1):
# for loop counting down the number of bottles
print(f"{garrafas} green bottles, hanging on the wall\n"
f"{garrafas} green bottles, hanging on the wall\n"
f"And if 1 green bottle should accidentally fall,\n"
f"They'd be {garrafas - 1} green bottles hanging on the wall."
f"...\n")
|
6f0283e896b0a758c9eb88198b2c9718c564aa1b | SurabhiTosh/AI_MazeSolving | /mazedemo.py | 684 | 3.828125 | 4 | from PIL import Image
import numpy as np
# Open the maze image and make greyscale, and get its dimensions
im = Image.open('examples/small.png').convert('L')
w, h = im.size
# Ensure all black pixels are 0 and all white pixels are 1
binary = im.point(lambda p: p > 128 and 1)
# Resize to half its height and width so we can fit on Stack Overflow, get new dimensions
# binary = binary.resize((w//2,h//2),Image.NEAREST)
w, h = binary.size
# Convert to Numpy array - because that's how images are best stored and processed in Python
nim = np.array(binary)
# Print that puppy out
for r in range(h):
for c in range(w):
print(nim[r,c],end='')
print() |
434f69b6fd36753ac13589061bec3cd3da51124a | Alex0Blackwell/recursive-tree-gen | /makeTree.py | 1,891 | 4.21875 | 4 | import turtle as t
import random
class Tree():
"""This is a class for generating recursive trees using turtle"""
def __init__(self):
"""The constructor for Tree class"""
self.leafColours = ["#91ff93", "#b3ffb4", "#d1ffb3", "#99ffb1", "#d5ffad"]
t.bgcolor("#abd4ff")
t.penup()
t.sety(-375)
t.pendown()
t.color("#5c3d00")
t.pensize(2)
t.left(90)
t.forward(100) # larger trunk
t.speed(0)
self.rootPos = t.position()
def __drawHelp(self, size, pos):
"""
The private helper method to draw the tree.
Parameters:
size (int): How large the tree is to be.
pos (int): The starting position of the root.
"""
if(size < 20):
if(size % 2 == 0):
# let's only dot about every second one
t.dot(50, random.choice(self.leafColours))
return
elif(size < 50):
t.dot(50, random.choice(self.leafColours))
# inorder traversial
t.penup()
t.setposition(pos)
t.pendown()
t.forward(size)
thisPos = t.position()
thisHeading = t.heading()
size = size - random.randint(10, 20)
t.setheading(thisHeading)
t.left(25)
self.__drawHelp(size, thisPos)
t.setheading(thisHeading)
t.right(25)
self.__drawHelp(size, thisPos)
def draw(self, size):
"""
The method to draw the tree.
Parameters:
size (int): How large the tree is to be.
"""
self.__drawHelp(size, self.rootPos)
def main():
tree = Tree()
tree.draw(125)
t.hideturtle()
input("Press enter to terminate program: ")
if __name__ == '__main__':
main()
|
1f4efdbabe7ec92db5d9a4d9f287de6c82988634 | scott-yj-yang/cogs118a-final | /data_cleaning.py | 3,909 | 3.59375 | 4 | import pandas as pd
from my_package import clean_course_num
def clean_all_dataset():
# Clean the adult dataset
columns = ["age", "workclass", "fnlwgt", "education", "education-num", "marital-status",
"occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week",
"native-country", ">50K"]
adult = pd.read_csv('data/adult.data', names=columns)
adult['>50K'] = adult['>50K'].apply(lambda x: 1 if x.strip() != "<=50K" else -1)
encoded = pd.get_dummies(adult, drop_first=True)
with open("data/adult_clean.csv", 'w') as file:
file.write(encoded.to_csv())
file.close()
# Clean the cape dataset
cape = pd.read_csv("data/CAPE_all.csv")
cape = cape.assign(course_code=cape['Course'].apply(lambda course: str(course).split('-')[0][:-1]))
cape = cape.assign(department=cape["course_code"].apply(lambda code: str(code).split()[0]))
cape = cape.assign(course_num=cape["course_code"].apply(
lambda code: str(code).split()[1]
if len(str(code).split()) == 2 else code))
cape = cape.assign(course_description=cape['Course'].apply(
lambda course: str(course).split('-')[1] if len(str(course).split('-')) == 2 else course))
grade = cape[['department', 'course_num', 'Term', 'Study Hrs/wk', 'Avg Grade Expected', 'Avg Grade Received']][
(cape["Avg Grade Expected"].notna()) & (cape["Avg Grade Received"].notna())
]
grade = grade.assign(
GPA_Expected=grade['Avg Grade Expected'].apply(lambda grade_: float(grade_.split()[1][1:-1])),
GPA_Received=grade['Avg Grade Received'].apply(lambda grade_: float(grade_.split()[1][1:-1])),
letter_Recieved=grade['Avg Grade Received'].apply(lambda grade_: grade_.split()[0])
)
grade["GPA_Received"] = grade["GPA_Received"].apply(lambda grade_: 1 if grade_ > 3.2 else -1)
grade = grade.drop(columns=['Avg Grade Expected', 'Avg Grade Received', 'letter_Recieved'])
grade['is_upper'] = grade['course_num'].apply(clean_course_num)
grade = grade.drop(columns=['course_num'])
grade_encoded = pd.get_dummies(grade, drop_first=True)
with open('data/cape_clean.csv', 'w') as file:
file.write(grade_encoded.to_csv())
file.close()
# Clean the COV dataset
columns = ["Elevation", "Aspect", "Slope", "Horizontal_Distance_To_Hydrology",
"Vertical_Distance_To_Hydrology", "Horizontal_Distance_To_Roadways",
"Hillshade_9am", "Hillshade_Noon", "Hillshade_3pm",
"Horizontal_Distance_To_Fire_Points"] + \
["Wilderness_Area_" + str(i) for i in range(4)] + \
["Soil_Type_" + str(i) for i in range(40)] + \
['Cover_Type']
cov_raw = pd.read_csv("data/covtype.data.gz", names=columns)
cov_raw['Cover_Type'] = cov_raw['Cover_Type'].apply(
lambda type_num: 1 if type_num == 7 else -1)
with open('data/cover_clean.csv', 'w') as file:
file.write(cov_raw.to_csv())
file.close()
# Clean the Letter dataset
columns = ['letter', 'x-box', 'y-box', 'width', 'high', 'onpix', 'x-bar', 'y-bar',
'x2bar', 'y2bar', 'xybar', 'x2ybr', 'xy2br', 'x-ege', 'xegvy',
'y-ege', 'yegvx']
letter_raw = pd.read_csv("data/letter-recognition.data", names=columns)
letter_p1 = letter_raw.assign(
letter=letter_raw['letter'].apply(lambda letter: 1 if letter == 'O' else -1)
)
positive_class = [chr(i) for i in range(ord("A"), ord("M") + 1)]
letter_p2 = letter_raw.assign(
letter=letter_raw['letter'].apply(lambda letter: 1 if letter in positive_class else -1)
)
with open("data/letter_clean_p1.csv", 'w') as file:
file.write(letter_p1.to_csv())
file.close()
with open("data/letter_clean_p2.csv", 'w') as file:
file.write(letter_p2.to_csv())
file.close()
|
e02add5ed76d468dc7ba4ec07060daeb1e069be3 | tjbonesteel/ECE364 | /Labfiles/Lab13/flow1.py~ | 2,174 | 3.53125 | 4 | #! /usr/bin/env python2.6
# $Author: ee364d02 $
# $Date: 2013-11-19 22:43:05 -0500 (Tue, 19 Nov 2013) $
# $HeadURL: svn+ssh://ece364sv@ecegrid-lnx/home/ecegrid/a/ece364sv/svn/F13/students/ee364d02/Lab13/flow.py $
# $Revision: 63131 $
from Tkinter import *
import os
import sys
import math
import re
fileIN = sys.argv[1]
class Game(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="gray")
self.parent = parent
self.initUI()
def initUI(self):
count=2
self.parent.title("FLOW")
fileObj = open(fileIN)
def callback(m,n,color):
row=n
col=m
btn = Button(self, text=line[x],width=10, height=5, command=lambda x=m, y=n: callback(x,y))
btn.config(bg="red")
btn.grid(column=col, row=row)
print n,m
for line in fileObj:
line = line.strip()
line = line.split(",")
width = len(line)
for x in range(width):
btn = Button(self, text=line[x],width=10, height=5, command=lambda x=x,color=line[x], y=count: callback(x,y,color))
if line[x] == "1":
btn.config(bg = "red")
elif line[x] == "2":
btn.config(bg = "orange")
elif line[x] == "3":
btn.config(bg = "green")
btn.grid(column=x, row=count)
count += 1
quitButton = Button(self, text="Quit",width=10, command=self.quit)
quitButton.grid(row=1, column=width-1)
self.pack(fill=BOTH,expand=1)
def main():
root=Tk()
root.geometry("700x700+300+300")
app=Game(root)
if len(sys.argv) != 2:
print "Usage: ./flow.py <inputfile>"
exit(1)
fileIN = sys.argv[1]
if not os.access(fileIN,os.R_OK):
print "%s is not a readable file" % (fileIN)
exit(1)
root.mainloop()
if __name__ == '__main__':
main()
|
d94f04f820ec9c6a0eb6b19c3e998384966b55aa | ProgFuncionalReactivaoct19-feb20/practica04-royerjmasache | /practica4.py | 1,239 | 3.90625 | 4 | """
Práctica 4
@royerjmasache
"""
# Importación de librerías
import codecs
import json
# Lectura de archivos con uso de codecs y json
file = codecs.open("data/datos.txt")
lines = file.readlines()
linesDictionary = [json.loads(a) for a in lines]
# Uso de filter y función anónima para evaluar la condición requerida y filtrar los resultados
goals = list(filter(lambda a: list(a.items())[1][1] > 3, linesDictionary))
# Presentación de resultados en forma de lista
print("Players with more than 3 goals scored:\n", list(goals))
# Uso de filter y función anónima para cumplir evaluar la condición requerida y filtrar los resultados
country = list(filter(lambda a: list(a.items())[0][1] == "Nigeria", linesDictionary))
# Presentación de resultados en forma de lista
print("Nigeria players:\n", list(country))
# Uso de función anónima para seleccionar la posición
height = lambda a: list(a.items())[2][1]
# Uso de función min, map para la iteración y presentación de resultados en forma de lista
print("Minimum height:\n", min(list(map(height, linesDictionary))))
# Uso de función max, map para la iteración y presentación de resultados en forma de lista
print("Maximum height:\n", max(list(map(height, linesDictionary))))
|
8a39ae38331f518ac8c64d6d74dee4a89534f559 | lfarhi/scikit-learn-mooc | /python_scripts/feature_selection.py | 11,193 | 3.828125 | 4 | # ---
# jupyter:
# jupytext:
# cell_metadata_filter: -all
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # Feature selection
#
# %% [markdown]
# ## Benefit of feature selection in practice
#
# ### Speed-up train and scoring time
# The principal advantage of selecting features within a machine learning
# pipeline is to reduce the time to train this pipeline and its time to
# predict. We will give an example to highlights these advantages. First, we
# generate a synthetic dataset to control the number of features that will be
# informative, redundant, repeated, and random.
# %%
from sklearn.datasets import make_classification
X, y = make_classification(
n_samples=5000,
n_features=100,
n_informative=2,
n_redundant=0,
n_repeated=0,
random_state=0,
)
# %% [markdown]
# We chose to create a dataset with two informative features among a hundred.
# To simplify our example, we did not include either redundant or repeated
# features.
#
# We will create two machine learning pipelines. The former will be a random
# forest that will use all available features. The latter will also be a random
# forest, but we will add a feature selection step to train this classifier.
# The feature selection is based on a univariate test (ANOVA F-value) between
# each feature and the target that we want to predict. The features with the
# two most significant scores are selected.
# %%
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif
from sklearn.pipeline import make_pipeline
model_without_selection = RandomForestClassifier(n_jobs=-1)
model_with_selection = make_pipeline(
SelectKBest(score_func=f_classif, k=2),
RandomForestClassifier(n_jobs=-1),
)
# %% [markdown]
# We will measure the average time spent to train each pipeline and make it
# predict. Besides, we will compute the generalization score of the model. We
# will collect these results via cross-validation.
# %%
import pandas as pd
from sklearn.model_selection import cross_validate
cv_results_without_selection = pd.DataFrame(
cross_validate(model_without_selection, X, y)
)
cv_results_with_selection = pd.DataFrame(
cross_validate(model_with_selection, X, y, return_estimator=True),
)
# %%
cv_results = pd.concat(
[cv_results_without_selection, cv_results_with_selection],
axis=1,
keys=["Without feature selection", "With feature selection"],
).swaplevel(axis="columns")
# %% [markdown]
# Let's first analyze the train and score time for each pipeline.
# %%
import matplotlib.pyplot as plt
cv_results["fit_time"].plot.box(vert=False, whis=100)
plt.xlabel("Elapsed time (s)")
_ = plt.title("Time to fit the model")
# %%
cv_results["score_time"].plot.box(vert=False, whis=100)
plt.xlabel("Elapsed time (s)")
_ = plt.title("Time to make prediction")
# %% [markdown]
# We can draw the same conclusions for both training and scoring elapsed time:
# selecting the most informative features speed-up our pipeline.
#
# Of course, such speed-up is beneficial only if the performance in terms of
# metrics remain the same. Let's check the generalization score.
# %%
cv_results["test_score"].plot.box(vert=False, whis=100)
plt.xlabel("Accuracy score")
_ = plt.title("Test score via cross-validation")
# %% [markdown]
# We can observe that the model's performance selecting a subset of features
# decreases compared with the model using all available features. Since we
# generated the dataset, we can infer that the decrease is because the
# selection did not choose the two informative features.
#
# We can quickly investigate which feature have been selected during the
# cross-validation. We will print the indices of the two selected features.
# %%
import numpy as np
for idx, pipeline in enumerate(cv_results_with_selection["estimator"]):
print(
f"Fold #{idx} - features selected are: "
f"{np.argsort(pipeline[0].scores_)[-2:]}"
)
# %% [markdown]
# We see that the feature `53` is always selected while the other feature
# varies depending on the cross-validation fold.
#
# If we would like to keep our score with similar performance, we could choose
# another metric to perform the test or select more features. For instance, we
# could select the number of features based on a specific percentile of the
# highest scores. Besides, we should keep in mind that we simplify our problem
# by having informative and not informative features. Correlation between
# features makes the problem of feature selection even harder.
#
# Therefore, we could come with a much more complicated procedure that could
# fine-tune (via cross-validation) the number of selected features and change
# the way feature is selected (e.g. using a machine-learning model). However,
# going towards these solutions alienates the feature selection's primary
# purpose to get a significant train/test speed-up. Also, if the primary goal
# was to get a more performant model, performant models exclude non-informative
# features natively.
#
# ## Caveats of the feature selection
# When using feature selection, one has to be extra careful about the way it
# implements it. We will show two examples where feature selection can
# miserably fail.
#
# ### Selecting features without cross-validation
# The biggest mistake to be made when selecting features is similar to one that
# can be made when optimizing hyperparameters of a model: find the subset of
# features on the same dataset as well used to evaluate the model's
# generalization performance.
#
# We will generate a synthetic dataset with a large number of features and a
# few samples to emphasize the issue. This use-case is typical in
# bioinformatics when dealing with RNA-seq. However, we will use completely
# randomized features such that we don't have a link between the data and the
# target. Thus, the performance of any machine-learning model should not
# perform better than the chance-level. In our example, we will use a logistic
# regressin classifier.
# %%
rng = np.random.RandomState(42)
X, y = rng.randn(100, 100000), rng.randint(0, 2, size=100)
# %%
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
test_score = cross_val_score(model, X, y, n_jobs=-1)
print(f"The mean accuracy is: {test_score.mean():.3f}")
# %% [markdown]
# There is no surprise that the logistic regression model performs as the
# chance level when we provide the full dataset.
#
# We will then show the **wrong** pattern that one should not apply: select the
# feature by using the entire dataset. We will choose ten features with the
# highest ANOVA F-score computed on the full dataset. Subsequently, we
# subsample the dataset `X` by selecting the features' subset. Finally, we
# train and test a logistic regression model.
# %%
from sklearn.model_selection import cross_val_score
feature_selector = SelectKBest(score_func=f_classif, k=10)
test_score = cross_val_score(model, feature_selector.fit_transform(X, y), y)
print(f"The mean accuracy is: {test_score.mean():.3f}")
# %% [markdown]
# Surprisingly, the logistic regression succeeded in having a fantastic
# accuracy using data with no link with the target, initially. We, therefore,
# know that these results are not legit.
#
# The reasons for obtaining these results are two folds: the pool of available
# features is large compared to the number of samples. It is possible to find a
# subset of features that will link the data and the target. By not splitting
# the data, we leak knowledge from the entire dataset and could use this
# knowledge will evaluating our model.
#
# Instead, we will now split our dataset into a training and testing set and
# only compute the univariate test on the training set. Then, we will use the
# best features found on the training set during the scoring.
# %%
model = make_pipeline(feature_selector, LogisticRegression())
test_score = cross_val_score(model, X, y)
print(f"The mean accuracy is: {test_score.mean():.3f}")
# %% [markdown]
# We see that selecting feature only on the training set will not help when
# testing our model. In this case, we obtained the expected results.
#
# Therefore, as with hyperparameters optimization or model selection, tuning
# the feature space should be done solely on the training set, keeping a part
# of the data left-out.
#
# ### Limitation of selecting feature using a model
# An advanced strategy to select features is to use a machine learning model.
# Indeed, one can inspect a model and find relative feature importances. For
# instance, the parameters `coef_` for the linear models or
# `feature_importances_` for the tree-based models carries such information.
# Therefore, this method works as far as the relative feature importances given
# by the model is sufficient to select the meaningful feature.
#
# Here, we will generate a dataset that contains a large number of random
# features.
# %%
X, y = make_classification(
n_samples=5000,
n_features=100,
n_informative=2,
n_redundant=5,
n_repeated=5,
class_sep=0.3,
random_state=0,
)
# %% [markdown]
# First, let's build a model which will not make any features selection. We
# will use a cross-validation to evaluate this model.
# %%
model_without_selection = RandomForestClassifier(n_jobs=-1)
cv_results_without_selection = pd.DataFrame(
cross_validate(model_without_selection, X, y, cv=5)
)
# %% [markdown]
# Then, we will build another model which will include a feature selection
# step based on a random forest. We will also evaluate the performance of the
# model via cross-validation.
# %%
from sklearn.feature_selection import SelectFromModel
model_with_selection = make_pipeline(
SelectFromModel(
estimator=RandomForestClassifier(n_jobs=-1),
),
RandomForestClassifier(n_jobs=-1),
)
cv_results_with_selection = pd.DataFrame(
cross_validate(model_with_selection, X, y, cv=5)
)
# %% [markdown]
# We can compare the generalization score of the two models.
# %%
cv_results = pd.concat(
[cv_results_without_selection, cv_results_with_selection],
axis=1,
keys=["Without feature selection", "With feature selection"],
).swaplevel(axis="columns")
cv_results["test_score"].plot.box(vert=False, whis=100)
plt.xlabel("Accuracy")
_ = plt.title("Limitation of using a random forest for feature selection")
# %% [markdown]
# The model that selected a subset of feature is less performant than a
# random forest fitted on the full dataset.
#
# We can rely on some aspects tackled in the notebook presenting the model
# inspection to explain this behaviour. The decision tree's relative feature
# importance will overestimate the importance of random feature when the
# decision tree overfits the training set.
#
# Therefore, it is good to keep in mind that feature selection relies on
# procedures making some assumptions, which can be perfectible.
|
c006402cf62530d0b685d5becf283a9f43d1796d | UCMHSProgramming16-17/file-io-HikingPenguin17 | /PokeClass.py | 344 | 3.5 | 4 | import random
class Pokemon(object):
def __init__(self, identity):
self.name = identity
self.level = random.randint(1, 100)
bulb = Pokemon('Bulbasaur')
char = Pokemon('Charmander')
squirt = Pokemon('Squirtle')
print(bulb.name, bulb.level)
print(char.name, char.level)
print(squirt.name, squirt.level) |
002464d45f720f95b4af89bfa30875ae2ed46f70 | spencerhcheng/algorithms | /codefights/arrayMaximalAdjacentDifference.py | 714 | 4.15625 | 4 | #!/usr/bin/python3
"""
Given an array of integers, find the maximal absolute difference between any two of its adjacent elements.
Example
For inputArray = [2, 4, 1, 0], the output should be
arrayMaximalAdjacentDifference(inputArray) = 3.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer inputArray
Guaranteed constraints:
3 ≤ inputArray.length ≤ 10,
-15 ≤ inputArray[i] ≤ 15.
[output] integer
The maximal absolute difference.
"""
def maxDiff(arr):
max_diff = float('-inf')
for idx in range(1, len(arr)):
max_diff = max(max_diff, abs(arr[idx] - arr[idx - 1]))
return max_diff
if __name__ == "__main__":
arr = [2, 4, 1, 0]
print(maxDiff(arr))
|
1283bc076c088f5f3ef66ba11af46cdb39aae2cd | cjohlmacher/PythonDataStructures | /37_sum_up_diagonals/sum_up_diagonals.py | 662 | 4 | 4 | def sum_up_diagonals(matrix):
"""Given a matrix [square list of lists], return sum of diagonals.
Sum of TL-to-BR diagonal along with BL-to-TR diagonal:
>>> m1 = [
... [1, 2],
... [30, 40],
... ]
>>> sum_up_diagonals(m1)
73
>>> m2 = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... ]
>>> sum_up_diagonals(m2)
30
"""
i = 0
j = len(matrix)-1
k = 0
sum = 0
while j > -1 and i < len(matrix):
sum += matrix[k][i]
sum += matrix[k][j]
i += 1
j -= 1
k += 1
return sum |
2252436f7d0b24feb0c6e518ce47f4b85b68bd40 | saumak/AI-projects | /map-search-algorithm/problem3/solver16.py | 7,136 | 3.859375 | 4 | #!/usr/bin/env python
#
# solver16.py : Solve the 16 puzzle problem - upto 3 tiles to move.
#
# (1)
# State space: All possible formulation of the tiles in 16 puzzle problem.
# For example, a sample of the state look like this,
# S0 = array([[ 2, 3, 0, 4],
# [ 1, 6, 7, 8],
# [ 5, 10, 11, 12],
# [ 9, 13, 14, 15]])
#
# Successor function: Possible position of the tiles after 1 move (either moving 1, 2, or 3 tiles at ones)
# I marked the each successor function with its appropriate move with the 3 character notation.
#
# The successor gets in the input of current state and the move up to the state.
# Then it returns list of all the possible next states paired with moves taken upto that state, heuristic, and the cost.
#
# >>> successor(S0, [])
# [[array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 0, 12],
# [13, 14, 11, 15]]), ['D14'], 1.3333333333333333, 2.333333333333333],
# [array([[ 1, 2, 3, 4],
# [ 5, 6, 0, 8],
# [ 9, 10, 7, 12],
# [13, 14, 11, 15]]), ['D24'], 2.0, 3.0],
# [array([[ 1, 2, 0, 4],
# [ 5, 6, 3, 8],
# [ 9, 10, 7, 12],
# [13, 14, 11, 15]]), ['D34'], 2.6666666666666665, 3.6666666666666665],
# [array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12],
# [13, 0, 14, 15]]), ['R13'], 1.3333333333333333, 2.333333333333333],
# [array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12],
# [ 0, 13, 14, 15]]), ['R23'], 2.0, 3.0],
# [array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12],
# [13, 14, 15, 0]]), ['L13'], 0.0, 1.0]]
#
# Edge weights: 1 (One valid move is calculated as cost of 1)
#
# Goal state: Following is the goal state
#
# array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12],
# [13, 14, 15, 0]])
# Heuristic function: (Sum of Manhattan cost) / 3
#
# If I use the sum of the Manhattan cost as in the notes, it would be not admissble due to the over-estimating.
# I can move the tiles upto 3, which means that Dividing the sum of Manhattan cost by 3 won't over-estimate.
# Hence, this huristic function is admissible.
# Also, it is consistent, because it meets the triangle inequality.
#
# (2) How the search algorithm work
#
# For each step, the algorithm chooses to branch the node with the minimum f value, which is (heuristic + cost). The algorithm also keeps track of the revisited states. In the successor function, if the child state is previously visited, then it doesn't return the visited child state. It keeps branching until it reaches the goal state.
#
# (3) Any problem I faced, assumptions, simplifications, design decisions
#
# The heuristic function I am using is admissble, hence it would be complete and optimal.
# However, when the input board gets very complicated, the power of the heuristics to find the goal state tend to get weaker.
# I found that instead of using the admissible heuristic, if I used a heuristic with sum of Manhattan distance without dividing it by 3,
# the performance got much better. Here is the comparison of the two heuristics.
#
# < Heuristic: sum of Manhattan distance divided by 3 >
#
# [hankjang@silo problem3]$ time python solver16.py input_board10.txt
# D14 R24 U13 L22 D24 R14 D12 R23 U31 L31
# real 0m22.801s
# user 0m22.755s
# sys 0m0.030s
#
# < Heuristic: sum of Manhattan distance (not dividing by 3)>
#
# [hankjang@silo problem3]$ time python solver16.py input_board10.txt
# D14 R24 U13 L22 D24 R14 D12 R23 U31 L31
# real 0m0.587s
# user 0m0.558s
# sys 0m0.026s
#
# The difference in performance was stable for over 10 different input boards I tested.
# However, since the heuristic of using sum of Manhattan distance (not dividing by 3) is not admissible,
# I decided to stick with the slower, but admissible heuristic.
#
from __future__ import division
import sys
import numpy as np
from scipy.spatial.distance import cdist
n_tile = range(4)
col_move = {0:["L11","L21","L31"],1:["R12","L12","L22"],2:["R13","R23","L13"],3:["R14","R24","R34"]}
row_move = {0:["U11","U21","U31"],1:["D12","U12","U22"],2:["D13","D23","U13"],3:["D14","D24","D34"]}
G = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,0]])
# Save the position to dictionary
# Each dictionary holds the row, col index as value in a numpy array
# Then, returns the sum of the mahattan distances per all tiles divided by 3.
def manhattan_distance(s1, s2):
s1_dict = {}
s2_dict = {}
for i in n_tile:
for j in n_tile:
s1_dict[s1[i][j]] = np.array([i, j])
s2_dict[s2[i][j]] = np.array([i, j])
return sum([np.abs(s1_dict[key]-s2_dict[key]).sum() for key in s1_dict]) / 3
def initial_state(filename):
file = open(filename, "r")
return np.array([[int(tile) for tile in line.split()] for line in file])
def swap(s, r1, c1, r2, c2):
temp = s[r1,c1]
s[r1,c1] = s[r2,c2]
s[r2,c2] = temp
def successor(s, cur_m):
successor_list = []
# Get the index of the blank tile
row, col = np.where(s==0)
row_idx, col_idx = row[0], col[0]
# Get the 6 possible moves
possible_move = row_move[row_idx] + col_move[col_idx]
for move in possible_move:
row, col = row_idx, col_idx
s_next = np.copy(s)
# Get direction and the number of tiles to move
direction, n, _ = move
n = int(n)
if direction=='D':
for i in range(n):
swap(s_next,row,col,row-1,col)
row -= 1
elif direction=='U':
for i in range(n):
swap(s_next,row,col,row+1,col)
row += 1
elif direction=='R':
for i in range(n):
swap(s_next,row,col,row,col-1)
col -= 1
elif direction=='L':
for i in range(n):
swap(s_next,row,col,row,col+1)
col += 1
# Don't add the child if it's already checked
if any((s_next == s).all() for s in puzzle_tracking):
continue
h = heuristic(s_next, G)
m = cur_m + [move]
c = h + len(m)
successor_list.append([s_next, m, h, c])
return successor_list
def is_goal(s):
return (s == G).all()
def heuristic(s1, s2):
return manhattan_distance(s1, s2)
# return number_of_misplaced_tiles(s1, s2)
# f = heuristic + cost so far
def find_best_state(fringe):
f_list = [s[3] for s in fringe]
return f_list.index(min(f_list))
def solve(initial_board):
global puzzle_tracking
h = heuristic(initial_board, G)
fringe = [[initial_board, [], h, h]]
while len(fringe) > 0:
s, m, _, c = fringe.pop(find_best_state(fringe))
puzzle_tracking.append(s)
if is_goal(s):
return fringe, m
fringe.extend(successor(s, m))
return False
def printable_result(path):
return " ".join(path)
filename = sys.argv[1]
S0 = initial_state(filename)
puzzle_tracking = []
fringe, path = solve(S0)
print printable_result(path)
|
624fc12118833578813725bbb15e2477e04e587e | borisnorm/codeChallenge | /practiceSet/redditList/general/rotatedBSearch.py | 1,074 | 4 | 4 | #Binary Search on a Rotated Array
#Find the pivot point on a rotated array with slight modificaitons to binary search
#There is reason why the pivoting does not phase many people
#[5, 6, 7, 8, 1, 2, 3, 4]
def find_pivot_index(array, low, hi):
#DONT FORGET THE BASE CASE
if hi < low:
return 0
if hi == low:
return low
mid = (low + hi) / 2
#pivot turns when, mid and mid - 1 work
#If indicies are correct, and pivot starts at mid
if (mid < hi && arr[mid] > array[mid + 1]):
return mid
#hi low are correct, and pivot starts ad mide -1
if (mid > low && arr[mid] < array[mid - 1]):
return mid - 1
#two other check cases which are key
#if lower is greater than mid pivot, the pivot is between them
if array[low] >= array[mid]:
#why is it mid - 1?
return find_pivot_index(array, low, mid - 1):
#if array[low] < array[mid]: if hi is greater than mid, pivot is not here
else:
#If it is not between them, they must be somewhere else
#slowly incremenet this thing by 1?
return find_pivot_index(array, mid + 1, hi)
|
ecaa063b18366d5248e01f5392fcb51e59612c1e | borisnorm/codeChallenge | /practiceSet/levelTreePrint.py | 591 | 4.125 | 4 | #Print a tree by levels
#One way to approach this is to bfs the tree
def tree_bfs(root):
queOne = [root]
queTwo = []
#i need some type of switching mechanism
while (queOne or queTwo):
print queOne
while(queOne):
item = queOne.pop()
if (item.left is not None):
queTwo.append(item.left)
if (item.right is not None):
queTwo.append(item.right)
print queTwo
while(queTwo):
item = queTwo.pop()
if (item.left is not None):
queOne.append(item.left)
if (item.right is not None):
queOne.append(item.right)
|
d3ad65cbc6ec353c964cb8fb7202b0156f2fb150 | borisnorm/codeChallenge | /practiceSet/g4g/DP/cover_distance.py | 803 | 4 | 4 | #Given a distance ‘dist, count total number of ways to cover the distance with 1, 2 and 3 steps.
#distance, and array of steps in the step count
#1, 2, 3 is specific - general case is harder because of hard coding
#RR solution
def cover(distance):
if distance < 0:
return 0
if distance = 0:
return 1
else:
return cover(distance - 1) + cover(distance - 2) + cover(distance - 3)
#DP solution
def cover(distance):
memo = [0 for x in range(distance) + 1]
memo[1] = 1
memo[2] = 2
memo[3] = 3
for i in range(4, len(distance)):
#I am not sure if i need to add anything onto this or not, no add because its the same number of ways - we are not counting total number of step
#we can do that too
memo[i] = memo[i-1] + memo[i -2] + memo[i-3]
return memo[distance]
|
bd2ec1025a05a2b3b3a8cb0188762d620090c328 | borisnorm/codeChallenge | /practiceSet/intoToBinary.py | 407 | 3.828125 | 4 | #Math Way
def binary_to_int(number):
result = ""
while (number > 0):
result.insert(0, number % 2)
number = number % 2
return result
#BitShifting Way
def b_to_int(number):
result = []
for i in range(0, 32):
result.insert(number && 1, 0)
number >> 1
return result
#Python convert array of numbers to string
# ''.join(map(str, myList)) #This works with the array 123,
|
409c1452aaaa56dfc51186c75c8a1bbaefece675 | borisnorm/codeChallenge | /practiceSet/phoneScreen/num_reduce.py | 1,074 | 3.578125 | 4 | #Given a list o numbers a1/b1, a2/b2, return sum in reduced form ab
#Sum it in fractional form, or keep decimals and try to reverse
#This is language specific question
#(0.25).asInteger_ratio()
#Simplify
#from Fractions import fraction
#Fraction(0.185).limit_denominator()A
#A fraction will be returned
from Fractions import fraction
class Solution:
#Array of tuples ()
def reduced_sum(array):
#Fraction array is here
deci_array = []
for fraction in array:
deci_array.append(fracion[0] / fraction[1])
#Fraction array is here
sum_value = reduce(lambda x: x + y, deci_array)
return Fraction(sumValue).limit_denominator()
#Find the amx difference in array such that larges appears after the smaller
def max_diff(array):
min_val = 1000000 #Max integer
max_diff = 0
for value in array:
if value < min_val:
min_val = value
diff = value - min_val
if diff > max_diff:
max_diff = diff
return diff
|
5efebfc8ae11c7ae96bfb8c263b5320e48a2a582 | borisnorm/codeChallenge | /practiceSet/redditList/trees/kOrderBST.py | 627 | 3.75 | 4 | #Find Second largest number in a BST
#Must be the parent of the largest number, logn time
def secondLargest(root):
if root.right.right is None:
return root.right.value
else:
return secondLargest(root.right):
#Find The K largest number in a BST
#Initalize counter to 1, could put it into an array, but wastes space
def k_largest(root, counter, k):
if root is None:
return
else:
k_largest(root.left, counter + 1, k)
#THE Location must be here not above or it will print pre, order after every hit
if (counter == k):
return root.value
k_largest(root.right, counter + 1, k)
|
74e6ec63b7f3f50cb964f5c0959e4b6b224bbf05 | borisnorm/codeChallenge | /practiceSet/g4g/graph/bridge.py | 759 | 3.53125 | 4 | #Given a graph find all of the bridges in the graph
#Remove every edge and then BFS the graph, fi not all veriicies touched then that is it
#get neighbors - would recursive solution be better here? Naieve solution
def dfs(source, graph, size):
visited = set()
stack = [source]
while stack:
item = stack.pop(0)
if item not in visited:
visited.add(item)
for item in getNeighbors(item):
stack.insert(0, item)
if len(visited) = len(graph.keys())
return True
return False
def bridge_find(graph):
bridges = []
for key in graph.keys():
for edge in graph[key]:
temp_holder = edge
graph[key].remove(edge)
if dfs:
bridges.append(edge)
return bridges
#Most efficent algorithm for this
|
77806d17215fc004445465e5c06714662f4deadf | borisnorm/codeChallenge | /practiceSet/redditList/trees/printTree.py | 657 | 3.8125 | 4 | #Print Tree using BFS and DFS
def dfs_print(root):
if root is None:
return
else:
#shift print down, for pre, in, or post order
print root.value
dfs_print(root.left)
dfs_print(root.right)
def bfs_print(root):
queOne = [root]
queTwo = []
while (queOne && queTwo):
print queOne
while (queOne):
item = queOne.pop(0)
if (item.left):
queTwo.append(item.left)
if (item.right)
queTwo.append(item.right)
print queTwo
while (queTwo):
item = queTwo.pop(0)
if (item.left):
queOne.append(item.left)
if (item.right):
queTwo.append(item.right)
|
1052e9187b6693114b6472dbfc4aebef9ec5e368 | borisnorm/codeChallenge | /practiceSet/unionFind.py | 937 | 3.765625 | 4 | class DisjoinstSet:
#This does assume its in the set
#We should use a python dictionary to create this
def __init__(self, size):
#Make sure these are default dicts to prevent the key error?
self.lookup = {}
self.rank = {}
self.size = 0
def add(self, item):
self.lookup[item] = -1
#Union by rank
def union(self, itemOne, itemTwo):
rankOne = find_rank(itemOne)
rankTwo = find_rank(itemTwo)
if rankOne >= rankTwo:
self.lookup[itemOne] = find(itemTwo)
self.rank[itemTwo] += 1
return
self.lookup[itemTwo] = find(itemOne)
self.lookup[itemOne] = self.lookup[itemTwo]
return
#Find Rank
def find_rank(self, item):
return self.rank[item]
#Find the parent set
def find(self, item):
pointer = self.lookup[item]
while (pointer != -1):
if (self.lookup[pointer] == -1):
return pointer
pointer = self.lookup[pointer]
return pointer
|
2c76d8ff3516b065bcf92f674a847640f0896153 | borisnorm/codeChallenge | /practiceSet/g4g/tree/bottom_top_view.py | 1,168 | 3.71875 | 4 | #Print the bottom view of a binary tree
lookup = defaultdict([])
def level_serialize(root, lookup):
queueOne = [(root, 0, 0)]
queueTwo = []
while (queueOne && queueTwo):
while (queueOne):
item = queueOne.pop()
lookup[item[1]].append(item[0].value)
if (item[0].left):
queueTwo.insert(0, (item[0].left, item[1] - 1, item[2] + 1))
if (item[0].right):
queueTwo.insert(0, (item[0].left, item[1] + 1, item[2] + 1))
while (queueTwo):
item = queueTwo.pop()
lookup[item[1]].apppend(item[0].value)
if (item[0].left):
queueOne.insert(0, (item[0].left, item[1] - 1, item[2] + 1))
if (item[1].right):
queueOne.insert(0, (item[0].left, item[1] - 1, item[2] + 1))
return
def bottom_view(root):
lookup = defaultdict([])
level_serialize(root, lookup)
solution = []
for key in sorted(lookup.keys()):
solution.append(lookup[key][0])
return solution
def top_view(root):
lookup = defaultdict([])
level_serialize(root, lookup)
solution = []
for key in sorted(lookup.keys()):
length = len(lookup[key]) - 1
solution.append(lookup[key][length]
return solution
|
7efe77de55bd3666271186c9e8537f4228eb300d | borisnorm/codeChallenge | /practiceSet/allPartitions.py | 808 | 3.71875 | 4 | def isPal(string):
if string = string[::-1]
return True
return False
def isPal(array):
lo = 0
hi = len(array) - 1
while lo < hi:
if array[lo] != array[hi]):
return False
return True
def arrayElmIsPal(array):
for i in range(len(array)):
if isPal(array[i]) is False:
return False
return True
def partition(string)
array = string.split()
solution = []
return solution
def parted(array, current, final, solution):
if len(array) == 0:
if len(current) == 0:
solution.append(final)
if len(current) > 0:
#This is because mandatory brackets
if arrayElemIsPal([current] + final):
solution.append([current] + final)
else:
parted(array[:1], current + array[0], final)
parted(array[:1], current, final + [[array[0]])
|
15deda40cadaee36bf146665d48fd507d33baaad | borisnorm/codeChallenge | /practiceSet/g4g/stringArray/special_reverse.py | 364 | 3.671875 | 4 | #Reverse reverse then add back in
def s_rev(string, alphabet):
string_builder = ""
for i in range(len(string)):
if string[i] in alphabet:
string_builder += string[i]
rev = string_builder[::-1]
rev_counter = 0
for j in range(len(string)):
if string[j] in alphabet:
string[j] = rev[rev_counter]
rev_counter += 1
return string
|
bb6ec537a4019717fcb9f4d9be38d30bd84c31c5 | borisnorm/codeChallenge | /practiceSet/g4g/stringArray/count_trip.py | 370 | 3.921875 | 4 | #Count Triplets with sum smaller than a given value in an array
#Hashing does not help because there is no specific target to look for?
def count_trip(array, value):
counter = 0
for i in range(len(array)):
for j in range(len(array)):
for k in range(len(array)):
if array[i] + array[j] + array[k] < value:
counter += 1
return counter
|
07e6ccccbbd50cbb91199588006e07afc89887af | sbsreedh/DP-3 | /minFallingPathSum.py | 1,042 | 3.84375 | 4 | #Time Complexity=O(m*n)m-length of A, n-length of A[0]
#Space Complexity-O(m*n)
#we first initialize a 2D DP matrix, and then iterate the original matrix row by row. For each element in DP matrix, we sum up the corresponding element from original matrix with the minimum neighbors from previous row in DP matrix.Here instead of using a new matrix I have made computations in the existing one. Does this alter my SPACE COMAPLEXITY ? I guess it will be still O(m*n). Correct me if I am wrong.
class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
if len(A)==0 or len(A[0])==0:
return 0
m=len(A)
n=len(A[0])
for i in range(1,m):
for j in range(n):
if j==0:
A[i][j]+=min(A[i-1][j+1],A[i-1][j])
elif j==n-1:
A[i][j]+=min(A[i-1][j-1],A[i-1][j])
else:
A[i][j]+=min(A[i-1][j-1],A[i-1][j],A[i-1][j+1])
return min(A[-1])
|
fe8abe9c0010c34ac01963ffa8032930c899625c | FailedChampion/CeV_Py_Ex | /ex049.py | 316 | 4.0625 | 4 | # Exercício Python 049: Refaça o DESAFIO 009, mostrando a tabuada
# de um número que o usuário escolher, só que agora utilizando um laço for.
num_escolhido = int(input('Insira o número que deseja ver a tabuada: '))
for a in range(1, 11):
print('{} x {} = {}'.format(num_escolhido, a, num_escolhido * a))
|
7d610d3df84b0abb5c39d03fd658cd1f0f0b0e81 | FailedChampion/CeV_Py_Ex | /ex006.py | 329 | 3.984375 | 4 | # Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada.
n1 = int(input('Digite um número: '))
dou = n1 * 2
tri = n1 * 3
rq = n1 ** (1/2)
print('\n O dobro de {} é: {}'.format(n1, dou), '\n \n O triplo de {} é: {}'.format(n1, tri), '\n \n A raíz quadrada de {} é: {:.3f}'.format (n1, rq))
|
65d580e0f81ba9c29d3e6aa97becd5c83bd36aaf | FailedChampion/CeV_Py_Ex | /ex30.py | 164 | 3.9375 | 4 | num = int(input('Insira um número: '))
res = num % 2
print('\n')
print(res)
print('\nSe o resultado for 1, o número é ímpar,\n se for 0, é par.')
|
81575a05e053e8fb26e75a18deeb4b2db6105a65 | FailedChampion/CeV_Py_Ex | /ex007.py | 357 | 4 | 4 | # Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média.
n1 = float(input('Insira a primeira nota: '))
n2 = float(input('Insira a segunda nota: '))
print('A média entre {:.1f} e {:.1f} é igual a {:.1f}.'.format(n1, n2, (n1 + n2 / 2)))
print('Com isso em mente, a média do aluno foi {:.1f}.'.format(n1 + n2 / 2))
|
7e9255240d93efca2d010bb9f290520d56dd9dad | FailedChampion/CeV_Py_Ex | /ex018.py | 422 | 4.03125 | 4 | # Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
from math import sin, cos, tan, radians
n = float(input('Insira um ângulo: '))
r = radians(n)
print('Os valores de seno, cosseno e tangente do ângulo {:.0f} são:'.format(n))
print('\nSeno: {:.2f}'.format(sin(r)))
print('Cosseno: {:.2f}'.format(cos(r)))
print('Tangente: {:.2f}'.format(tan(r)))
|
fd181116ec4204dc513a88bad5efbe5057fe2096 | FailedChampion/CeV_Py_Ex | /ex008.py | 387 | 4.09375 | 4 | # Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
m = float(input('Insira uma distância em metros: '))
dm = m * 10
cm = m * 100
mm = m * 1000
print('A medida de {}m corresponde a \n{:.3f} Km \n{:.2f} Hm \n{:.1f} Dam'.format(m, (m / 1000), (m / 100), (m / 10)))
print('{:.0f} Dm \n{:.0f} Cm \n{:.0f} mm'.format(dm, cm, mm))
|
4f99ebc36affe769b3f861b7353e26dd8bc61f17 | ANANDMOHIT209/PythonBasic | /11opera.py | 255 | 4.09375 | 4 | #1.Arithmatic Operators
x=2
y=3
print(x+y)
print(x-y)
print(x*y)
print(x/y)
#2.Assignment Operators
x+=2
print(x)
a,b=5,6
print(a)
print(b)
#3.Relational Operators-- <,>,==,<=,>=,!=
#4.Logical Operators-- and ,or,not
#5.Unary Operators--
|
ef1808200296b1e75862f604def553543e94c246 | ANANDMOHIT209/PythonBasic | /4.py | 209 | 3.765625 | 4 | x=2
y=3
print(x+y)
x=10
print(x+y)
name='mohit'
print(name[0])
#print(name[5]) give error bound checking
print(name[-1]) #it give last letter
print(name[0:2])
print(name[1:3])
print(name[1:])
|
21d5842cfc55a1ee5d742eab7ca8f4a89278de30 | usert5432/cafplot | /cafplot/plot/rhist.py | 3,128 | 3.546875 | 4 | """
Functions to plot RHist histograms
"""
from .nphist import (
plot_nphist1d, plot_nphist1d_error, plot_nphist2d, plot_nphist2d_contour
)
def plot_rhist1d(ax, rhist, label, histtype = None, marker = None, **kwargs):
"""Plot one dimensional RHist1D histogram.
This is a wrapper around `plot_nphist1d` function.
Parameters
----------
ax : Axes
Matplotlib axes on which histogram will be plotted.
rhist : Rhist1D
Histogram to be plotted.
histtype : { 'line', 'step', 'bar' } or None, optional
Histogram style. None by default.
marker : str or None, optional
If not None this function will add markers on top of histogram bins.
c.f. help(matplotlib.pyplot.scatter).
kwargs : dict, optional
Additional parameters to pass directly to the matplotlib plotting funcs
"""
plot_nphist1d(
ax, rhist.hist, rhist.bins_x, label, histtype, marker, **kwargs
)
def plot_rhist1d_error(
ax, rhist, err_type = 'bar', err = None, sigma = 1, **kwargs
):
"""Plot error bars for one dimensional RHist1D histogram
Parameters
----------
ax : Axes
Matplotlib axes on which histogram will be plotted.
rhist : Rhist1D
Histogram to be plotted.
err_type : { 'bar', 'margin' } or None
Error bar style.
err : { None, 'normal', 'poisson' }
Type of the statistics to use for calculating error margin.
c.f. `RHist.get_error_margin`
sigma : float
Confidence expressed as a number of Gaussian sigmas
c.f. `RHist.get_error_margin`
kwargs : dict, optional
Additional parameters to pass directly to the matplotlib plotting funcs
c.f. `plot_nphist1d_error`
"""
hist_down, hist_up = rhist.get_error_margin(err, sigma)
plot_nphist1d_error(
ax, hist_down, hist_up, rhist.bins_x, err_type, **kwargs
)
def plot_rhist2d(ax, rhist, **kwargs):
"""Draw a two dimensional RHist2D histogram as an image.
Parameters
----------
ax : Axes
Matplotlib axes on which histogram will be plotted.
rhist : RHist2D
Histogram to be plotted.
kwargs : dict, optional
Additional parameters to pass directly to the matplotlib
NonUniformImage function
Returns
-------
NonUniformImage
Matplotlib NonUniformImage that depicts `rhist`.
"""
return plot_nphist2d(ax, rhist.hist, rhist.bins, **kwargs)
def plot_rhist2d_contour(ax, rhist, level, **kwargs):
"""Draw level contour for a two dimensional RHist2D histogram.
Parameters
----------
ax : Axes
Matplotlib axes on which contours will be plotted.
rhist : RHist2D
Histogram to be plotted.
level : float or list of float
Value of level(s) at which contour(s) will be drawn.
kwargs : dict, optional
Additional parameters to pass to the `plot_nphist2d_contour` function.
Returns
-------
pyplot.contour.QuadContourSet
Matplotlib contour set
"""
return plot_nphist2d_contour(ax, rhist.hist, rhist.bins, level, **kwargs)
|
11ff9ab018629fccbc71bbde47158ae1c8f0a0af | bamundi/python-cf | /diccionario.py | 373 | 3.625 | 4 | #no se pueden usar diccionarios y listas
#no tienen indice como las listas
#no se puede hacer slidesing (?) [0:2]
#se debe hacer uso de la clave para llamar a un elemento
diccionario = {'Clave1' : [2,3,4],
'Clave2' : True,
'Clave00' : 4,
5 : False
}
diccionario['clave00'] = "hola"
print diccionario['Clave2']
print diccionario[5]
print diccionario['clave00'] |
925cdc22f6be9a7103ba64204e1c54aa31db0f4c | jpclark6/adventofcode2019 | /solutions/20day.py | 4,467 | 3.578125 | 4 | import re, time
class Puzzle:
def __init__(self, file_name):
self.tiles = {}
file = open(file_name).read().splitlines()
matrix = [[x for x in line] for line in file]
for y in range(len(matrix)):
for x in range(len(matrix[0])):
if bool(re.search('[#.]', matrix[y][x])):
tile = Tile(x, y, matrix[y][x])
self.tiles[str(x) + "," + str(y)] = tile
if bool(re.search('[A-Z]', matrix[y - 1][x])):
tile.portal = True
tile.portal_key = matrix[y - 2][x] + matrix[y - 1][x]
elif bool(re.search('[A-Z]', matrix[y + 1][x])):
tile.portal = True
tile.portal_key = matrix[y + 1][x] + matrix[y + 2][x]
elif bool(re.search('[A-Z]', matrix[y][x - 1])):
tile.portal = True
tile.portal_key = matrix[y][x - 2] + matrix[y][x - 1]
elif bool(re.search('[A-Z]', matrix[y][x + 1])):
tile.portal = True
tile.portal_key = matrix[y][x + 1] + matrix[y][x + 2]
def get_tile(self, x, y):
key = str(x) + "," + str(y)
return self.tiles[key]
def find_end(self):
start = self.find_portal("AA")[0]
i = 0
visited = {start.make_key(): [i]}
queue = self.check_surrounding_spaces(start, visited, i)
while True:
i += 1
new_queue = []
for tile in queue:
# import pdb; pdb.set_trace()
if tile.portal_key == "ZZ":
print("Found end:", i)
return
if visited.get(tile.make_key()):
visited[tile.make_key()].append(i)
else:
visited[tile.make_key()] = [i]
new_queue += self.check_surrounding_spaces(tile, visited, i)
queue = new_queue
def check_surrounding_spaces(self, tile, visited, i):
queue = []
if tile.portal:
portal_locs = self.find_portal(tile.portal_key)
for portal in portal_locs:
try:
if self.recently_visited(visited[portal.make_key()], i):
continue
except KeyError:
return [portal]
for tile in tile.make_key_check():
try:
tile = self.tiles[tile]
except KeyError:
continue
try:
if tile.space == "." and not self.recently_visited(visited[tile.make_key()], i):
queue.append(tile)
except KeyError:
queue.append(tile)
return queue
def recently_visited(self, visited, i):
if len(visited) > 4:
return True
for time in visited:
if time >= i - 1:
return True
return False
def find_portal(self, letters):
tiles = []
for loc, tile in self.tiles.items():
if tile.portal == True and tile.portal_key == letters:
tiles.append(tile)
return tiles
class Tile:
def __init__(self, x, y, space, portal=False, portal_key=None):
self.x = x
self.y = y
self.space = space
self.portal = portal
self.portal_key = portal_key
def __repr__(self):
if self.portal:
add_key = self.portal_key
else:
add_key = ""
return "(" + str(self.x) + "," + str(self.y) + ")" + self.space + add_key
def __str__(self):
return self.__repr__
def wall(self):
if self.space == "#":
return True
else:
return False
def passage(self):
if self.space == ".":
return True
else:
return False
def make_key(self):
return str(self.x) + "," + str(self.y)
def make_key_check(self):
return [
str(self.x + 1) + "," + str(self.y),
str(self.x - 1) + "," + str(self.y),
str(self.x) + "," + str(self.y + 1),
str(self.x) + "," + str(self.y - 1),
]
s = time.time()
puzzle = Puzzle('./puzzledata/20day.txt')
puzzle.find_end()
e = time.time()
print("Time for part 1:", round(e - s, 3), "Seconds")
|
53f08e65cc83ea5040a6477e363a487a59d343ed | jpclark6/adventofcode2019 | /solutions/8day.py | 2,043 | 3.53125 | 4 | # For example, given an image 3 pixels wide and 2 pixels tall,
# the image data 123456789012 corresponds to the following image layers:
# Layer 1: 123
# 456
# Layer 2: 789
# 012
# The image you received is 25 pixels wide and 6 pixels tall.
def input():
return open("puzzledata/8day.txt", "r").read().rstrip('\n')
def slice_layers(wide, tall, data):
if len(data) % wide * tall != 0:
print("Data is not correct length")
return
image = []
layer = []
while data:
row = list(data[0:wide])
row = [int(n) for n in row]
data = data[wide:]
layer.append(row)
if len(layer) == tall:
image.append(layer)
layer = []
return image
wide = 25
tall = 6
data = input()
def find_fewest_0_layer_multi_1_by_2(image):
wide = len(image[0][0])
tall = len(image[0])
fewest = wide * tall
for i, layer in enumerate(image):
pixels = [pixel for row in layer for pixel in row]
num_zeros = pixels.count(0)
if num_zeros < fewest:
fewest = num_zeros
fewest_layer = i
pixels = [pixel for row in image[fewest_layer] for pixel in row]
return pixels.count(1) * pixels.count(2)
def print_image(image):
wide = len(image[0][0])
tall = len(image[0])
final_image = [[-1 for _ in range(wide)] for _ in range(tall)]
for l, layer in enumerate(image):
for r, row in enumerate(layer):
for p, pixel in enumerate(row):
if final_image[r][p] != -1 or pixel == 2:
pass
else:
if pixel == 1:
final_image[r][p] = "X"
elif pixel == 0:
final_image[r][p] = " "
print("\n")
for row in final_image:
print("".join(row))
print("\n")
# import pdb; pdb.set_trace()
image = slice_layers(wide, tall, data)
ans_part_1 = find_fewest_0_layer_multi_1_by_2(image)
print("Part 1 answer", ans_part_1)
print_image(image)
|
e27e14c82cf4b8a8a76981ae7ff87ec882ca35d8 | oarriaga/PyGPToolbox | /src/genBivarGaussGrid.py | 1,072 | 3.890625 | 4 | ## This code is modified from: https://scipython.com/blog/visualizing-the-bivariate-gaussian-distribution/
## How to use output:
## plt.figure()
## plt.contourf(X, Y, Z)
## plt.show()
import numpy as np
def genBivarGaussGrid(mu, cov, numSamples = 60):
size = np.sqrt(np.amax(cov))
X = np.linspace(mu[0]-4*size, mu[0]+4*size, numSamples)
Y = np.linspace(mu[1]-3*size, mu[1]+3*size, numSamples)
X, Y = np.meshgrid(X, Y)
pos = np.zeros((X.shape[0], X.shape[1], 2))
pos[:, :, 0] = X
pos[:, :, 1] = Y
def multivariate_gaussian(pos, mu, Sigma):
"""Return the multivariate Gaussian distribution on array pos.
pos is an array constructed by packing the meshed arrays of variables
x_1, x_2, x_3, ..., x_k into its _last_ dimension.
"""
n = mu.shape[0]
Sigma_det = np.linalg.det(Sigma)
Sigma_inv = np.linalg.inv(Sigma)
N = np.sqrt((2*np.pi)**n * Sigma_det)
fac = np.einsum('...k,kl,...l->...', pos-mu, Sigma_inv, pos-mu)
return np.exp(-fac / 2) / N
Z = multivariate_gaussian(pos, mu, cov)
return X,Y,Z
|
0f41df799989322b73f8aad2a7d00cac3ecdd7e7 | nadyndyaa/BASIC_PYTHON5-C | /day3.py | 1,858 | 4.0625 | 4 | #For Loop = mengulang suatu program sebanyak yg kita inginkan
# fruits = ["apple","banana","cherry","manggis","buah naga"]
#print(fruits[0])
#print(fruits[1])
#print(fruits[2])
#print(fruits[3])
#fruits = ["apple","banana","cherry"]
#for x in fruits:
#print(x)
#range
#menggunakan batasan stop saja
#for i in range(6):
#print("i")
#menggunakan batasan start dan stop
#for x in range(3,6):
#print(x)
#menggunakan batasan start, stop dan step(kelipatan)
#for m in range(0,20,2):
#print(m)
#for loop(inisialisasi ; kondisi;increment)
#for i in range(0,6,2): # 0,1,2,3,4,5,
#print(i)
#print("======")
#while loop (inisialisasi ; kondisi;increment)
#i = 0 #inisialisasi
#while i < 6:
#print(i)
#i += 2 #increment i = i +1
#CONTINUE = untuk melompati suatu kondisi
#for i in range (5):
#if i == 3:
#continue
#program tidak akan dicetak
# print(i)
#for i in range (5):
#q = input("Masukkan kode : ")
# if q == 'm':
# print("angka diskip")
# continue
#program dibawah ini tidak akan akan dieksekusi
#ketika continue aktif
# print(i)
#BREAK
#for i in range(5):
# if i == 3:
# break
#print(i)
#for i in range(10):
# q = input("Apakah anda yakin keluar ? :")
# if q == 'y' :
## print("anda keluar")
# break
#INFINTITE LOOP
#for i in range(2):
#print("i = {}".format(i))
#print("Perulangan I ")
#for j in range(3):
# print("j ={}".format(j))
# print("perulangan j")
# print()
#satu_d = [1,2,3,4,5,6,]
#dua_d =[ [1,2,3] , [4,6,6] ]
#tiga_d = [ [ [1,2],[3,4] ] , [ [5,6],[7,8] ] ]
#PKE NESTED LOOP
#for i in tiga_d:
# for j in i:
# for k in j:
# print(k)
# coba = [ [ "nadya","nami","key"] , [20,2,3] ]
# for i in coba:
# print()
# for j in range(5): |
a7da7e51ab20d1a4122af8458847451696bf500e | nadyndyaa/BASIC_PYTHON5-C | /func_example.py | 323 | 3.65625 | 4 | def luas_lingkaran(r):
return 3.14 * (r*r)
r = input('Masukan jari lingkaran :')
luas = luas_lingkaran(int(r))
print('Luasnya: {}'.format(luas))
def keliling_lingkaran(R):
return 2 * 3.14 *(R)
R = input( "masukkan keliling :")
keliling = keliling_lingkaran(int(R))
print('Kelilingnya :{}'.format(keliling))
|
582d85050e08a6b8982aae505cdc0acc273aec74 | Kyle-Koivukangas/Python-Design-Patterns | /A.Creational Patterns/4.Prototype.py | 1,661 | 4.1875 | 4 | # A prototype pattern is meant to specify the kinds of objects to use a prototypical instance,
# and create new objects by copying this prototype.
# A prototype pattern is useful when the creation of an object is costly
# EG: when it requires data or processes that is from a network and you don't want to
# pay the cost of the setup each time, especially when you know the data won't change.
from copy import deepcopy
class Car:
def __init__(self):
self.__wheels = []
self.__engine = None
self.__body = None
def setBody(self, body):
self.___body = body
def attachWheel(self, wheel):
self.__wheels.append(wheel)
def setEngine(self, engine):
self.__engine = engine
def specification(self):
print(f"body: {self.__body.shape}")
print(f"engine horsepower: {self.__engine.horsepower}")
print(f"tire size: {self.__wheels[0].size}")
#it's pretty similar to the builder pattern, except you have a method that will easily allow you to copy the instance
# this stops you from having to
def clone(self):
return deepcopy(self)
# Here is another separate example
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
print(f"({self.x}, {self.y})")
def move(self, x, y):
self.x += x
self.y += y
def clone(self, move_x, move_y):
""" This clone method allows you to clone the object but it also allows you to clone it at a different point on the plane """
obj = deepcopy(self)
obj.move(move_x, move_y)
return obj
|
1d55b37fbef0c7975527cd50a4b65f2839fd873a | Kyle-Koivukangas/Python-Design-Patterns | /A.Creational Patterns/2.Abstract_Factory.py | 1,420 | 4.375 | 4 | # An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.
# it's basically just another level of abstraction on top of a normal factory
# === abstract shape classes ===
class Shape2DInterface:
def draw(self): pass
class Shape3DInterface:
def build(self): pass
# === concrete shape classes ===
class Circle(Shape2DInterface):
def draw(self):
print("Circle.draw")
class Square(Shape2DInterface):
def draw(self):
print("Square.draw")
class Sphere(Shape3DInterface):
def draw(self):
print("Sphere.build")
class Cube(Shape3DInterface):
def draw(self):
print("Cube.build")
# === Abstract shape factory ===
class ShapeFactoryInterface:
def getShape(self, sides): pass
# === Concrete shape factories ===
class Shape2DFactory(Shape2DInterface):
@staticmethod
def getShape(sides):
if sides == 1:
return Circle()
if sides == 4:
return Square()
assert 0, f"Bad 2D shape creation: shape not defined for {sides} sides"
class Shape3DFactory(Shape3DInterface):
@staticmethod
def getShape(sides):
"""technically, sides refers to faces"""
if sides == 1:
return Sphere()
if sides == 6:
return Cube()
assert 0, f"Bad 3D shape creation: shape not defined for {sides} sides"
|
4eb05cf9d3d3b4dba91e659cc75882b5d35f9955 | FunkMarvel/CompPhys-Project-1 | /project.py | 3,546 | 3.734375 | 4 | # Project 1 FYS3150, Anders P. Åsbø
# general tridiagonal matrix.
from numba import jit
import os
import timeit as time
import matplotlib.pyplot as plt
import numpy as np
import data_generator as gen
def main():
"""Program solves matrix equation Au=f, using decomposition, forward
substitution and backward substitution, for a tridiagonal, NxN matrix A."""
init_data() # initialising data
# performing decomp. and forward and backward sub.:
decomp_and_forward_and_backward_sub()
save_sol() # saving numerical solution in "data_files" directory.
plot_solutions() # plotting numerical solution vs analytical solution.
plt.show() # displaying plot.
def init_data():
"""Initialising data for program as global variables."""
global dir, N, name, x, h, anal_sol, u, d, d_prime, a, b, g, g_prime
dir = os.path.dirname(os.path.realpath(__file__)) # current directory.
# defining number of rows and columns in matrix:
N = int(eval(input("Specify number of data points N: ")))
# defining common label for data files:
name = input("Label of data-sets without file extension: ")
x = np.linspace(0, 1, N) # array of normalized positions.
h = (x[0] - x[-1]) / N # defining step-siz.
gen.generate_data(x, name) # generating dataanal_name set.
anal_sol = np.loadtxt("%s/data_files/anal_solution_for_%s.dat" %
(dir, name))
u = np.empty(N) # array for unkown values.
d = np.full(N, 2) # array for diagonal elements.
d_prime = np.empty(N) # array for diagonal after decom. and sub.
a = np.full(N - 1, -1) # array for upper, off-center diagonal.
b = np.full(N - 1, -1) # array for lower, off-center diagonal.
# array for g in matrix eq. Au=g.
f = np.loadtxt("%s/data_files/%s.dat" % (dir, name))
g = f * h ** 2
g_prime = np.empty(N) # array for g after decomp. and sub.
def decomp_and_forward_and_backward_sub():
"""Function that performs the matrix decomposition and forward
and backward substitution."""
# setting boundary conditions:
u[0], u[-1] = 0, 0
d_prime[0] = d[0]
g_prime[0] = g[0]
start = time.default_timer() # times algorithm
for i in range(1, len(u)): # performing decomp. and forward sub.
decomp_factor = b[i - 1] / d_prime[i - 1]
d_prime[i] = d[i] - a[i - 1] * decomp_factor
g_prime[i] = g[i] - g_prime[i - 1] * decomp_factor
for i in reversed(range(1, len(u) - 1)): # performing backward sub.
u[i] = (g_prime[i] - a[i] * u[i + 1]) / d_prime[i]
end = time.default_timer()
print("Time spent on loop %e" % (end - start))
def save_sol():
"""Function for saving numerical solution in data_files directory
with prefix "solution"."""
path = "%s/data_files/solution_%s.dat" % (dir, name)
np.savetxt(path, u, fmt="%g")
def plot_solutions():
"""Function for plotting numerical vs analytical solutions."""
x_prime = np.linspace(x[0], x[-1], len(anal_sol))
plt.figure()
plt.plot(x, u, label="Numerical solve")
plt.plot(x_prime, anal_sol, label="Analytical solve")
plt.title("Integrating with a %iX%i tridiagonal matrix" % (N, N))
plt.xlabel(r"$x \in [0,1]$")
plt.ylabel(r"$u(x)$")
plt.legend()
plt.grid()
if __name__ == '__main__':
main()
# example run:
"""
$ python3 project.py
Specify number of data points N: 1000
Label of data-sets without file extension: num1000x1000
"""
# a plot is displayed, and the data is saved to the data_files directory.
|
ae0cc41da83e3c9babb8b2363ddab700cb375179 | drewthayer/intro-to-ds-sept9 | /week2/day05-strings_tuples/strings_tuples_lecture.py | 5,481 | 4.65625 | 5 | # create, analyze and modify strings
# strings are like immutable lists
# def iterate_through_str(some_str):
# for i, char in enumerate(some_str):
# print(i, char)
# # some_str_lst = list(some_str)
# # for char in some_str_lst:
# # print(char)
test_str = 'We need to pass something in this function'
# test_str[0] = 'w'
# iterate_through_str(test_str)
# commonly declare strings using the syntax string = 'some text here
# utilize the three types of string bounding characters
# 'some text' : most widely used
# some_string = 'with "single" \'quotes\''
# print(some_string)
# some_string = "with 'double' \"quotes\""
# print(some_string)
# some_string = '''with single quotes
# some more text
# '''
# print(some_string)
# some_string = """with single quotes"""
# "more text" : also used, less often
# ''' multi-line strings''' : used when \n is to be implicitly stated, through
# a simple carriage return
# used in function Docstrings
def count_unique_chars_in_str(some_string):
'''takes a string and returns a count of that string's
unique characters, not including empty spaces
Parameters
----------
some_str: (str)
we count the characters of this string
Returns
-------
count: (int)
number of characters in the string
'''
output = []
for char in some_string:
if char != ' ' and char not in output:
output.append(char)
return len(output)
# print(count_unique_chars_in_str(test_str))
# in operator
# print('a' in 'plant')
# print(4 in [1,4,7,8,2,4,6,4])
def find_anagrams(list_of_words):
output = []
for word1 in list_of_words:
for word2 in list_of_words:
print(sorted(word1), sorted(word2))
if word1 != word2:
if sorted(word1) == sorted(word2):
if word1 not in output:
output.append(word1)
return output
word_list = ['levis', 'elvis', 'bat', 'tab', 'tab', 'car', 'ark', 'tabb']
# print(find_anagrams(word_list))
# can be used for multi-line comments
# can also be """ like this """
# operating on strings with +
# 'str' + 'ing'
def concatenate_strings(str1, str2):
return str1 + ' ' + str2
str1 = 'black'
str2 = 'cat'
# print(concatenate_strings(str1, str2))
# casting data to a string with str()
# print(type(str(type(str(43.7)))))
# print(type(concatenate_strings))
# str(['hey', 'you', 'guys']) : might not do what you expect it do do
# print(str(['hey', 'you', 'guys']))
# if you want to combine characters in a string, use
def create_sentence_from_list(some_list):
some_list[0] = some_list[0][0].upper() + some_list[0][1:]
return ' '.join(some_list) + '.'
# 'this'[0] #-> 't'
test_list = ['this', 'will', 'combine', 'words']
# print(create_sentence_from_list(test_list))
# str slicing
print('not all cats hate water'[8:]) #-> 'cats hate water'
print('not all cats hate water'[0:7]) #-> 'not all'
# using for loops to iterate through strings:
# for char in 'some_string': print(char)
# str indexing
# 'some_str'[0] #--> 's'
# 'some string'[0] = 'f' will throw an error
# Write a function that returns 2 parallel lists, based on counts of letters in an input string:
# letters : list of letters in the input string
# counts : parallel list with the counts of each letter
def get_letter_counts(some_str):
letters = []
for char in some_str:
if char not in letters and char != ' ':
letters.append(char.lower())
some_str_ = some_str.lower()
counts = [0] * len(letters)
for i, char in enumerate(letters):
counts[i] = some_str_.count(char)
return (letters, counts)
# tuples
some_str = 'I am a happy string'
results = get_letter_counts(some_str)
letters = results[0]
counts = results[1]
# print(results)
animal_tup = ('dog', 'cat', 'badger')
animal_tup = ('plover', animal_tup[1], animal_tup[2])
# hashable
# only immutable types can be used as keys in a dict
def get_three_note_perms():
notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G','G#', 'A', 'A#', 'B']
chords = []
for note1 in notes:
for note2 in notes:
if note1 == note2:
continue
for note3 in notes:
if note1 != note2 and note1 != note3 and note2 != note3:
chords.append(tuple(sorted([note1, note2, note3])))
return sorted(chords)
print(len(get_three_note_perms()))
# Membership in strings
# similar to lists
# 'club' in 'very important club' #-> True
# Important string functions and methods
# len('some string')
# list('splits characters')
# 'split separates on a character'.split(' ')
# 'SoMe StRiNg'.lower()
# 'SoMe StRiNg'.upper()
# 'time tome'.replace('t', 'l')
# String interpolation with format() and fstrings
# '{}x{}x{}'.format(length, width, height)
# f'{length}x{width}x{height}'
# more on formatting for rounding and justification
# Write the is_palindrome() function
# Write the is_anagram() function
# Create and use tuples
# tuples are like immutable lists
# access elements in the tuple using our common indexing approach
# tuple values cannot be changed!
# some_tuple = ('item1', 'item2', 'item3')
# tuple_from_list = tuple([3,4,5])
# functions that return multiple values return tuples!!
# def generic_func(): return 25, 17
# type(generic_func()) #--> tuple
# unpack tuples:
# var1, var2, var3 = (1, 2, 3)
# why tuples? |
54b83e0a80cb5ddf23722b4170d671e6974686c8 | shahZ51/python-challenge | /PyPoll/main.py | 1,345 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[13]:
import os
import csv
import pandas as pd
# In[14]:
csvpath = ("Resources/election_data.csv")
df = pd.read_csv(csvpath)
df.head()
# In[15]:
total_votes = df['Voter ID'].count()
total_votes
# df.groupby('Candidate').sum()
# In[16]:
candidate_vote =df.groupby('Candidate').count()
candidate_vote = candidate_vote.reset_index(drop = False)
candidate_vote = candidate_vote.rename(columns={"Voter ID": "Number of Votes"})
candidate_vote = candidate_vote.drop(columns =['County'])
candidate_vote
# In[17]:
max_vote = candidate_vote['Number of Votes'].max()
max_vote
# In[18]:
unique_candidate =df.Candidate.unique()
unique_candidate
# In[19]:
df.head()
# In[20]:
vote_received = df.Candidate.value_counts()
vote_received
# In[21]:
percent_count = (vote_received / total_votes)*100
percent_count
# In[22]:
winner = candidate_vote.loc[candidate_vote['Number of Votes' ] == max_vote ] ['Candidate'].iloc[0]
winner
# In[25]:
# Printing terminal
output = (
f"Election Results\n"
f"---------------------------------\n"
f"Total Votes: {total_votes}\n"
f"---------------------------------\n"
f"{percent_count}% {vote_received} \n"
f"---------------------------------\n"
f" Winner: {winner}\n"
f"---------------------------------\n"
f"```\n"
)
print(output)
|
e24fe24b95d36d74782e57d0754e6fac56007425 | tofuu/CSE-Novello-Final | /__main__.py | 676 | 3.84375 | 4 | # -*- coding: utf-8 -*-
#Before you push your additions to the code, make sure they exactly fit the parameters described in the project!
#Let's write delicious code. がんばってくらさい!
# Abirami
import math
def list_prime_factors(num):
n = int(num)
prime = []
k=1
if n%2==0:
prime.append(2)
flag = 0
while (2*k+2)**2 < n:
if n%(2*k+1)==0:
for p in prime:
if (2*k+1)%p ==0:
flag = 1
if flag ==+ 0:
prime.append(2*k+1)
flag = 0
k=k+1
if len(prime)== 0:
prime.append(n)
print prime
return prime |
d40f8d250528001d359c09eecf6505e970cb426e | vbodell/ii1304-modellering | /simulation.py | 2,885 | 3.625 | 4 | from population import Population
class Simulation:
def __init__(self, N, probInfect, minDaysSick, maxDaysSick, probDeath,
initialSick, VERBOSE, SEED):
self.N = N
self.probInfect = probInfect
self.totalSickCount = len(initialSick)
self.totalDeathCount = 0
self.printInitString(VERBOSE, SEED, N, probInfect, minDaysSick,
maxDaysSick, probDeath, initialSick)
self.currentSimulationDay = 0
self._population = Population(N, probInfect, minDaysSick,
maxDaysSick, probDeath, initialSick, VERBOSE, SEED)
print(self._population)
def start(self):
while not self.simulationFinished():
self.currentSimulationDay += 1
values = self._population.simulateDay(self.currentSimulationDay)
self.printDailyReport(values)
self.totalSickCount += values['gotInfected']
self.totalDeathCount += values['died']
self.printCumulativeReport()
def simulationFinished(self):
return self._population.allDead or self._population.allLivingHealthy
def printDailyReport(self, values):
print("Day %d:" % self.currentSimulationDay)
print(" # got infected: %d" % values['gotInfected'])
print(" # deaths: %d" % values['died'])
print(" # got healthy: %d" % values['gotHealthy'])
print(" # infected: %d" % values['infected'])
print(self._population)
def printCumulativeReport(self):
if not self.simulationFinished():
print("Simulation hasn't terminated yet!")
return
print("===Simulation ran a total of %d days===" % self.currentSimulationDay)
print(" Total # of infected: %d" % self.totalSickCount)
print(" Total # of deaths: %d" % self.totalDeathCount)
print(" Proportion infected: %.3f" % (self.totalSickCount/(self.N*self.N)))
print("CSV:%.3f,%.3f" % (self.probInfect, self.totalSickCount/(self.N*self.N)))
def printInitString(self, VERBOSE, SEED, N, probInfect,
minDaysSick, maxDaysSick, probDeath, initialSick):
initSimString = "\n### Initializing simulation with the" +\
" following parameters ###\n"
initSimString += " Verbose=%s\n" % VERBOSE
initSimString += " SEED=%s\n" % SEED
initSimString += " N=%d\n" % N
initSimString += " probInfect=%.2f\n" % probInfect
initSimString += " minDaysSick=%d\n" % minDaysSick
initSimString += " maxDaysSick=%d\n" % maxDaysSick
initSimString += " probDeath=%.2f\n" % probDeath
initSimString += " initialSick=%d\n" % len(initialSick)
for ndx in range(len(initialSick)):
initSimString += " Sick position #%d: [%d,%d]\n" % (ndx+1,
initialSick[ndx][0], initialSick[ndx][1])
print(initSimString)
|
7b8625d7a26569c437a7ea560b2c56596db48fb1 | atomsk752/study | /180806_oop/dragon_game_item.py | 4,697 | 3.703125 | 4 | import random
class Dragon:
def __init__(self, lev, name):
self.lev = lev
self.hp = lev * 10
self.jewel = lev % 3
self.name = name
self.attack = self.lev * 10
def giveJewel(self):
return self.jewel
def attackHero(self):
print(self.name + ": 캬오~~~~~~~`ㅇ'")
return random.randint(1, self.attack)
def damage(self, amount):
print(self.name + ": 꾸엑....................ㅠ_ㅠ")
self.hp -= amount
if self.hp > 0:
print("[드래곤의 체력이", self.hp, "로 줄었다]")
else:
print(self.name + ": 크으으... 인간따위에게......")
return self.hp
def __str__(self):
return self.name + " 레벨: " + str(self.lev)+ " HP:" + str(self.hp)
class Hero:
def __init__(self, name, hp):
self.name = name
self.hp = hp
self.mp = 100 - hp
self.min_mp = 1
def attackDragon(self):
return random.randint(self.min_mp, self.mp)
def damage(self, amount):
print(self.name+": 윽....................ㅠ_ㅠ")
self.hp -= amount
if self.hp > 0:
print("[플레이어의 체력이", self.hp, "로 줄었다]")
return self.hp
def __str__(self):
return self.name
class DragonContainer:
def __init__(self, name_list):
self.dragons = [Dragon(idx + 1, x) for idx, x in enumerate(name_list)]
def getNext(self):
if len(self.dragons) == 0:
return None
return self.dragons.pop(0)
class Colosseum:
def __init__(self,container):
self.container = container
self.player = None
def makePlayer(self):
name = input("플레이어의 이름을 입력하시오: ")
hp = int(input("HP는 얼마나 하겠습니까? (최대 100) "))
self.player = Hero(name,hp)
print("[캐릭터 "+ self.player.name,"이/가 만들어 졌습니다]")
print("[게임을 시작합니다]")
print("[BGM.... Start.............]")
def fight(self):
dragon = self.container.getNext()
if dragon == None:
print("[용사는 전설이 되었다]")
return
print("")
print("====================================")
print("["+dragon.name+"]"," [레벨:", str(dragon.lev)+"]","[데미지: 1 ~ "+str(dragon.attack)+"]")
print("["+self.player.name+"]"," [HP:", str(self.player.hp)+"]",
"[데미지: "+str(self.player.min_mp)+" ~ "+str(self.player.mp)+"]")
print("====================================")
while True:
power = self.player.attackDragon()
input("")
print("[용사가 공격했다", "데미지:", power,"]")
dragonhp = dragon.damage(power)
if dragonhp <= 0:
print("[현재 플레이어 HP: ", self.player.hp,"]")
print("[Next Stage~]")
jewel = dragon.giveJewel()
if jewel == 0:
self.player.hp += 30
print("[보너스 체력이 30이 추가되었습니다]")
random_box=random.randint(0,3)
if random_box == 1:
print("[롱소드를 얻으셨습니다. 최소 공격력 증가(+10)]")
self.player.min_mp += 10
elif random_box == 2:
print("[물약을 얻으셨습니다. HP 증가(+20)]")
self.player.hp += 20
elif random_box == 3:
print("[갑옷을 얻으셨습니다. 드래곤 최대 데미지 감소(-10)]")
for x in self.container.dragons:
x.attack -= 10
else:
print("[드래곤 사체에서 아무것도 나오지 않았습니다]")
print("[Mission Complete]")
break
dragonattack=dragon.attackHero()
print("[드래곤이",dragonattack,"만큼 데미지를 주었다]")
herohp = self.player.damage(dragonattack)
if herohp <= 0:
print("["+self.player.name + "은/는 " + dragon.name +"에게 죽었습니다]")
print(" [Game Over]")
return
self.fight()
name_list=["해츨링","그린드래곤","블랙드래곤","화이트드래곤","블루드래곤","실버드래곤",
"레드드래곤","골드드래곤","레인보우드래곤","G-dragon"]
container = DragonContainer(name_list)
ground = Colosseum(container)
ground.makePlayer()
ground.fight()
|
66484192d25bf31838df22abe82623a8e11567b9 | atomsk752/study | /180806_oop/lucky_box.py | 461 | 3.515625 | 4 | import random
class Item:
def __init__(self, str):
self.str = str
def __str__(self):
return "VALUE: " + self.str
class Box:
def __init__(self, items):
self.items = items
random.shuffle(self.items)
def selectOne(self):
return self.items.pop()
item_list = [Item('O') ] * 5
item_list.append(Item('X'))
box = Box(item_list)
for x in range(6):
print(box.selectOne())
|
2350246ad0d7208ad8a2136740f6fb83f1b662bb | kenjirotorii/burger_war_kit | /autotest/draw_point_history.py | 781 | 3.5625 | 4 | #!/usr/bin/env python
import pandas as pd
import matplotlib.pyplot as plt
import sys
def draw_graph(csv_file, png_file):
df = pd.read_csv(csv_file,
encoding="UTF8",
names=('sec', 'you', 'enemy', 'act_mode', 'event',
'index', 'point', 'before', 'after'),
usecols=['sec', 'you', 'enemy'],
index_col='sec')
df.plot(color=['r','b'], drawstyle='steps-post', fontsize=15)
plt.title("Point history")
plt.xlabel("timestamp [sec]")
plt.ylabel("point")
plt.savefig(png_file)
if __name__ == "__main__":
if (len(sys.argv) != 3):
print("[usage]" + sys.argv[0] + " CSV_FILE PNG_FILE")
exit(1)
draw_graph(sys.argv[1], sys.argv[2])
|
7d5e1744f843893d418819a14cfc6c7f200de686 | yunakim2/Algorithm_Python | /프로그래머스/level2/짝지어 제거하기.py | 326 | 3.78125 | 4 | def solution(s):
stack = []
for char in s:
if not stack:
stack.append(char)
elif stack[-1] == char:
stack.pop()
else:
stack.append(char)
return 1 if not stack else 0
if __name__ == "__main__":
print(solution("baabaa"))
print(solution("cdcd"))
|
fb317af1c41098a48c682ba0ec9337d69b165fda | yunakim2/Algorithm_Python | /백준/재귀/baekjoon10872.py | 141 | 3.625 | 4 | num = int(input())
def fac (i) :
if(i == 1 ) : return 1
if(i ==0) : return 1
else :
return i*fac(i-1)
print(fac(num)) |
f422a1ef411b40fb0553d8e34ca2c780980dd223 | yunakim2/Algorithm_Python | /프로그래머스/level2/가장 큰 수.py | 457 | 3.5625 | 4 | def solution(numbers):
combi_number = []
bigger_number = ''
for number in numbers:
tmp_number = (str(number)*4)[:4]
combi_number.append([''.join(tmp_number), number])
combi_number.sort(reverse=True)
for _, item in combi_number:
bigger_number += str(item)
return str(int(bigger_number))
if __name__ == '__main__':
print(solution([0,0,0,1000]))
print(solution([6,10,2]))
print(solution([0,0,0,0]))
|
b0eb26a51875aaa4516f1e8db4c2d9a23ec444a0 | yunakim2/Algorithm_Python | /백준/실습 1/baekjoon10996.py | 105 | 3.953125 | 4 | a = int(input())
even = a//2
odd = a- a//2
for i in range(a) :
print("* "*odd)
print(" *"*even) |
93337a29ae77fba36b750bcbf5aeaa16e6e996ee | yunakim2/Algorithm_Python | /알고리즘특강/그리디_숫자카드게임.py | 292 | 3.515625 | 4 |
data = """3 3
3 1 2
4 1 4
2 2 2"""
data = data.split("\n")
n, m = map(int, data[0].split())
arr = []
small= []
arr.append(map(int,data[1].split()))
arr.append(map(int,data[2].split()))
arr.append(map(int,data[3].split()))
for i in range(n):
small.append(min(arr[i]))
print(max(small)) |
eb309a4c1f80124cfba320759ad9e35c5840c7d5 | yunakim2/Algorithm_Python | /코테/1.py | 1,044 | 3.578125 | 4 | '''
정렬 은 우선 빈도,
같으면 크기 순
'''
from collections import defaultdict
from collections import deque
def sorting(arr):
tmp_arr = []
for i in range(len(arr)):
size = arr[i][1]
for j in range(i+1,len(arr)):
if size != arr[j][1]:
break
else:
else:
for i in range(len(arr)):
for j in range(i, len(arr)):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
def coutingSort(arr):
count_arr = defaultdict()
for item in arr:
if item not in count_arr.keys():
count_arr[item] = 1
else:
count_arr[item] += 1
count_arr = sorting(count_arr)
# count_arr = list(sorted(count_arr.items(), key=lambda x : -x[1]))
res = []
for idx in count_arr:
for _ in range(int(idx[1])):
res.append(idx[0])
return res
if __name__ == '__main__':
arr = [1,3,3,5,5,6,7,8]
print(coutingSort(arr)) |
e98f224870424065636d98b986db536bb8fe0296 | yunakim2/Algorithm_Python | /프로그래머스/level1/세 소수의 합.py | 866 | 3.796875 | 4 | def solution(n):
def sieve(n):
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
for candidate in range(2, n + 1):
if not is_prime[candidate]:
continue
for multiple in range(candidate * candidate, n + 1, candidate):
is_prime[multiple] = False
return [idx for idx, value in enumerate(is_prime) if value]
def dfs(cur_idx, count, total):
if count == 3:
if total == n:
return 1
else:
return 0
if cur_idx >= len(prime_num):
return 0
return dfs(cur_idx + 1, count, total) + dfs(cur_idx + 1, count + 1, total + prime_num[cur_idx])
prime_num = sieve(n)
return dfs(0, 0, 0)
if __name__ == "__main__":
print(solution(33))
print(solution(9))
|
5f30daf7d6e6fca7a3d058e9834ce3d2faf63234 | yunakim2/Algorithm_Python | /프로그래머스/level4/버스 여행 - DFS.py | 725 | 3.796875 | 4 | def solution(n,signs):
def dfs(source, signs, visited_stations):
if len(visited_stations) == len(signs):
return
for destination in range(len(signs)):
if signs[source][destination] == 1 and destination not in visited_stations:
visited_stations.add(destination)
dfs(destination, signs, visited_stations)
for source in range(n):
visited_stations = set()
dfs(source, signs, visited_stations)
for destination in visited_stations:
signs[source][destination] = 1
return signs
if __name__ == "__main__":
print(solution(3, [[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
print(solution(3,[[0,0,1],[0,0,1],[0,1,0]]))
|
424206f92ae36b0920b12bd37b657e4a432ef419 | yunakim2/Algorithm_Python | /프로그래머스/level2/전화번호 목록.py | 634 | 3.796875 | 4 |
def solution(phone_book):
phone_book.sort()
phone_book = dict([(index, list(phone)) for index, phone in enumerate(phone_book)])
for i in range(len(phone_book)):
size = len(phone_book[i])
for j in range(i+1, len(phone_book)):
if len(phone_book[j]) >= size:
if phone_book[j][0:size] == phone_book[i]:
return False
else:
return True
if __name__ == "__main__":
print(solution(["0", "97674223", "1195524421"]))
print(solution(["123","456","789"]))
print(solution(["123", "456", "4567", "999"]))
print(solution(["113","44","4544"]))
|
6d2877bb66b8da148e0e06c272588b4e5bc2dfdf | yunakim2/Algorithm_Python | /카카오/2021 카카오 공채/6.py | 631 | 3.546875 | 4 | from collections import deque
def solution(board, skill):
for types, r1, c1, r2, c2, degree in skill:
for r in range(r1, r2+1):
for c in range(c1, c2+1):
if types == 1:
board[r][c] -= degree
else:
board[r][c] += degree
answer = [b for board_list in board for b in board_list if b > 0]
return len(answer)
if __name__ == "__main__":
print(solution([[5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5]],
[[1, 0, 0, 3, 4, 4], [1, 2, 0, 2, 3, 2], [2, 1, 0, 3, 1, 2], [1, 0, 1, 3, 3, 1]]))
|
adfa7b36c3cfef17161452849821e96b7a887607 | yunakim2/Algorithm_Python | /백준/실습 1/baekjoon10039.py | 109 | 3.6875 | 4 | sum = 0
for i in range(0,5) :
a = int(input())
if a<40 : sum+=40
else : sum += a
print(sum//5) |
89197c0273cfaf25f86785d59634cc8470f27713 | yunakim2/Algorithm_Python | /백준/1차원 배열/baekjoon4344.py | 270 | 3.578125 | 4 | num = int(input())
for i in range(num) :
data = list(map(int, input().split(' ')))
cnt = data[0]
del data[0]
avg = sum(data) / cnt
k = 0
for j in range(cnt) :
if(data[j]>avg) :
k+=1
print("%.3f"%round((k/cnt*100),3)+"%") |
4d4626a0cdfaf504bc794b78b806e2ac10cd1ee6 | yunakim2/Algorithm_Python | /프로그래머스/level1/짝수와 홀수.py | 96 | 3.671875 | 4 | def solution(num):
if num%2 !=0 : answer ="Odd"
else : answer = "Even"
return answer |
c264959d445653be32a98b1838bd10132ceaa205 | JinhanM/leetcode-playground | /19. 删除链表的倒数第 N 个结点.py | 607 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0, head)
front, back = dummy, head
for _ in range(n):
back = back.next
while back:
back = back.next
front = front.next
front.next = front.next.next
return dummy.next |
1994561a1499d77769350b55a6f32cdd111f31fa | Ajat98/LC-2021 | /easy/buy_and_sell_stock.py | 1,330 | 4.21875 | 4 | """
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
minProfit = float('inf') #to represent largest possible val
#TOO SLOW on large arrays
# for i in range(len(prices)):
# for x in range(i, len(prices)):
# profit = prices[x] - prices[i]
# if profit > maxProfit:
# maxProfit = profit
#compare min buy price difference to max sell price at every step, keep tracking as you go.
for i in prices:
minProfit = min(i, minProfit)
profit = i - minProfit
maxProfit = max(profit, maxProfit)
return maxProfit
|
0b19bc5f6af31fb9ef1e9b217e0f99405b139986 | mchristofersen/tournament-project | /vagrant/tournament/tournament.py | 9,965 | 3.578125 | 4 | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
# This file can be used to track the results of a Swiss-draw style tournament
# First use set_tournament_id() to generate a new tournament
# Register new players with register_player()
# Once all players are registered, assign pairings with swiss_pairings()
# As matches are finished, report the winner with report_match()
# For a simple match with a clear winner:
# use report_match(winner, loser) where winner and loser are player_ids
# For a match that resulted in a draw:
# use report_match(player1_id, player2_id, True)
# Use swiss_pairings() again once the round is finished.
# Once the tournament is over, run finalRankings() to print the final results.
import psycopg2
import random
import re
tournament_id = None
def set_tournament_id(t_id=0):
"""
Sets a global tournament_id to keep track of the current tournament.
Takes an optional argument to assign a tournament other than the first.
"""
new_tournament(t_id)
global tournament_id
tournament_id = t_id
return t_id
def new_tournament(t_id):
pg, c = connect()
try:
c.execute("INSERT INTO tournaments \
VALUES ('GENERATED_TOURNAMENT', %s)", (t_id,))
pg.commit()
except psycopg2.IntegrityError:
pg.rollback()
finally:
pg.close()
def connect():
"""Connect to the PostgreSQL database.
Returns a database connection."""
pg = psycopg2.connect("dbname = tournament")
c = pg.cursor()
return pg, c
def execute_query(query, variables=()):
pg, c = connect()
c.execute(query, variables)
if re.match("(^INSERT|^UPDATE|^DELETE)", query, re.I) is not None:
pg.commit()
pg.close()
else:
fetch = c.fetchall()
pg.close()
return fetch
def delete_matches():
"""Remove all the match records from the database."""
execute_query("DELETE FROM matches WHERE tournament_id = %s",
(tournament_id,))
def delete_players():
"""Remove all the player records from the database."""
execute_query("DELETE FROM players WHERE tournament_id = %s",
(tournament_id,))
def count_players():
"""Returns the number of players currently registered."""
return_value = execute_query("SELECT COUNT(*) FROM players\
WHERE tournament_id = %s",
(tournament_id,))
return return_value[0][0]
def register_player(name):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique).
"""
execute_query("INSERT INTO players (name, tournament_id, prev_opponents)\
VALUES (%s, %s, %s)", (name, tournament_id, [],))
def player_standings():
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place,
or a player tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by the database)
name: the player's full name (as registered)
wins: the number of matches the player has won
matches: the number of matches the player has played
"""
r_value = execute_query("SELECT * FROM tournament_filter(%s)",
(tournament_id,))
return r_value
def report_match(winner, loser, draw=False):
"""Records the outcome of a single match between two players.
For a simple match with a clear winner:
use report_match(winner, loser) where winner and loser are player_ids
For a match that resulted in a draw:
use report_match(player1_id, player2_id, True)
Args:
winner: the player_id of the player who won
loser: the player_id of the player who lost
draw: boolean on whether the match was a draw or split. Defaults to False
"""
if not draw:
execute_query("""UPDATE players SET
matches_played = matches_played +1,
prev_opponents = prev_opponents || %s
WHERE player_id = %s and tournament_id = %s""",
(winner, loser, tournament_id))
execute_query("UPDATE players SET points = points + 1.0,\
matches_played = matches_played +1,\
prev_opponents = prev_opponents || %s\
WHERE player_id = %s and tournament_id = %s",
(loser, winner, tournament_id))
else:
for player in range(0, 1):
execute_query("""UPDATE players SET points = (points + 0.5)
WHERE (player_id = %s or player_id = %s) and
tournament_id = %s""",
(winner, loser, tournament_id))
execute_query("INSERT INTO matches VALUES (%s, %s, %s, %s)",
(winner, loser, tournament_id, draw))
def pick_random_player(players):
"""
Picks a player at random from the standings, checks that they haven't
already received a bye, and if not, assigns them a bye.
Returns an even list of players to be assigned pairings.
"""
global bye_player
prev_bye = True
while prev_bye:
random.shuffle(players)
bye_player = players[0]
prev_bye = execute_query("Select bye from players\
WHERE player_id = %s",
(bye_player[0],))[0][0]
standings = player_standings()
standings.remove(bye_player)
assign_bye(bye_player[0])
return standings
def swiss_pairings():
"""Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a player adjacent
to him or her in the standings.
Returns:
A list of tuples, each of which contains (id1, name1, id2, name2)
id1: the first player's unique id
name1: the first player's name
id2: the second player's unique id
name2: the second player's name
"""
standings = player_standings()
pairings = []
if len(standings) % 2 != 0:
pick_random_player(standings)
while len(standings) > 1:
idx = 1
prev_opponents = execute_query("""SELECT prev_opponents from players
WHERE player_id = %s""",
(standings[0][0],))
while True:
if standings[idx][0] in prev_opponents and\
idx != len(standings)-1:
idx += 1
else:
pairings.append(sum([list(standings[0][0:2]),
list(standings[idx][0:2])], []))
standings.pop(idx)
standings.pop(0)
break
return pairings
def final_rankings():
"""
Calculates any tie-breakers and prints the rankings
in table form. Can be used on any round.
"""
ties = 1 # used to keep track of how many players tied at a certain rank
last_record = [0, 0] # used to track the previous players record
rank = 0 # keeps track of the current rank during iteration
players = execute_query("""SELECT player_id, prev_opponents FROM players
WHERE tournament_id = %s
ORDER BY points DESC, name""",
(tournament_id,))
for (player, opponents) in players:
player_sum = 0 # tracks a certain player's opponent points
for opponent in opponents:
player_sum += execute_query("""SELECT points FROM players
WHERE player_id = %s""",
(opponent,))[0][0]
execute_query("""UPDATE players SET opp_win = %s
WHERE player_id = %s""",
(float(player_sum)/len(opponents), player,))
standings = execute_query("""SELECT name, points, opp_win FROM players
ORDER BY points DESC, opp_win DESC, name""")
print "\nCurrent Rankings:"
for player in standings:
if [player[1], player[2]] != last_record:
rank += 1 * ties
ties = 1
else: # Must be a tie, increment ties multiplier
ties += 1
last_record = [player[1], player[2]]
print("%d.: %s" % (rank, player))
def assign_bye(player):
"""
Assigns a bye to a player and updates their points.
Should be called automatically when necessary.
:param player: The player's id.
"""
execute_query("""UPDATE players SET bye = TRUE, points = points + 1
WHERE player_id = %s and tournament_id = %s """,
(player, tournament_id,))
def main():
"""
Sets the tournament_id if it is not already. Runs on initialization.
"""
if tournament_id is None:
print("""Tournament id not found...\
\nChecking for existing tournaments...""")
t_id = set_tournament_id()
t_name = execute_query("""
Select tournament_name from tournaments
WHERE tournament_id = %s
""", (t_id,))[0][0]
print("""Using tournament: %s\
\nTo change this, use setTournament(t_id)""" % t_name)
if __name__ == '__main__':
main()
|
3b76875ec54479b956a45331c3863f956a61df9a | mounui/python | /examples/use_super.py | 643 | 4.125 | 4 | # -*- coding: utf-8 -*-
# super使用 避免基类多次调用
class Base(object):
def __init__(self):
print("enter Base")
print("leave Base")
class A(Base):
def __init__(self):
print("enter A")
super(A, self).__init__()
print("leave A")
class B(Base):
def __init__(self):
print("enter B")
super(B, self).__init__()
print("leave B")
class C(A, B):
def __init__(self):
print("enter C")
super(C, self).__init__()
print("leave C")
C()
# 测试结果
# enter C
# enter A
# enter B
# enter Base
# leave Base
# leave B
# leave A
# leave C
|
7290d9abe62da81613c2bc7a12b0aead3b5e8ae4 | mounui/python | /examples/demo1.py | 387 | 4 | 4 | print('hello world!')
name = input('please enter your name:')
print('hello,',name)
print(1024 * 768)
print(5^2)
print('haha')
bmi = 80.5 / (1.75 ** 2)
if bmi >= 32:
print('严重肥胖')
elif bmi >= 28:
print('肥胖')
elif bmi >= 25:
print('过重')
elif bmi >= 18.5:
print('正常')
else:
print('过轻')
sum = 0
for x in range(101):
sum += x
print(sum)
|
0b495e493aaf605222998fee8c76b4d02062a94a | RomanKlimov/PythonCourse | /HomeW_13.09.17/MultiTable.py | 136 | 3.609375 | 4 | def mt(number):
for i in range(1, 10):
print(str(number) + " x " + str(i) + " = " + str(number * i))
i += 1
mt(5)
|
ce6e1845c663b30f80d21a5481249fdf685cfef8 | ML-Baidu/classification | /ml/classfication/ID3.py | 4,407 | 3.75 | 4 | import numpy as np
import math
'''
@author: FreeMind
@version: 1.1
Created on 2014/2/26
This is a basic implementation of the ID3 algorithm.
'''
class DTree_ID3:
def __init__(self,dataSet,featureSet):
#Retrieve the class list
self.classList = set([sample[-1] for sample in dataSet])
if ((len(featureSet)+1) != (len(dataSet[1]))):
print("The feature set do not match with the data set,please check your data!")
#Set the feature set
self.featureSet = featureSet
def runDT(self,dataSet):
##recursive run DT, return a dictionary object
##1.check boundary: two case - only one tuple
## or all tuples have the same label
##2.compute inforGain for each feature, select
## feature corresponding to max inforGain
##3.split data set on that feature, recursively
## call runDT on subset until reaching boundary
classList = set([sample[-1] for sample in dataSet])
#If the data set is pure or no features
if len(classList)==1:
return list(classList)[-1]
if len(self.featureSet)==0: #no more features
return self.voteForMost(dataSet,classList)
bestSplit = self.findBestSplit(dataSet)
bestFeatureLabel = self.featureSet[bestSplit]
dTree = {bestFeatureLabel:{}}
featureValueList = set([example[bestSplit] for example in dataSet])
for value in featureValueList:
subDataSet = self.splitDataSet(dataSet,bestSplit,value)
self.featureSet.remove(self.featureSet[bestSplit])
dTree[bestFeatureLabel][value] = self.runDT(subDataSet)
self.featureSet.insert(bestSplit,bestFeatureLabel)
return dTree
#Find the most in the set
def voteForMost(self,dataSet,classList):
count = np.zeros(len(self.classList))
for sample in dataSet:
for index in range(len(self.classList)):
if sample[-1]==list(self.classList)[index]:
count[index] = count[index]+1
maxCount = 0
tag = 0
for i in range(len(count)):
if count[i]>maxCount:
maxCount = count[i]
tag = i
return list(self.classList)[tag]
#Compute all infoGains,return the best split
def findBestSplit(self,dataSet):
#initialize the infoGain of the features
infoGain = 0
tag = 0
for i in range(len(self.featureSet)):
tmp = self.infoGain(dataSet,i)
if(tmp > infoGain):
infoGain = tmp
tag = i
return tag
def entropy(self,dataSet):
total = len(dataSet)
cal = np.zeros(len(self.classList))
entropy = 0
for sample in dataSet:
index = list(self.classList).index(sample[-1],)
cal[index] = cal[index]+1
for i in cal:
proportion = i/total
if proportion!=0:
entropy -= proportion*math.log(proportion,2)
return entropy
def infoGain(self,dataSet,featureIndex):
origin = self.entropy(dataSet)
featureValueList = set([sample[featureIndex] for sample in dataSet])
newEntropy = 0.0
for val in featureValueList:
subDataSet = self.splitDataSet(dataSet,featureIndex,val)
prob = len(subDataSet)/(len(dataSet))
newEntropy += prob*self.entropy(subDataSet)
return origin-newEntropy
def splitDataSet(self,dataSet,featureIndex,value):
subDataSet = []
for sample in dataSet:
if sample[featureIndex] == value:
reducedSample = sample[:featureIndex]
reducedSample.extend(sample[featureIndex+1:])
subDataSet.append(reducedSample)
return subDataSet
def predict(self,testData):
##predict for the test data
pass
if __name__ == "__main__":
dataSet = [["Cool","High","Yes","Yes"],["Ugly","High","No","No"],
["Cool","Low","No","No"],["Cool","Low","Yes","Yes"],
["Cool","Medium","No","Yes"],["Ugly","Medium","Yes","No"]]
featureSet = ["Appearance","Salary","Office Guy"]
dTree = DTree_ID3(dataSet,featureSet)
tree = dTree.runDT(dataSet)
print(tree) |
ac697cfc455c987e41da0e89fc33de44e13b7d28 | Raunaka/guvi | /ideone_JwxIRn.py | 201 | 3.71875 | 4 | x = int(input())
y = int(input())
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
print( hcf)
|
e8f2b3ddb028397e083bad8369be3589e3e73405 | Raunaka/guvi | /palin.py | 98 | 3.546875 | 4 | a=input()
a=list(a)
if a==a[::-1]:
while a==a[::-1]:
a[-1]=""
q=""
for i in a:
q=q+i
print(q)
|
63a9898b547389e60826521a27a60a8ca4c6d70b | rsirs/foobar | /dont_mind_map.py | 2,368 | 3.78125 | 4 | def answer(subway):
dest = [{},{},{}]
max_route_length = len(subway)
import itertools
directions = '01234'
for closed_station in range(-1, len(subway)):
for path_length in range(2,6):
current_directions =directions[:len(subway[0])]
for route in itertools.product(current_directions,repeat = path_length):
dest[0][route] = destination(route,0,subway,closed_station)
dest[2][route] = destination(route,2,subway,closed_station)
dest[1][route] = destination(route,1,subway,closed_station)
for route in dest[0]:
if (dest[0][route] == dest[1][route]) and closed_station == -1:
satisfy = True
for station in range(2,3):
if (dest[0][route] != destination(route,station,subway,closed_station)):
satisfy = False
if satisfy:
return -1
elif closed_station == 1 and (dest[0][route] == dest[2][route]):
satisfy = True
if len(subway) == 3:
return closed_station
elif (dest[0][route] != destination(route,3,subway,closed_station)):
satisfy = False
if satisfy:
return closed_station
elif closed_station != -1 and (dest[0][route] == dest[1][route]):
satisfy = True
for station in range(2,3):
if (dest[0][route] != destination(route,station,subway,closed_station)):
satisfy = False
if satisfy:
return closed_station
return -2
def destination(path, station, subway,closed_station):
current_station = station
for direction in path:
direction = int(direction)
previous_station = current_station
current_station = subway[current_station][direction]
if current_station == closed_station:
if subway[current_station][direction] == closed_station:
current_station = previous_station
else:
current_station = subway[current_station][direction]
destination = current_station
return destination
|
aebfbbd797d10209adeca8e2005940939f7198f6 | bugmany/nlp_demo | /src/Basic_knowledge/Manual_implementation_neural_network/简单感知器.py | 1,481 | 4.03125 | 4 |
'''
1. 处理单个输入
2. 处理2分类
'''
class Perceptron(object):
'''
初始化参数lr(用于调整训练步长,即 learning),iterations(迭代次数),权重w 与 bias 偏执
'''
def __init__(self,eta=0.01,iterations=10):
self.lr = eta
self.iterations = iterations
self.w = 0.0
self.bias = 0.0
#'''
#公式:
#Δw = lr * (y - y') * x
#Δbias = lr * (y - y')
#'''
def fit(self,X,Y):
for _ in range(self.iterations):
for i in range(len(X)):
x = X[i]
y = Y[i]
#首先获得真实值 y 与预测值 y' 的偏差,乘以一个较小的参数
# 【lr 值过小导致训练时间过长,难以判断是否收敛】
# 【lr 值过大则容易造成步长过大而无法收敛】
update = self.lr * (y - self.predict(x))
self.w += update * x
self.bias += update
# y'(预测值) = w * x + bias
def net_input(self,x):
return self.w * x + self.bias
def predict(self,x):
return 1.0 if self.net_input(x) > 0.0 else 0.0
x = [1, 2, 3, 10, 20, -2, -10, -100, -5, -20]
y = [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
model = Perceptron(0.01,10)
model.fit(x,y)
test_x = [30, 40, -20, -60]
for i in range(len(test_x)):
print('input {} => predict: {}'.format(test_x[i],model.predict(test_x[i])))
print(model.w)
print(model.bias) |
1e598b5c0e8208f88db6eda0aecddbc0f1b05b2c | Quyxor/project_euler | /problem_002/fibonacci.py | 526 | 3.9375 | 4 | '''
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
'''
def fib_generator(n):
a, b = 1, 1
while b <= n:
a, b = b, a + b
yield a
def calculate(n):
return sum(i for i in fib_generator(n) if not i % 2)
if __name__ == "__main__":
print(calculate(4000000)) |
e4b6dd203d9d6cbb9a0da72e15f3e382cc765305 | jameslamb/doppel-cli | /doppel/PackageCollection.py | 3,609 | 3.59375 | 4 | """
``PackageCollection`` implements methods for comparing
a list of multiple ``PackageAPI`` objects.
"""
from typing import Dict, List, Set
from doppel.PackageAPI import PackageAPI
class PackageCollection:
"""
Create a collection of multiple ``PackageAPI`` objects.
This class contains access methods so you don't have to
keep doing ``for package in packages`` over a collection
of ``PackageAPI`` instances.
"""
def __init__(self, packages: List[PackageAPI]):
"""
Class that holds multiple ``PackageAPI`` objects.
:param packages: List of ``PackageAPI`` instances to be
compared to each other.
"""
for pkg in packages:
assert isinstance(pkg, PackageAPI)
pkg_names = [pkg.name() for pkg in packages]
if len(set(pkg_names)) < len(packages):
msg = "All packages provided to PackageCollection must have unique names"
raise ValueError(msg)
self.pkgs = packages
def package_names(self) -> List[str]:
"""
Get a list of all the package names in this collection.
"""
return [p.name() for p in self.pkgs]
def all_classes(self) -> List[str]:
"""
List of all classes that exist in at least
one of the packages.
"""
out: Set[str] = set([])
for pkg in self.pkgs:
out = out.union(pkg.class_names())
return list(out)
def shared_classes(self) -> List[str]:
"""
List of shared classes
across all the packages in the collection
"""
# Only work on shared classes
out = set(self.pkgs[0].class_names())
for pkg in self.pkgs[1:]:
out = out.intersection(pkg.class_names())
return list(out)
def non_shared_classes(self) -> List[str]:
"""
List of all classes that are present in
at least one but not ALL packages
"""
all_classes = set(self.all_classes())
shared_classes = set(self.shared_classes())
return list(all_classes.difference(shared_classes))
def all_functions(self) -> List[str]:
"""
List of all functions that exist in at least
one of the packages.
"""
out: Set[str] = set([])
for pkg in self.pkgs:
out = out.union(pkg.function_names())
return list(out)
def shared_functions(self) -> List[str]:
"""
List of shared functions
across all the packages in the collection
"""
# Only work on shared classes
out = set(self.pkgs[0].function_names())
for pkg in self.pkgs[1:]:
out = out.intersection(pkg.function_names())
return list(out)
def non_shared_functions(self) -> List[str]:
"""
List of all functions that are present in
at least one but not ALL packages
"""
all_funcs = set(self.all_functions())
shared_funcs = set(self.shared_functions())
return list(all_funcs.difference(shared_funcs))
def shared_methods_by_class(self) -> Dict[str, List[str]]:
"""
List of public methods in each shared
class across all packages
"""
out = {}
shared_classes = self.shared_classes()
for class_name in shared_classes:
methods = set(self.pkgs[0].public_methods(class_name))
for pkg in self.pkgs[1:]:
methods = methods.intersection(pkg.public_methods(class_name))
out[class_name] = list(methods)
return out
|
bd55d538be2a352b5cdd11c9736711abafadf681 | Runsheng/rosalind | /REVC.py | 776 | 3.65625 | 4 | #!/usr/bin/env python
'''
Rosalind #: 003
Rosalind ID: REVC
Problem Title: Complementing a Strand of DNA
URL: http://rosalind.info/problems/revc/
'''
def reverse_complement(seq):
"""
Given: A DNA string s of length at most 1000 bp.
Return: The reverse complement sc of s.
due to the complement_map,
the symbol such as \n and something else is illegal
the input need to be pure sequence
"""
complement_map = dict(zip("acgtACGTNn-","tgcaTGCANn-"))
complement=[]
for s in seq:
complement.append(complement_map[s])
reverse=''.join(reversed(complement))
return reverse
if __name__ == '__main__':
with open("./data/rosalind_revc.txt") as input_data:
seq=input_data.read().strip()
print reverse_complement(seq) |
8e0e070279b4e917758152ea6f833a26bc56bad7 | chirag16/DeepLearningLibrary | /Activations.py | 1,541 | 4.21875 | 4 | from abc import ABC, abstractmethod
import numpy as np
"""
class: Activation
This is the base class for all activation functions.
It has 2 methods -
compute_output - this is used during forward propagation. Calculates A given Z
copute_grad - this is used during back propagation. Calculates dZ given dA and A
"""
class Activation(ABC):
@abstractmethod
def compute_output(self, Z):
pass
@abstractmethod
def compute_grad(self, A, dA):
pass
"""
class: Sigmoid
This activation is used in the last layer for networks performing binary classification.
"""
class Sigmoid(Activation):
def __init__(self):
pass
def compute_output(self, Z):
return 1. / (1 + np.exp(-Z))
def compute_grad(self, Y, A, dA):
return dA * A * (1 - A)
"""
class: Softmax
This activation is used in the last layer for networks performing multi-class classification.
"""
class Softmax(Activation):
def __init__(self):
pass
def compute_output(self, Z):
return np.exp(Z) / np.sum(np.exp(Z), axis=0)
def compute_grad(self, Y, A, dA):
return A - Y
"""
class ReLU
This activation is used in hidden layers.
"""
class ReLU(Activation):
def __init__(self):
pass
def compute_output(self, Z):
A = Z
A[Z < 0] = 0
return A
def compute_grad(self, Y, A, dA):
dZ = dA
dZ[A == 0] = 0
return dZ
|
01e8da8327f10fc0e14c8af7832e01bf3e98b429 | Warrlor/Lab3-SP | /1.py | 143 | 3.6875 | 4 | import math
n = int (input('введите n'))
i = 1
p = 1
for i in range (1,n+1):
p = p*i
z = math.pow(2,i)
print (p)
print (z)
|
79516107093e5e469e9c6e55b7ec0b630897133a | BradSegel/stuff | /assignments-master/merge_inverge.py | 1,943 | 4 | 4 |
def merge_sort(unsorted_list):
l = len(unsorted_list)
inversion_count = 0
# here's our base case
if l <= 2:
# make sure our pair is ordered
if l==2 and unsorted_list[0] > unsorted_list[1]:
holder = unsorted_list[0]
unsorted_list[0] = unsorted_list[1]
unsorted_list[1] = holder
inversion_count = 1
return (unsorted_list, inversion_count)
# RECURSE!!
split_idx = l/2
a,a_inversion_count = merge_sort(unsorted_list[:split_idx])
b,b_inversion_count = merge_sort(unsorted_list[split_idx:])
inversion_count = a_inversion_count + b_inversion_count
while b: # we're putting b into a, so we don't want to stop while there's b
for idx, a_val in enumerate(a):
if b:
# when we get to a value in 'a' bigger than b[0]
if a_val > b[0]:
inversion_count = inversion_count + len(a[idx:])
a[idx:idx] = [b.pop(0)]
# b now contains larger values than a
if len(a) == idx + 1:
a.extend(b)
b = None # we want out of this while loop
return (a, inversion_count)
def get_inversion_count(unsorted_list):
i = 0
for idx, elem in enumerate(unsorted_list,1):
for x in unsorted_list[idx:]:
if elem > x: i = i + 1
return i
if __name__ == '__main__':
# import random
# sorter = [int(1000 * random.random()) for i in xrange(1000)]
# print 'before: {}'.format((sorter, get_inversion_count(sorter)))
# print 'result: {}'.format(merge_sort(sorter))
nums = []
with open('IntegerArray.txt', 'r') as f:
nums = [int(x) for x in f.read().split("\r\n") if x ]
print "brute: {}".format(get_inversion_count(nums))
print "merge: {}".format(merge_sort(nums)[1])
# print get_inversion_count(nums)
# print merge_sort(nums)[1]
|
f97b32658a54680d8cbfe95abbfd5612e6d22e4e | ssj9685/lecture_test | /assignment/week3.py | 290 | 4.15625 | 4 | num1=int(input("first num: "))
num2=int(input("second num: "))
print("num1 + num2 = ", num1 + num2)
print("num1 + num2 = ", num1 - num2)
print("num1 + num2 = ", num1 * num2)
print("num1 + num2 = ", num1 / num2)
print("num1 + num2 = ", num1 // num2)
print("num1 + num2 = ", num1 % num2) |
bad0deeb8b06195df2613e16e9ebb96b8f1aa802 | shj2013/python | /while.py | 95 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
n=1
while n<=100:
print(n)
n=n+1
print('end')
|
705dbffc6bf57626c64609337ceb701ed849e66d | ptracton/MachineLearning | /my_notes/python/test_cost_function.py | 260 | 3.65625 | 4 | #! /usr/bin/env python3
import numpy as np
import cost_function
Y_GOLDEN = [0.9, 1.6, 2.4, 2.3, 3.1, 3.6, 3.7, 4.5, 5.1, 5.3]
X = np.arange(0, 10, 1)
my_cost = cost_function.cost_function(X, Y_GOLDEN, (1, 0.5))
print("FOUND: Cost = {:02f} ".format(my_cost))
|
5915dcaf57ad92e9a1f3ad46d00ff7fb4cd54caa | 0ashu0/Python-Tutorial | /Lynda Course/1003_raise Exceptions.py | 613 | 3.9375 | 4 | #def main():
#num = 1
#print("main begins")
#for line in readfile('lines.txt'):
#print('printing {} line'.format(num))
#print(line.strip())
#num = num + 1
#
#
#def readfile(filename):
#fh = open(filename)
#return fh.readlines()
#
#main()
def main():
try:
for line in readfile('lines.txt'):
print(line.strip())
except IOError as e:
print('can not read the file: ', e)
except ValueError as e:
print('wrong filename: ', e)
def readfile(filename):
if filename.endswith('.txt'):
fh = open(filename)
return fh.readlines()
else:
raise ValueError('Filename must end with .txt')
main() |
7fd3e2d847f607001cd5a32f09594d17a5ddde35 | hiEntropy/hex | /hex.py | 424 | 3.609375 | 4 | import sys
'''
'''
def convert(value):
if len(value)==1:
return '%'+hex(ord(value[0]))[2:]
else:
return '%'+hex(ord(value[0]))[2:]+convert(value[1:])
def getArgs(value):
if len(value)==1:
return value[0]
else:
return value[0]+getArgs(value[1:])
def main():
if len(sys.argv[1:])>0:
input_string=getArgs(sys.argv[1:])
print(convert(input_string))
main()
|
e045f34684fc8e3efe153ae84d80e3f4d922dd7f | humanoiA/Python-Practice-Sessions | /day2/ass9.py | 336 | 3.71875 | 4 | a=int(input("Enter Hardness: "))
b=int(input("Enter Carbon Content: "))
c=int(input("Enter Tensile Strength: "))
if a>50 and b<0.7:
print("Grade is 9")
elif c>5600 and b<0.7:
print("Grade is 8")
elif a>50 and c>5600:
print("Grade is 7")
elif a>50 or b<0.7 or c>5600:
print("Grade is 6")
else:
print("Grade is 5") |
27a0944fee14ee315bd5489bcdd980448a65f757 | humanoiA/Python-Practice-Sessions | /day3/ass4.py | 142 | 3.65625 | 4 | str= input("Enter String : ")
ch= input("Enter Char: ")
s1=str[:str.index(ch)+1]
s2=str[str.index(ch)+1:].replace(ch,"$")
str=s1+s2
print(str) |
88fb7e1c3ea8b3eda8a2365688cbd09674bbb6da | humanoiA/Python-Practice-Sessions | /day2/test.py | 218 | 3.828125 | 4 | for i,p in zip(range(5),range(4,0,-1)):
for j in range(i):
print(" ",end=" ")
for k in range(i,3):
print("*",end=" ")
for l in range(p):
print("*",end=" ")
print("") |
8cde9dc4f1f709d9ba50cd1818fa88e06259034a | humanoiA/Python-Practice-Sessions | /day3/ass7.py | 111 | 3.640625 | 4 | str=input("Enter String: ")
if len(str)%4==0:
print(str[-1:-len(str)-1:-1])
else:
print("Length issue") |
8fbd95b0aa93df35f082fbdeba058595acc1a497 | humanoiA/Python-Practice-Sessions | /day1/ass4.py | 85 | 3.625 | 4 | b=int(input("Enter Base: "))
h=int(input("Enter height: "))
print("Area is",0.5*b*h)
|
7ac520284b42d4e0d94a76372028c9c3f781c07f | A01375137/Tarea-02 | /porcentajes.py | 483 | 4 | 4 | #encoding: UTF-8
# Autor: Mónica Monserrat Palacios Rodríguez, A01375137
# Descripcion: Calcular el porcentaje de mujeres y hombres inscritos, calcular la cantidad total de inscritos.
# A partir de aquí escribe tu programa
m_i=int(input("Mujeres inscritas: "))
h_i=int(input("Hombres inscritos: "))
total=(m_i+h_i)
print("Total de inscritos:", total)
porc_m=(m_i*100)/total
print("Porcentaje de mujeres:", porc_m, "%")
porc_h=(h_i*100)/total
print("Porcentaje de hombres:", porc_h, "%")
|
a58875f38dab10aabdd477b5578fda70e9b72187 | alexl0/GIISOF01-2-009-Numerical-Computation | /Lab02/Lab02_Exercise1.py | 653 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Horner for a point
"""
#---------------------- Import modules
import numpy as np
#---------------------- Function
def horner(p,x0):
q = np.zeros_like(p)
q[0] = p[0]
for i in range(1,len(p)):
q[i] = q[i-1]*x0 + p[i]
return q
#----------------------- Data
p = np.array([1, -1, 2, -3, 5, -2])
r = np.array([ 5, -3, 1, -1, -4, 0, 0, 3])
x0 = 1.
x1 = -1.
#------------ Call the function (1)
q = horner(p,x0)
print('Q coefficients = ', q[:-1])
print('P(1) = ', q[-1])
print('\n')
#------------ Call the function (2)
q1 = horner(r,x1)
print('Q1 coefficients = ', q1[:-1])
print('R(-1) = ', q1[-1])
|
1670757f322720abc36337fc9fd70043ed0b532c | alexl0/GIISOF01-2-009-Numerical-Computation | /Lab07/Lab07_Exercise3.py | 1,085 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
second derivative
"""
#---------------------- Import modules
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import norm
#---------------------- Function
def derivative2(f,a,b,h):
x = np.arange(h,b,h)
d2f = np.zeros_like(x)
k = 0
for x0 in x:
d2f[k] = (f(x0+h) - 2* f(x0) + f(x0-h)) / h**2
k += 1
return x, d2f
#---------------------- Plot
def plotDer2(f,d2f_e,a,b,h):
# derivatives
x, d2f_a = derivative2(f,a,b,h)
#plot
plt.plot(x,d2f_e(x),'y',linewidth=6,label='exact')
plt.plot(x,d2f_a,'b--',label='approximate')
plt.legend()
plt.title(r'Second derivative of $\sin(2 \pi x)$')
plt.show()
# Print error
E = norm(d2f_e(x)-d2f_a)/norm(d2f_e(x))
print('%15s %15s\n' % ('h','E(df_f)'))
print('%15.3f %15.6e\n' % (h,E))
#----------------------- Data
f = lambda x: np.sin(2*np.pi*x)
d2f_e = lambda x: -(2*np.pi)**2 * np.sin(2*np.pi*x)
a = 0.
b = 1.
h = 0.01
#------------ Call the function
plotDer2(f,d2f_e,a,b,h)
#%% |
c87fb20dd1a8a233bcc4178dcd5003ef42821bbe | mikejry/simple-rsa | /primes.py | 1,166 | 4 | 4 | import math
class Prime:
def __init__(self, number):
try:
if self.is_prime(number) is False:
self.primeNumber = 2
else:
self.primeNumber = int(number)
except ValueError:
print("Invalid number")
self.primeNumber = 2
def __mul__(self, other):
multiply = self.primeNumber*other.primeNumber
return multiply
def __sub__(self, other):
substitute = self.primeNumber-other
return substitute
def enter_prime(self):
pierwsza = input("Podaj liczbę pierwszą:")
try:
pierwsza = int(pierwsza)
except ValueError:
print("Invalid number")
return pierwsza
def is_prime(self,num):
num = int(num)
if (num < 2):
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def enter_authenticated(self, num):
while self.is_prime(num) == False:
num = self.enter_prime()
return num
|
325b2b1a929506115bfc63e825c551f1eb21bf3a | carnei-ro/request-logger | /server.py | 3,047 | 3.515625 | 4 | #!/usr/bin/env python3
"""
Very simple HTTP server in python for logging requests
Usage::
./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import json
import os
class S(BaseHTTPRequestHandler):
def _set_response(self, length):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.send_header('Content-Length', length)
self.end_headers()
def _process_request(self):
data = ''
if self.headers['Content-Length']:
content_length = int(self.headers['Content-Length'])
data = self.rfile.read(content_length)
data = data.decode('utf-8')
r = {}
r['method']=str(self.command)
r['path']=str(self.path)
r['headers']=dict(self.headers)
r['body']=data
logging.info("\n> Method: %s\n> Version: %s\n> Path: %s\n> Headers:\n%s> Body:\n%s\n",
str(self.command), str(self.request_version), str(self.path), str(self.headers), data)
return r
def do_GET(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_HEAD(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_POST(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_PUT(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_DELETE(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_CONNECT(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_OPTIONS(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_TRACE(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def do_PATCH(self):
r = json.dumps(self._process_request(), indent=2).encode('utf-8')
self._set_response(len(r))
self.wfile.write(r)
def run(server_class=HTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
|
2fedfa213660d5bca39d1598b8de77fd343082f3 | tangym27/mks66-matrix | /main.py | 7,944 | 4.03125 | 4 | from display import *
from draw import *
from matrix import *
from random import randint
import math
screen = new_screen()
matrix = new_matrix(4,10)
m1 = [[1, 2, 3, 1], [4, 5, 6, 1]]
m2 = [[2, 4], [4, 6], [6, 8]]
A = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
B = [[11,12,13,14],[15,16,17,18],[19,20,21,22],[23,24,25,26]]
print("Printing matrix:")
print("=======================================")
print("Matrix A:")
print_matrix(A)
print("Matrix B:")
print_matrix(B)
print("Printing matrix after multiplication (A x B):")
print("=======================================")
matrix_mult(A,B)
print("Matrix A:")
print_matrix(A)
print("Matrix B:")
print_matrix(B)
print("Printing matrix after multiplication (B x A):")
print("=======================================")
matrix_mult(B,A)
print("Matrix A:")
print_matrix(A)
print("Matrix B:")
print_matrix(B)
print("Printing matrix after ident:")
print("=======================================")
IDENT = ident(new_matrix())
matrix_mult(IDENT, A)
print("Ident:")
print_matrix(IDENT)
print("Matrix A:")
print_matrix(A)
#####################################################################################################################
#just doing this because i didnt want to code too many things haha
#black bars in the top and bottom (game is more rectangle than square)
black = [0,0,0]
color = black
heading = new_matrix()
footer = new_matrix()
i = 0
while ( i < 101 ):
add_point(footer, 0, 500-i)
add_point(footer, 500, 500-i)
add_point(heading, 0, 100-i)
add_point(heading, 500, 100-i)
i += 1
draw_lines(heading, screen, color)
draw_lines(footer, screen, color)
#######################################
#makes the ground
block = new_matrix()
i = 0
while (i < 30):
add_point(block, 0, 120-i)
add_point(block, 500, 120-i)
i += 1
draw_lines(block, screen, [ 230, 100, 25 ])
#######################################
#makes the lines in the ground
lines = new_matrix()
j = 0
i = 1
while (j < 500 ):
if (i%2):
add_edge(lines, j, 0, 0, j , 120, 0)
add_edge(lines, j, 107, 0, j+10, 107, 0)
add_edge(lines, j+10, 0, 0, j+10, 120, 0)
j += 10
else:
add_edge(lines, j, 0, 0, j, 120, 0)
add_edge(lines, j+25, 0, 0, j+25, 120, 0)
j += 25
i +=1
draw_lines(lines, screen, black)
#######################################
#such bad code, sets up all of the elements, edges are the outline of each element (right and left side)
i = 0
angle = 2 * math.pi / 360
center= 145
grass = new_matrix()
edge = new_matrix()
edge2 = new_matrix()
grass2 = new_matrix()
edge3 = new_matrix()
edge4 = new_matrix()
grass3 = new_matrix()
edge0 = new_matrix()
edge1 = new_matrix()
cloud = new_matrix()
edge5 = new_matrix()
edge6 = new_matrix()
cloud2 = new_matrix()
edge7 = new_matrix()
edge8 = new_matrix()
circle = new_matrix()
edge9 = new_matrix()
while (i < 20):
#grasses of randomized length
r = randint(20,40 -i) -i
r1 = randint(20,40 -i) -i
add_edge(grass, 300-r, 120+i, 0, 300+r, 120+i, 0)
add_point(edge, 300-r-1,120+i)
add_point(edge2, 300+r+1,120+i)
add_edge(grass2, 60-r1, 120+i, 0, 60+r1, 120+i, 0)
add_point(edge3, 60-r1-1,120+i)
add_point(edge4, 60+r1+1,120+i)
#green hill (top curve and ..lump)
for n in range(180):
angle = (n * 2 * math.pi )/ 360
dx = int(i * math.cos(angle))
dy = int(i * math.sin(angle))
if (i == 19):
add_edge(edge9, center+dx, center + dy, 0, center + dx+1, center +dy+1, 0)
else:
add_edge(circle, center+dx, center + dy, 0, center + dx+1, center +dy+1, 0)
if (i < 15):
add_edge(grass3, 112+i, 119+i+i, 0, 179-i, 119+i+i, 0)
add_edge(grass3, 112+i, 120+i+i, 0, 179-i, 120+i+i, 0)
add_point(edge0, 112+i, 119+i+i)
add_point(edge1, 179-i, 119+i+i)
add_point(edge0, 112+i, 120+i+i)
add_point(edge1, 179-i, 120+i+i)
#clouds which i was told are just the bushes?!
cloud_height = 335+i
add_edge(cloud, 140-r, cloud_height, 0, 140+r, cloud_height, 0)
add_point(edge5, 140-r-1,cloud_height)
add_point(edge6, 140+r+1,cloud_height)
cloud_height2 = 310+i
add_edge(cloud2, 360-r1, cloud_height2, 0, 360+r1, cloud_height2, 0)
add_edge(cloud2, 390-r1, cloud_height2, 0, 390+r1, cloud_height2, 0)
add_edge(cloud2, 420-r1, cloud_height2, 0, 420+r1, cloud_height2, 0)
add_point(edge7, 360-r1-1,cloud_height2)
add_point(edge8, 420+r1+1,cloud_height2)
i+=1
#semi-circle of the green hill
draw_lines( circle, screen, [5,161,4] )
draw_lines( edge9, screen, black )
#bush1
draw_lines(grass, screen, [189,254,24])
draw_lines(edge, screen, black)
draw_lines(edge2, screen, black)
#bush2
draw_lines(grass2, screen, [189,254,24])
draw_lines(edge3, screen, black)
draw_lines(edge4, screen, black)
#green hill
draw_lines(grass3, screen, [5,161,4])
draw_lines(edge0, screen, black)
draw_lines(edge1, screen, black)
#cloud1
draw_lines(cloud, screen, [251,253,252])
draw_lines(edge5, screen, black)
add_edge(edge6, 120 , 335, 0, 160, 335, 0)
draw_lines(edge6, screen, black)
#cloud2
draw_lines(cloud2, screen, [251,253,252])
draw_lines(edge7, screen, black)
add_edge(edge8, 340 , 310, 0, 440, 310, 0)
draw_lines(edge8, screen, black)
#######################################
# makes that really long four block road
b = new_matrix()
b1 = new_matrix()
b2 = new_matrix()
i = 0
count = 0
for j in range(6):
i = 0
while (i <20):
height = 190+i
add_edge(b, 180, height, 0, 200 + count, height, 0)
if ((i%5)== 0):
r = randint(4,16)
add_edge(b1, 180, height, 0 , 200+count, height, 0)
add_edge(b2, 180+count+r, height, 0, 180+count+r, height+5, 0)
i += 1
add_edge(b2, 200+count, 190, 0, 200+count, 210, 0)
count += 20
add_edge(b2, 180, height+1, 0 , 300, height+1, 0)
add_edge(b1, 180, 190, 0, 180, height, 0)
draw_lines(b, screen, [179,91,49])
draw_lines(b1, screen, black)
draw_lines(b2, screen, black)
#######################################
#makes the pipe!
pipe = new_matrix()
edge = new_matrix()
edge2 = new_matrix()
add_edge(edge, 455, 154, 0, 415 , 154, 0)
add_edge(edge, 455, 155, 0, 415 , 155, 0)
add_edge(edge, 455, 170, 0, 415 , 170, 0)
add_edge(edge, 455, 171, 0, 415 , 171, 0)
i = 0
while (i < 50):
startx = 450
endx = 420
y = 120+ i
if (i <= 33):
add_edge(pipe, startx, y, 0, endx, y, 0)
add_point(edge, startx, y)
add_point(edge2, endx,y)
add_point(edge, startx+1, y)
add_point(edge2, endx-1,y)
else:
add_edge(pipe, startx+5, y, 0, endx-5, y, 0)
add_point(edge, startx+5, y)
add_point(edge, startx+6, y)
add_point(edge2, endx-6,y)
add_point(edge2, endx-5,y)
i += 1
draw_lines(pipe, screen, [122,206,14])
draw_lines(edge, screen, black)
draw_lines(edge2, screen, black)
#######################################
#makes the first block
b = new_matrix()
b1 = new_matrix()
b2 = new_matrix()
i = 0
while (i <20):
height = 190+i
add_edge(b, 100, height, 0, 120 , height, 0)
if ((i%5)== 0):
r = randint(3,17)
i += 1
add_edge(b1, 100, 190, 0, 100, 210, 0)
add_edge(b1, 100, 210, 0, 120, 210, 0)
add_edge(b1, 100, 190, 0, 120, 190, 0)
add_edge(b1, 120, 190, 0 , 120, 210, 0)
draw_lines(b, screen, [204,78,12])
draw_lines(b1, screen, black)
#######################################
#makes the highest block
b = new_matrix()
b1 = new_matrix()
b2 = new_matrix()
i = 0
while (i <20):
height = 260+i
add_edge(b, 230, height, 0, 250 , height, 0)
i += 1
add_edge(b1, 230, 260, 0, 230, height, 0)
add_edge(b1, 250, 260, 0, 250, height, 0)
add_edge(b1, 230, 260, 0, 250, 260, 0)
add_edge(b1, 230, height, 0 , 250, height, 0)
draw_lines(b, screen, [204,78,12])
draw_lines(b1, screen, black)
#######################################
display(screen)
save_extension(screen, 'img.png')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.