#Saint Francis High School


Linear Regression

A linear regression program which shows the slope of the line and y-intercept

import numpy as np import matplotlib.pyplot as plt def estimate_coef(x, y): n = np.size(x) m_x, m_y = np.mean(x), np.mean(y) SS_xy = np.sum(y*x) - n*m_y*m_x SS_xx = np.sum(x*x) - n*m_x*m_x b_1 = SS_xy / SS_xx b_0 = m_y - b_1*m_x return(b_0, b_1) def plot_regression_line(x, y, b): plt.scatter(x, y, color = "m", marker = "o", s = 30) y_pred = b[0] + b[1]*x plt.plot(x, y_pred, color = "g") plt.xlabel('x') plt.ylabel('y') plt.show() def main(): x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12]) b = estimate_coef(x, y) print("Estimated coefficients:\nb_0 = {} \" \nb_1 = {}".format(b[0], b[1]")) plot_regression_line(x, y, b) if __name__ == "__main__": main()

k nearest neighbor


from statistics import mode from math import sqrt import operator data = [(1,1,"red"),(2,4,"red"),(6,3,"red"),(7,4,"blue"),(4,2,"blue"),(3,4,"green")] x = int(input("What is the x value?")) y = int(input("What is the y value?")) k = int(input("How many closest points would you like?")) point = (x,y) print(point) def distance(x2,y2): dist = ((x2[0]-x)**2)+((y2[1]-y)**2) return sqrt(dist) if k>len(data): print("Enter a different number of points") Dictionary = {} for i in range(0,len(data)): var = distance(data[i],data[i]) print(var) Dictionary[data[i]]=var sorted_Dictionary = sorted(Dictionary.items(), key=operator.itemgetter(1)) print(sorted_Dictionary) for i in range(0,k): var1 = (sorted_Dictionary[0][0][2]) print(var1)

Car Class

Lets you create cars and store them in a Garage. You can drive cars, you can repair them, refuel them and change their tires. You can also specify whether the car is electric or not.

import random import math class Car: def __init__(self, name, capacity, mpg, cost): #the name of the car self.name = name #the car's odometer self.miles = 0.0 #the car's current fuel self.fuel = float(capacity) #the car's maximum fuel self.capacity = float(capacity) #the car's fuel efficiency self.mpg = float(mpg) #the car's tire health self.tiretreads = 5000.0 #the car's body damage self.damage = 0 #total costs spent on the car self.cost = float(cost) #def repair, def drive,def refuel,def tire rotation,def info def drive(self,distance): if (self.fuel*self.mpg < distance) and self.capacity != math.inf: print(" you need to refuel ") elif self.tiretreads < distance: print(" you have to change tires") elif self.damage > 50: print(" your car is to damaged to drive") else: crashchance = distance/1000 if round(random.uniform(0,100),2) <= crashchance: newdistance = random.randint(1,distance) print("your car crashed but it drove " + str(newdistance) + " miles") self.damage+=random.randint(1,100) print("your car got in an accident and aquired some damage " + str(self.damage)) self.miles+=newdistance self.tiretreads-=newdistance print("you drove " + str(newdistance) + " miles") if self.capacity != math.inf: self.fuel-=newdistance/self.mpg print("you now have " + str(self.fuel) + " gallons of fuel") else: self.miles+=distance self.tiretreads-=distance print("=====================") print("you drove " + str(distance) + " miles") if self.capacity != math.inf: self.fuel-=distance/self.mpg print("you now have " + str(self.fuel) + " gallons of fuel") print("=====================") def refuel(self): if self.capacity == math.inf: print ("cannot refuel electric car") return print("your refuel cost $" + str((self.capacity - self.fuel)* 4.20)) self.cost += (self.capacity - self.fuel)* 4.20 self.fuel = self.capacity def tirerotation(self): self.tiretreads = 5000.0 self.cost += 420 print("your tire rotation cost $420") def repair(self): self.cost += self.damage * (42) self.damage = 0 print("your repair cost $" + str(self.damage * 42)) def printinfo(self): print("====================================================") if self.capacity != math.inf: print("Name:" + str(self.name)) else: print("Name:" + str(self.name) + "(electric vehicle)") print("Odometer:" + str(self.miles)) if self.capacity != math.inf: print("Fuel: " + str(self.fuel) + '/' + str(self.capacity)) print("Fuel Effiency:" + str(self.mpg)) print("Miles remaning before maintenance:" + str(self.tiretreads)) print("Body damage:" + str(self.damage) + '%') print("Total money spent:$" + str((self.capacity - self.fuel)* 4.20)) print("====================================================") class Garage: def __init__(self): self.carobject = [] def mainloop(self): answer = "" while answer != "Q": print("===========================") print("1. Create Car") print("2. View Cars") print("3. Car Action") print("4. Print Financial Report") print("5. Save Garage") print("6. Load Garage") print("Q. Exit program") print("===========================") answer = (input("Enter your selection")) if answer == "1": self.CreateCar() elif answer == "2": self.Displaycar() elif answer == "3": self.caraction() elif answer == "4": self.financialreport() elif answer == "5": self.save() elif answer == "6": self.open() def financialreport(self): totalcost = 0 for i in self.carobject: totalcost+=i.cost print("your total spending was $" + str(totalcost)) def CreateCar(self): name = input("what is the name of your car?") capacity = input("how many gallons of gas can your car store?(E for electric car)") if capacity == "E": capacity = math.inf mpg = math.inf else: capacity =float(capacity) mpg = float(input("what is the fuel effiency of your car?")) cost = float(input("How much does your car cost?")) car = Car(name,capacity,mpg,cost) self.carobject.append(car) print("Successfully created a car") def Displaycar(self): count = 1 for i in self.carobject: print("Car " + str(count) + ": " + i.name) count+=1 def caraction(self): self.Displaycar() selection = int(input("enter the number of the car you want to view?")) self.carobject[selection-1].printinfo print("1. Refuel Car") print("2. Repair Car") print("3. Change your tires") print("4. Display information about the care") print("5. Drive the car") print("6. Would you like to go back?") answer = int(input("Enter your selection?")) if answer == 1: self.carobject[selection-1].refuel() elif answer == 2: self.carobject[selection-1].repair() elif answer == 3: self.carobject[selection-1].tirerotation() elif answer == 4: self.carobject[selection-1].printinfo() elif answer == 5: distance = int(input("How many miles would you like to drive?")) self.carobject[selection-1].drive(distance) elif answer == 6: self.Displaycar() else: print("Invalid Input") def save(self): file = open("garage.dat","w") for i in self.carobject: file.write(i.name + '\n') file.write(str(i.capacity) + '\n') file.write(str(i.mpg) + '\n') file.write(str(i.cost) + '\n') file.write(str(i.fuel) + '\n') file.write(str(i.tiretreads) + '\n') file.write(str(i.damage) + '\n') file.write(str(i.miles) + '\n') file.close() print("Succesfuly saved in garage.dat") def open(self): if len(self.carobject) != 0: print("using load will overwrite current garage") answer = input("would you like to continue(y/n)") if answer == "n": return self.carobject = [] file = open("garage.dat","r") lines = 0 for line in file: lines+=1 file.close() if lines%8 != 0: print("file is corrupted") return file = open("garage.dat","r") for i in range(int(lines/8)): car1 = Car(str(file.readline().rstrip()),float(file.readline().rstrip()),float(file.readline().rstrip()),float(file.readline().rstrip())) car1.fuel = float(file.readline().rstrip()) car1.tiretreads = file.readline().rstrip() car1.damage = file.readline().rstrip() car1.miles = file.readline().rstrip() self.carobject.append(car1) print(" Succesfully loaded " + str(len(self.carobject)) + " cars") file.close()

drive function in car class

The user creates their own car and the drive function drives the car and displays statistics on how the drive went


import random class Car: def __init__(self, name, capacity, mpg, cost): #the name of the car self.name = name #the car's odometer self.miles = 0.0 #the car's current fuel self.fuel = float(capacity) #the car's maximum fuel self.capacity = float(capacity) #the car's fuel efficiency self.mpg = float(mpg) #the car's tire health self.tiretreads = 5000.0 #the car's body damage self.damage = 0 #total costs spent on the car self.costs = float(cost) #def repair, def drive,def refuel,def tire rotation,def info def drive(self,distance): if self.fuel*self.mpg < distance: print(" you need to refuel ") elif self.tiretreads < distance: print(" you have to change tires") elif self.damage > 50: print(" your car is to damaged to drive") else: crashchance = distance/1000 if round(random.uniform(0,100),2) <= crashchance: newdistance = random.randint(1,distance) print("your car crashed but it drove " + str(newdistance) + " miles") self.damage+=random.randint(1,100) print("your car was damaged " + str(self.damage)) self.miles+=newdistance self.tiretreads-=newdistance self.fuel-=newdistance/self.mpg print("you drove " + str(newdistance) + " miles") print("you now have " + str(self.fuel) + " gallons of fuel") else: self.miles+=distance self.tiretreads-=distance self.fuel-=distance/self.mpg print("=====================") print("you drove " + str(distance) + " miles") print("you now have " + str(self.fuel) + " gallons of fuel") print("=====================") for i in range(200): car1= Car("Tesla",50,25,50000) car1.drive(600)

PC class

lets the user enter in specific pc parts and their price then calculates the total price of the pc and lets the user see the individual parts.


class PC: def __init__(self, name, CPU, CPUprice, GPU, GPUprice, RAM, RAMprice, case, casePrice, cooler, coolerPrice, motherboard, motherboardPrice, storage, storagePrice, monitor, monitorPrice, PSU, PSUprice): self.name = name self.CPU = [CPU, CPUprice] self.GPU = [GPU, GPUprice] self.RAM = [RAM, RAMprice] self.case = [case, casePrice] self.cooler = [cooler, coolerPrice] self.motherboard = [motherboard, motherboardPrice] self.storage = [storage, storagePrice] self.monitor = [monitor, monitorPrice] self.PSU = [PSU, PSUprice] def printPartList(self): print(self.CPU[0]) print(self.GPU[0]) print(self.RAM[0]) print(self.case[0]) print(self.cooler[0]) print(self.motherboard[0]) print(self.storage[0]) print(self.monitor[0]) print(self.PSU[0]) def printTotalPrice(self): print( "total price: $" + (str(self.CPU[1] + self.GPU[1] + self.RAM[1]+self.case[1]+self.cooler[1]+self.motherboard[1]+self.storage[1]+self.storage[1]+self.PSU[1]))) def printOnePart(self): print("===============================") print("1. CPU") print("2. GPU") print("3. RAM") print("4. Case") print("5. Cooler") print("6. Motherboard") print("7. Storage") print("8. Monitor") print("9. PSU") print("===============================") answer = "y" while answer == "y": selection = int(input("select the number of which part you would like to see")) if (selection == 1): print("CPU:", self.CPU[0], "costs $" + str(self.CPU[1])) elif (selection == 2): print("GPU:", self.GPU[0], "costs $" + str(self.GPU[1])) elif (selection == 3): print("RAM:", self.RAM[0], "costs $" + str(self.RAM[1])) elif (selection == 4): print("Case:", self.case[0], "costs $" + str(self.case[1])) elif (selection == 5): print("Cooler:", self.cooler[0], "costs $" + str(self.cooler[1])) elif (selection == 6): print("Motherboard:", self.motherboard[0], "costs $" + str(self.motherboard[1])) elif (selection == 7): print("Storage:", self.storage[0], "costs $" + str(self.storage[1])) elif (selection == 8): print("Monitor:", self.monitor[0], "costs $" + str(self.monitor[1])) elif (selection == 9): print("PSU:", self.PSU[0], "costs $" + str(self.PSU[1])) else: print("Invalid input!") answer = input("would you like to see another part (y/n)?") mypc=PC("Alans pc","Intel - Core i9-9900K 3.6 GHz 8-Core Processor", 484,"Asus - GeForce RTX 2080 8 GB ROG Strix Gaming OC Video Card",769 , "G.Skill - Trident Z RGB 16 GB (2 x 8 GB) DDR4-3600 Memory", 114, "NZXT H700I",179, "NZXT kraken X62", 139, "MSI - Z390-A PRO ATX LGA1151 Motherboard",129 , "Samsung - 970 Evo 1 TB M.2-2280 Solid State Drive1", 214,"alienware-aw2518hf-245-1920x1080-240hz-monitor-aw2518hf", 389, "Asus - 850 W 80+ Platinum Certified Fully Modular ATX Power Supply" ,209) mypc.printPartList() mypc.printTotalPrice() mypc.printOnePart()

password generator

Creates x amount of passwords at x length depending on the user inputs


import random def exercise_11(): alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" pw_length = int(input("how long do you want your password to be?")) quantity = int(input("how many passwords do you want to generate?")) for i in range(quantity): mypw = "" for i in range(pw_length): next_index = random.randrange(len(alphabet)) mypw = mypw + alphabet[next_index] print(mypw)

Bank Account Class

A bank account simulation


class Bank_Account: def __init__(self): self.balance=0 print("Hello!!! Welcome to the Bank") def deposit(self,amount): self.balance += amount print("\n Amount Deposited:",amount) def withdraw(self,amount): if self.balance>=amount: self.balance-=amount print("\n You Withdrew:", amount) else: print("\n Insufficient balance ") def display(self): print("\n Net Available Balance=",self.balance) account1 = Bank_Account() account1.deposit(500) account1.withdraw(200) account1.display()

Number Guessing Game

Asks a user to guess a number and gives hints to the user based on how close the users guess is. Displays Users statistics about their games.


from random import randint condition = "yes" numgames = 0 numcount =[] while condition == "yes": num = randint(1,100) count = 0 answer = 0 while answer != num: answer = int(input(" guess a number from 1 to 100?")) count+=1 if answer < num: print( " guess a little higher") elif answer == num: print ("you guessed it") numgames+=1 numcount.append(count) else: print ("guess a little lower") condition = input(" Would you like to play again ?") print(" Here are your results") print("total games:" + str(len(numcount))) avg = 0 for i in numcount: avg+=i avg/=len(numcount) print( "Here is your average:" + str(avg)) least = numcount[0] for i in numcount: if i < least: least = i print("here was your best game:" + str(least))
Akshay Jun 05

This is amazing!

Mad Libs

When provided with a MadLibs file that has specified parts of speech can take in user input to create a MadLib


filename = input("Enter Filename") f = open(filename,'r') wordList = f.read().split() position = 0 for i in wordList: if i[0] == "<": wordList[position] = input("Input " + i) position+=1 for i in wordList: print(i,end = " ") f.close
Akshay Jun 04

This is amazing.

Python Generated House

A house I created using Turtle


from turtle import * screen = Screen() screen.setup(900,900) bgcolor("blue") color("white") shape("turtle") penup() goto(-400,-400) pendown() begin_fill() for i in range(4): forward(300) left(90) penup() goto(-400,-100) pendown() left(60) forward(300) right(120) forward(300) penup() right(30) goto(-250,-400) pendown() right(90) for i in range(4): forward(25) right(90) forward(130) penup() goto(-300,-200) pendown() for i in range(4): forward(50) right(90) penup() goto(-325,-200) pendown() right(90) forward(50) penup() goto(-300,-175) left(90) pendown() forward(50) penup() goto(-150,-300) pendown() begin_fill() for i in range(360): forward(0.1) left(1) end_fill() penup() goto(0,0)
Akshay Jun 05

This is amazing!

1