#California High School


Naive Bayes Algorithm

This is a program demonstrating the Naive Bayes Algorithm. It is used to see if it will be a good day to golf.



import math #set up the predone data outlook = ['sunny','sunny','overcast','rainy','rainy','rainy','overcast','sunny', 'sunny','rainy','sunny','overcast','overcast','rainy'] temperature = ['hot','hot','hot','mild','cool','cool','cool','mild','cool', 'mild','mild','mild','hot','mild'] humidity = ['high','high','high','high','normal','normal','normal','high', 'normal','normal','normal','high','normal','high'] windy = ['false','true','false','false','false','true','true','false','false', 'false','true','true','false','true'] play = ['no','no','yes','yes','yes','no','yes','no','yes','yes','yes','yes', 'yes','no'] print("Hi welcome to the Naive Bayes Algorithm which will help calculate if it will be a good day to golf!") print("This program has some preset data that will be inputted into the algorithm""\n") #need sunny,cool,high humidity,strong wind, and play yes yescount = 0 nocount = 0 #finds the amount of days you can play golf and bad days to play golf out the the amount of days tested def findyes(): no = 0 yes = 0 for x in range(len(play)): if play[x] == 'no': no += 1 else: yes += 1 global yescount yescount += yes global nocount nocount += no print("There were", yes ,"/", len(play),"days you could golf on and","There were", no,"/",len(play),"days you couldn't golf on") findyes() yeshumid = 0 yessunny = 0 yescool = 0 yeswind = 0 ''' This is a function that helps determine the amount of humid, sunny, cool, and windy days out of the days that it was good to gold ''' def yescalculator(): highhumidity = 0 sunny = 0 cool = 0 wind = 0 for x in range(len(play)): if play[x] == 'yes': if outlook[x] == 'sunny': sunny += 1 if temperature[x] == 'cool': cool += 1 if humidity[x] == 'high': highhumidity += 1 if windy[x] == 'true': wind += 1 global yeshumid yeshumid += highhumidity global yessunny yessunny += sunny global yescool yescool += cool global yeswind yeswind += wind nohumid = 0 nosunny = 0 nocool = 0 nowind = 0 ''' This function helps determine the amount of sunny, humid, cool, a windy days bad golf days ''' def nocalculator(): sunny = 0 cool = 0 wind = 0 highhumidity = 0 for x in range(len(play)): if play[x] == 'no': if outlook[x] == 'sunny': sunny += 1 if temperature[x] == 'cool': cool += 1 if humidity[x] == 'high': highhumidity += 1 if windy[x] == 'true': wind += 1 global nohumid nohumid += highhumidity global nosunny nosunny += sunny global nocool nocool += cool global nowind nowind += wind yescalculator() nocalculator() print("\n""Probability we can play the game:") print("Probability of it being a good golf day and sunny is" ,yessunny,"/",yescount) print("Probability of it being a good golf day and cool is" ,yescool,"/",yescount) print("Probability of it being a good golf day and humid is" ,yeshumid,"/",yescount) print("Probability of it being a good golf day and windy is" ,yeswind,"/",yescount,"\n") print("Probability we cannot play a game:") print("Probability of it being a stay home day and sunny is",nosunny,"/",nocount) print("Probability of it being a stay home day and sunny is",nocool,"/",nocount) print("Probability of it being a stay home day and sunny is",nohumid,"/",nocount) print("Probability of it being a stay home day and sunny is",nowind,"/",nocount) #calculate evidence P(x) of the equation which is denominator evidences = 0 def findevidence(): evidence = (((yeshumid + nohumid)/14)*((yessunny + nosunny)/14)*((yeswind+nowind)/14)*((yescool + nocool)/14)) global evidences evidences += evidence findevidence() ''' this function multiplies all the no probabilities and yes probabilities and compares to see if it will be a good day to golf or a good day to stay home and watch a movie ''' def compare(): yesequation = (((yessunny/yescount)*(yeshumid/yescount)*(yeswind/yescount)*(yescool/yescount)*(yescount/len(play)))/evidences) noequation = (((nosunny/nocount)*(nohumid/nocount)*(nowind/nocount)*(nocool/nocount)*(nocount/len(play)))/evidences) print("\n""The probability it will be a good day is", yesequation) print("The probability it will be a bad day is", noequation) if yesequation > noequation: print("\n""There is higher probability it will be a good day for golf.","Let's go play some!") else: print("\n""There is a higher probability it will be a bad day for golf.","Lets go watch a movie!") compare()

Hangman

I made a program for Hangman, where the user is given 5 wrong letters to try to guess the random word.


import random wordbank = ["dinosaur","peanut","pencil","apple","pineapple"] separatedword = [] usedletters = [] #chooses a word from the list randomly random = random.randint(0,4) word = wordbank[random] guesses = 0 amountwrong = 5 wrong = "true" #welcomes user print("Hi welcome to Royce's Hangman Game" "\n" "Rule include: you have 5 wrong guesses", "Good Luck :)") #function to check if the user has already guessed the letter def guesscheck(userguesses): for x in range(len(usedletters)): if userguesses == usedletters[x]: print("oops you have already guessed that letter") global userguess userguess = input("\n" "Guess a letter") #separates the word up into a list by letter def separateword(): for x in range(0,len(word),1): separatedword.append(word[x]) separateword() letterleft = len(separatedword) length = len(separatedword) print("For testing purposes I'm including the random word" , word) print("The random word is", letterleft, "letters long") ''' loop to see if they can guess the word as long as the player hasn't run out of turns or has guessed it the loop will continue ''' while amountwrong != 0 and letterleft != 0: #asks user for a letter userguess = input("\n""Guess a letter") if guesses >= 1: guesscheck(userguess) #iterates through the list and checks to see if the guessed letter is in the #word for x in range(0,length,1): if userguess == separatedword[x]: print("You got the letter right!", "The word had a(n)",userguess) letterleft -= 1 wrong = "false" usedletters.append(userguess) guesses += 1 ''' uses a true or false to determine if the user has guessed wrong if true then it takes away a chance and tells the user ''' if wrong == "true": amountwrong -=1 print("oops that letter isn't in the word try again") #if not then it just continues and prints out the stats else: wrong = "true" print("You can still get" , amountwrong, "wrong" ) print("There are still", letterleft, "letters left to guess") #end of game print("\n" "You took an amount of",guesses,"guesses") if amountwrong == 0: print("Too bad you lost all your chances. Better luck next time!") else: print("Congrats! you guessed the word!", "The word was",word)

K Means Clustering

This program first assigns initial clusters to a set of data. It then takes the mean of each of these clusters and then uses them to make new clusters. If the new cluster is the same as the previous loop's cluster then the program ends.


import math import random same = "false" counter = 1 print("Hi welcome to my K Means Cluster program") #select value of K kvalue = int(input('What value of K?')) #endless loop until clusters are set while same != "true": clusterpoints = [(2,0),(2.3,0),(2.5,0),(2.7,0),(2.9,0),(2.2,0) ,(3.1,0),(3.3,0),(3.4,0),(3.6,0),(3.9,0),(3.2,0) ,(4,0),(4.5,0),(4.1,0),(4.3,0),(4.7,0),(4.5,0)] referencepoints = [] red = [] blue = [] yellow = [] #select 3 points if counter == 1: for x in range(0,kvalue,1): points = random.randint(0,15) if x == 1: red.append(clusterpoints[points]) clusterpoints.remove(clusterpoints[points]) elif x == 2: blue.append(clusterpoints[points]) clusterpoints.remove(clusterpoints[points]) else: yellow.append(clusterpoints[points]) clusterpoints.remove(clusterpoints[points]) #after the first loop it now uses the mean as a point to determine clusters if counter > 1 : red.append((findmean(previousred),0)) blue.append((findmean(previousblue),0)) yellow.append((findmean(previousyellow),0)) reddistances = [] bluedistances = [] yellowdistances = [] #function for calculating the distances def distancecalculator(color, list): for x in range(len(clusterpoints)): first = clusterpoints[x] firstvalue = first[0] secondvalue = first[1] distance = math.sqrt(((firstvalue-color[0][0])**2)+((secondvalue-color[0][1])**2)) list.append(distance) distance = 0 distancecalculator(red, reddistances) distancecalculator(blue, bluedistances) distancecalculator(yellow, yellowdistances) #assign each point to the nearest cluster placeholder1 = 0 placeholder2 = 0 placeholder3 = 0 for x in range(0,len(clusterpoints),1): placeholder1 = reddistances[x] placeholder2 = bluedistances[x] placeholder3 = yellowdistances[x] if placeholder1 < placeholder2 and placeholder1 < placeholder3: red.append(clusterpoints[x]) elif placeholder2 < placeholder3 and placeholder2 < placeholder1: blue.append(clusterpoints[x]) elif placeholder3 < placeholder2 and placeholder3 < placeholder1: yellow.append(clusterpoints[x]) #removes reference point red.pop(0) blue.pop(0) yellow.pop(0) #This is for the breaking of the loop. It checks to see if all three clusters are the same endcounter = 0 if counter > 1: if (sorted(red)==sorted(previousred)): endcounter +=1 if (sorted(red)==sorted(previousred)): endcounter +=1 if (sorted(red)==sorted(previousred)): endcounter +=1 #if all 3 clusters are same as previous loop then end code if endcounter == 3: print("\n""This is the previous clusters","\n""red",previousred,"\n""blue",previousblue,"\n""yellow",previousyellow) print("\n""This is the cluster on the next loop","\n""red",red,"\n""blue",blue,"\n""yellow",yellow) print("\n""Since they are the same, the clusters are set") print("The clusters were set in", counter, "loops") same = "true" #This is a variable that is used to keep the previous clusters previousred = red previousblue = blue previousyellow = yellow #find mean of each cluster and do the process again def findmean(list): adder = 0 for x in range(len(list)): adder += list[x][0] meanvalue = adder/len(list) return meanvalue counter+=1

Implementing Hierarchical Clustering into a dataset

This code implements Hierarchical Clustering into a real dataset of information regarding credit cards. It outputs the centroids of the number of clusters that the user wants the data to be split into.


import pandas as pd import math import random csv = pd.read_csv('Card.csv', header = 0) data = [] for x in range(len(csv)): balance = csv.iloc[x].iloc[1] balanceFrequency = csv.iloc[x].iloc[2] purchases = csv.iloc[x].iloc[3] oneOffPurchases = csv.iloc[x].iloc[4] installmentsPurchases = csv.iloc[x].iloc[5] cashAdvance = csv.iloc[x].iloc[6] accountTuple = (balance, balanceFrequency, purchases, oneOffPurchases, installmentsPurchases, cashAdvance) data.append(accountTuple) k = int(input("How many final clusters do you want(max is 97):")) def distance(x, y): return math.sqrt((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2 + (x[3] - y[3]) ** 2 + (x[4] - y[4]) ** 2 + (x[5] - y[5]) ** 2) def minDistance(clusters): minDist = 10000 for x in data: for y in data: dist = distance(x, y) if dist < minDist and dist != 0: minDist = dist minX = x minY = y minPoints = (minX, minY) return minPoints def findCentroid(minPoints): x = minPoints[0] y = minPoints[1] centroid = [] for d in range(len(x)): centroid.append((x[d] + y[d])/2) return centroid data1 = data while k < len(data): minPoints = minDistance(data) data.append(findCentroid(minPoints)) data.remove(minPoints[0]), data.remove(minPoints[1]) print("Centroids:", data)

Implementing K Means Clustering into a dataset

This code takes a real dataset of information of credit card users and uses K means Clustering to categorize the users into separate clusters. It outputs the lowest variation and the centroids of the clusters


import pandas as pd import math import random csv = pd.read_csv('Card.csv', header = 0) data = [] for x in range(len(csv)): balance = csv.iloc[x].iloc[1] balanceFrequency = csv.iloc[x].iloc[2] purchases = csv.iloc[x].iloc[3] oneOffPurchases = csv.iloc[x].iloc[4] installmentsPurchases = csv.iloc[x].iloc[5] cashAdvance = csv.iloc[x].iloc[6] accountTuple = (balance, balanceFrequency, purchases, oneOffPurchases, installmentsPurchases, cashAdvance) data.append(accountTuple) clstr1 = [] lowestVarClstr1 = [] clstr2 = [] lowestVarClstr2 = [] clstr3 = [] lowestVarClstr3 = [] centroids = [] lowestVarCentroids = [] def orignalCentroids(): for a in range(3): rand = data[random.randrange(len(data))] centroids.append(rand) def findDistance(x, y): return math.sqrt((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2 + (x[3] - y[3]) ** 2 + (x[4] - y[4]) ** 2 + (x[5] - y[5]) ** 2) def sortIntoClstr(): clstr1.clear() clstr2.clear() clstr3.clear() for d in data: coorCentClstr1 = centroids[0] coorCentClstr2 = centroids[1] coorCentClstr3 = centroids[2] distClstr1 = findDistance(coorCentClstr1, d) distClstr2 = findDistance(coorCentClstr2, d) distClstr3 = findDistance(coorCentClstr3, d) if distClstr1 < distClstr2 and distClstr1 < distClstr3: clstr1.append(d) elif distClstr2 < distClstr1 and distClstr2 < distClstr3: clstr2.append(d) elif distClstr3 < distClstr1 and distClstr3 < distClstr2: clstr3.append(d) def newCentroid(cluster): x1 = 0 x2 = 0 x3 = 0 x4 = 0 x5 = 0 x6 = 0 for c in cluster: coor = c x1 += coor[0] x2 += coor[1] x3 += coor[2] x4 += coor[3] x5 += coor[4] x6 += coor[5] x1 /= (len(cluster) + 1) x2 /= (len(cluster) + 1) x3 /= (len(cluster) + 1) x4 /= (len(cluster) + 1) x5 /= (len(cluster) + 1) x6 /= (len(cluster) + 1) return (x1, x2, x3, x4, x5, x6) def findNewCentroids(): centroids.clear() centroids.append(newCentroid(clstr1)) centroids.append(newCentroid(clstr2)) centroids.append(newCentroid(clstr3)) def varCluster(cluster, centroid): var = 0 for c in cluster: var += findDistance(centroid, c) return var def findVariation(): variation = 0 variation += varCluster(clstr1, centroids[0]) variation += varCluster(clstr2, centroids[1]) variation += varCluster(clstr3, centroids[2]) return variation def oneCycle(): for x in range(0, 100, 1): sortIntoClstr() findNewCentroids() return findVariation() orignalCentroids() for c in range(21): variation = oneCycle() lowestVariation = 99999999999999999 if variation < lowestVariation: lowestVariation = variation lowestVarCentroids = centroids print('Lowest Variation: ') print(lowestVariation) print('Centroids: ') print(lowestVarCentroids)

Implementing KNN on a dataset

This code takes a real dataset of types of glass and uses K nearest neighbors to classify what the new type of glass(given by the user) is used for. The user needs to input the following to receive what type of glass they have: RI: refractive index Na: Sodium (unit measurement: weight percent in corresponding oxide, as are attributes 4-10) Mg: Magnesium Al: Aluminum Si: Silicon K: Potassium Ca: Calcium Ba: Barium Fe: Iron


import pandas as pd import math csv = pd.read_csv('glass.csv', header = 0) data = [] for x in range(len(csv)): rl = csv.iloc[x].iloc[0] na = csv.iloc[x].iloc[1] mg = csv.iloc[x].iloc[2] al = csv.iloc[x].iloc[3] si = csv.iloc[x].iloc[4] k = csv.iloc[x].iloc[5] ca = csv.iloc[x].iloc[6] ba = csv.iloc[x].iloc[7] fe = csv.iloc[x].iloc[8] glassType = csv.iloc[x].iloc[9] glassTuple = (rl, na, mg, al, si, k, ca, ba, fe, glassType) data.append(glassTuple) userData = [] userData.append(float(input("Enter Rl value of glass: "))) userData.append(float(input("Enter Na value of glass: "))) userData.append(float(input("Enter Mg value of glass: "))) userData.append(float(input("Enter Al value of glass: "))) userData.append(float(input("Enter Si value of glass: "))) userData.append(float(input("Enter K value of glass: "))) userData.append(float(input("Enter Ca value of glass: "))) userData.append(float(input("Enter Ba value of glass: "))) userData.append(float(input("Enter Fe value of glass: "))) distances = [] for x in data: Rl = x[0] Na = x[1] Mg = x[2] Al = x[3] Si = x[4] K = x[5] Ca = x[6] Ba = x[7] Fe = x[8] distance = ((Rl ** 2) + (Na ** 2) + (Mg ** 2) + (Al ** 2) + (Si ** 2) + (K ** 2) + (Ca ** 2) + (Ba ** 2) + (Fe ** 2)) ** (1. /9) distances.append(distance) k = int(input("Enter number of neighbors you wish to calculate (max is 214): ")) nearestDistances = [] nearestNeighbors = [] while len(nearestDistances) > k: nearestDistance = min(distances) nearestDistances.append(nearestDistance) index = distances.index(nearestDistance) distances.remove[index] nearestNeighbors.append(index) glassTypes = [] for n in nearestNeighbors: point = data[n] glassType = point[9] glassTypes.append(glassType) type1 = 0 type2 = 0 type3 = 0 type4 = 0 type5 = 0 type6 = 0 type7 = 0 for t in glassTypes: if(t == 1): type1 += 1 elif(t == 2): type2 += 1 elif(t == 3): type3 += 1 elif(t == 4): type4 += 1 elif(t == 5): type5 += 1 elif(t == 6): type6 += 1 else: type7 += 1 if type1 < type2: if type2 < type3: if type3 < type4: if type4 < type5: if type5 < type6: if type6 < type7: print("The glass is used for headlamps") else: print("The glass is used for tableware") else: print("The glass is used for containers") else: print("The glass is used for vehicle windows that don't float") else: print("The glass is used for vehicle windows that float") else: print("The glass is used for building windows that don't float") else: print("The glass is used for building windows that float")

KNN Algorithm (K Nearest Number)

This program asks the user for a specific point and an amount of neighbors to check. It then checks these nearest points for a color and the color of the most nearest points is the color of the user's point.


import math import operator #data set data = [(3,6,"blue"), (4,7,"red"),(2,2,"purple"),(1,7,"blue"),(3,6,"red"),(2,0,"blue"),(0,9,"purple"), (0,0,"red"),(7,2,"purple"),(1,5,"red"),(0,7,"red"),(9,1,"red"),(1,1,"purple"),(2,5,"blue"), (4,0,"red"),(0,9,"blue"),(5,2,"blue"),(6,0,"red"),(2,6,"blue"),(3,3,"red"),(3,9,"purple"), (2,5,"purple"),(6,9,"blue"),(2,9,"purple"),(8,0,"red"),(7,8,"red"),(6,9,"blue"),(10,0,"purple"), (5,5,"red")] #asks user for a point and how many points close to the point xvalue = int(input("What's the x value of your point?")) yvalue = int(input("What's the y value of your point?")) kvalue = int(input("How many nearest points should there be?")) #finds all the distances and puts it into a dictionary with point and distance from user point distance = 0 distancedictionary = {} for x in range(0,len(data),1): first = data[x] firstvalue = first[0] secondvalue = first[1] distance = math.sqrt(((firstvalue-xvalue)**2)+((secondvalue-yvalue)**2)) distancedictionary[first] = distance distance = 0 #this sorts the dictionary by value sorted_distances = sorted(distancedictionary.items(), key=operator.itemgetter(1)) krange = [] colors = [] red = 0 blue = 0 purple = 0 #this puts the closest values into a list for x in range(0,kvalue,1): sortedset = sorted_distances[x] color = sortedset[0] krange.append(color[2]) print(krange) #this iterates through the list and determines the amount of colors with counters for x in range(0,len(krange),1): if(krange[x] == "red"): red = red + 1 elif(krange[x] == "blue"): blue = blue + 1 elif(krange[x] == "purple"): purple = purple + 1 print("There are " + str(red) + " red dots" ) print("There are " + str(blue) + " blue dots") print("There are " +str(purple) + " purple dots") if(red > blue and red > purple): print("Your color is red") elif(blue > red and blue > purple): print("Your color is blue") elif(purple > blue and purple > red): print("Your color is purple")

DNA to Amino Acid Converter

This program asks the user for a length of a DNA strand, it then generates the strand and converts it to RNA. After, it splits the RNA into Codons and then converts it into an Amino Acid Chain.


import random print("Welcome to Royce's DNA to Amino Acid Converter") #asks user for length of chain userlength = int(input("How long should the DNA strand be")) #generates DNA strand allamino = ["A" ,"T" , "C" , "G"] DNA = [] RNA = [] for x in range(0,userlength,1): amino = random.randint(0,3) DNA.append(allamino[amino]) print("This is the DNA Strand " + "\n" + str(DNA)) #converts to RNA for x in range(0,len(DNA),1): if DNA[x] == "A": RNA.append("U") elif DNA[x] == "T": RNA.append("A") elif DNA[x] == "C": RNA.append("G") elif DNA[x] == "G": RNA.append("C") print("This is the RNA strand " + "\n" + str(RNA)) #splits RNA into codons codons=[] amountcodons = len(RNA)/3 for x in range(0,int(amountcodons),1): holder = RNA[x] +RNA[x+1] + RNA[x+2] codons.append(holder) holder = 0 print("This is the RNA split into codons " + "\n" + str(codons)) #converts the codons into amino acids allamino = ["Lysine", "Asparagine","Isoleucine","Methionine","Threonine" ,"Arginine" ,"Serine","Stop Codon", "Tyrosine","Leucine","Phenylalanine","Cysteine","Tryptophan","Glutamine","Histidine", "Proline","Arginine","Glutamic Acid","Aspartic Acid","Valine","Alanine","Glycine"] aminoacid = [] for x in range(0,int(amountcodons),1): if codons[x] == "AAA" or codons[x] == "AAG": aminoacid.append(allamino[0]) elif codons[x] == "AAU" or codons[x] == "AAC": aminoacid.append(allamino[1]) elif codons[x] == "AUA" or codons[x] == "AUU" or codons[x] =="AUC": aminoacid.append(allamino[2]) elif codons[x] =="AUG": aminoacid.append(allamino[3]) elif codons[x] =="ACA" or codons[x] =="ACU" or codons[x]=="ACC" or codons[x]=="ACG": aminoacid.append(allamino[4]) elif codons[x] =="AGA" or codons[x] =="AGG": aminoacid.append(allamino[5]) elif codons[x] =="AGU" or codons[x] =="AGC" or codons[x] =="UCA" or codons[x] =="UCU" or codons[x] =="UCC" or codons[x] =="UCG": aminoacid.append(allamino[6]) elif codons[x] =="UAA" or codons[x] =="UAG" or codons[x] =="UGA": aminoacid.append(allamino[7]) elif codons[x] =="UAU" or codons[x] =="UAC": aminoacid.append(allamino[8]) elif codons[x] =="UUA" or codons[x] =="UUG" or codons[x] =="CUA" or codons[x] =="CUU" or codons[x] =="CUC" or codons[x] =="CUG": aminoacid.append(allamino[9]) elif codons[x] =="UUU" or codons[x] =="UUC": aminoacid.append(allamino[10]) elif codons[x] =="UGU" or codons[x] =="UGC": aminoacid.append(allamino[11]) elif codons[x] =="UGG": aminoacid.append(allamino[12]) elif codons[x] =="CAA" or codons[x] =="CAG": aminoacid.append(allamino[13]) elif codons[x] =="CAU" or codons[x] =="CAC": aminoacid.append(allamino[14]) elif codons[x] =="CCA" or codons[x] =="CCU" or codons[x] =="CCC" or codons[x] =="CCG": aminoacid.append(allamino[15]) elif codons[x] =="CGA" or codons[x] =="CGU" or codons[x] =="CGC" or codons[x] =="CGG": aminoacid.append(allamino[16]) elif codons[x] =="GAA" or codons[x] =="GAG": aminoacid.append(allamino[17]) elif codons[x] =="GAU" or codons[x] =="GAC": aminoacid.append(allamino[18]) elif codons[x] =="GUA" or codons[x] =="GUU" or codons[x] =="GUC" or codons[x] =="GUG": aminoacid.append(allamino[19]) elif codons[x] =="GCA" or codons[x] =="GCU" or codons[x] =="GCC" or codons[x] =="GCG": aminoacid.append(allamino[20]) elif codons[x] =="GGA" or codons[x] =="GGU" or codons[x] =="GGC" or codons[x] =="GGG": aminoacid.append(allamino[21]) print("This is the amino acid chain " + "\n" + str(aminoacid))

Converter for Decimal, Binary, Hexadecimal

This program converts decimal, binary, and hexadecimal


#conversion binary to decimal total = 0 power = 0 user = input("Input a binary code for me to convert to a decimal") for x in range(len(user)-1, -1, -1): if(user[x] == "1"): total = total + ((2**power)) power = power + 1 print(total) #conversion decimal to binary list = [] add = 0 decimal = input("Input a decimal for me to convert to binary") list.append(int(decimal) % 2) while int(decimal) > 1: decimal = int(decimal)/2 list.append(int(decimal) % 2) list.reverse() for x in range(0,len(list),1): print(list[x], end = ""), #function for converting the higher than 10 remainders def remaindercheck(remainder): if remainder == 10: remainder = "A" if remainder == 11: remainder = "B" if remainder == 12: remainder = "C" if remainder == 13: remainder = "D" if remainder == 14: remainder = "E" if remainder == 15: remainder = "F" return remainder #conversion decimal to hexadecimal hexalist = [] remainder = 0 hexa = input("\n" "Input a decimal for me to convert to hexadecimal") while int(hexa) > 16: remainder = int(hexa) % 16 hexa = (int(hexa)/16) remainder = remaindercheck(remainder) hexalist.append(remainder) remainder = int(hexa)%16 remainder = remaindercheck(remainder) hexalist.append(remainder) hexalist.reverse() for x in range(0,len(hexalist),1): print(hexalist[x],end ="") #binary to hexadecimal binary = input("\n" "Input a binary code for me to convert to hexadecimal") binarytotal = 0 newpower = 0 for x in range(len(binary)-1, -1, -1): if(binary[x] == "1"): binarytotal = binarytotal + ((2**newpower)) newpower = newpower + 1 converthex = [] while int(binarytotal) > 16: remainder = int(binarytotal) % 16 binarytotal = (int(binarytotal)/16) remainder = remaindercheck(remainder) converthex.append(remainder) remainder = int(binarytotal)%16 remainder = remaindercheck(remainder) converthex.append(remainder) converthex.reverse() for x in range(0,len(converthex),1): print(converthex[x],end ="") #hexadecimal to decimal total = 0 powers = 0 placeholder = 0 hexadecimal = input("\n" "Input a hexadecimal for me to convert to decimal") for x in range(len(hexadecimal)-1,-1,-1): placeholder = hexadecimal[x] if(hexadecimal[x] == "A"): placeholder = 10 if(hexadecimal[x] == "B"): placeholder = 11 if(hexadecimal[x] == "C"): placeholder = 12 if(hexadecimal[x] == "D"): placeholder = 13 if(hexadecimal[x] == "E"): placeholder = 14 if(hexadecimal[x] == "F"): placeholder = 15 total = total + (int(placeholder))*(16**powers) powers = powers + 1 print(total) #hexadecimal to binary totaled = 0 nextpower = 0 holder = 0 hexadecimaltobin = input("Input a hexadecimal for me to convert to binary") for x in range(len(hexadecimaltobin)-1,-1,-1): holder = hexadecimaltobin[x] if(hexadecimaltobin[x] == "A"): holder = 10 if(hexadecimaltobin[x] == "B"): holder = 11 if(hexadecimaltobin[x] == "C"): holder = 12 if(hexadecimaltobin[x] == "D"): holder = 13 if(hexadecimaltobin[x] == "E"): holder = 14 if(hexadecimaltobin[x] == "F"): holder = 15 totaled = totaled + (int(holder))*(16**nextpower) nextpower = nextpower + 1 listed = [] added = 0 listed.append(int(totaled) % 2) while int(totaled) > 1: totaled = int(totaled)/2 listed.append(int(totaled) % 2) listed.reverse() for x in range(0,len(listed),1): print(listed[x], end = "")

Correlation Coefficient

This program calculates the Correlation Coefficient of the two data sets


import math SPY = ["170.66","170.95","170.70","169.73","169.18","169.80","169.31","169.11","169.61","168.74","166.38","165.83"] JPM = ["56.54","56.40","56.10","55.49","55.30","54.83","54.52","54.09","54.29","54.15","53.29","51.83"] Spysquared = 0 JPMsquared = 0 Spyavg = 0 JPMavg = 0 both = 0 #calculate average of SPY for x in range(0,12,1): Spyavg = Spyavg + float(SPY[x]) Spyavg = Spyavg/len(SPY) #calculates average of JPM for x in range(0,12,1): JPMavg = JPMavg + float(JPM[x]) JPMavg = JPMavg/len(JPM) #calculate squared average of SPY for x in range(0,12,1): Spysquared = Spysquared + float(SPY[x])*float(SPY[x]) Spysquared = Spysquared/len(SPY) #calculates squared average of JPM for x in range(0,12,1): JPMsquared = JPMsquared + float(JPM[x])*float(JPM[x]) JPMsquared = JPMsquared/len(JPM) #calculates average of both multiplied for x in range(0,12,1): both = both + float(SPY[x])*float(JPM[x]) both = both/(len(SPY)) #Variance of SPY and JPM VarianceSpy = Spysquared -(Spyavg*Spyavg) print("The Variance of SPY is " + str(VarianceSpy)) VarianceJPM = JPMsquared -(JPMavg*JPMavg) print("The Variance of JPM is " + str(VarianceJPM)) #covariance of both covariance = both - (Spyavg*JPMavg) print("The Covariance is " + str(covariance)) #calculates the Correlation Coefficiant CorrelationCoefficient = covariance/math.sqrt(VarianceSpy*VarianceJPM) print("The Correlation Coefficient is " + str(CorrelationCoefficient))

Naive Bayes

This code uses the Naive Bayes Theorem and a random dataset to decide if the weather given by the user is appropriate to play golf


outlook = ["sunny","sunny","overcast","rainy","rainy","rainy","overcast","sunny","sunny","rainy","sunny","overcast","overcast","rainy"] temp = ["hot","hot","hot","mild","cool","cool","cool","mild","cool","mild","mild","mild","hot","mild"] humidity = ["high","high","high","high","normal","normal","normal","high","normal","normal","normal","high","normal","high"] windy = ["false","true","false","false","false","true","true","false","false","false","true","true","false","true"] play = ["no","no","yes","yes","yes","no","yes","no","yes","yes","yes","yes","yes","no"] inputOutlook = input("What's outlook weather like today?(options: sunny, overcast, or rainy): ") inputTemp = input("What's the temperature looking like today?(options: hot, mild, or cool): ") inputHumidity = input("What's the humidity looking like today?(options: high or normal): ") inputWindy = input("Is it windy today?(options: true or false): ") total = len(play) yes = 0 no = 0 for outcome in play: if(outcome == "no"): no += 1 else: yes += 1 Pyes = yes / total Pno = no / total PoutlookInputYes = 0 PtempInputYes = 0 PhumidityInputYes = 0 PwindyInputYes = 0 PoutlookInputNo = 0 PtempInputNo = 0 PhumidityInputNo = 0 PwindyInputNo = 0 for index in range(0, len(play)): outcome = play[index] if outcome == "yes": if outlook[index] == inputOutlook: PoutlookInputYes += 1 if temp[index] == inputTemp: PtempInputYes += 1 if humidity[index] == inputHumidity: PhumidityInputYes += 1 if windy[index] == inputWindy: PwindyInputYes += 1 else: if outlook[index] == inputOutlook: PoutlookInputNo += 1 if temp[index] == inputTemp: PtempInputNo += 1 if humidity[index] == inputHumidity: PhumidityInputNo += 1 if windy[index] == inputWindy: PwindyInputNo += 1 PoutlookInputYes /= yes PtempInputYes /= yes PhumidityInputYes /= yes PwindyInputYes /= yes PoutlookInputNo /= no PtempInputNo /= no PhumidityInputNo /= no PwindyInputNo /= no PAllYes = PoutlookInputYes * PtempInputYes * PhumidityInputYes * PwindyInputYes * Pyes PAllNo = PoutlookInputNo * PtempInputNo * PhumidityInputNo * PwindyInputNo * Pno inputMatchesOutlook = 0 inputMatchesTemp = 0 inputMatchesHumidity = 0 inputMatchesWindy = 0 for o in outlook: if o == inputOutlook: inputMatchesOutlook += 1 for t in temp: if t == inputTemp: inputMatchesTemp += 1 for h in humidity: if h == inputHumidity: inputMatchesHumidity += 1 for w in windy: if w == inputWindy: inputMatchesWindy += 1 PEvidence = inputMatchesOutlook/len(outlook) * inputMatchesTemp/len(temp) * inputMatchesHumidity/len(humidity) * inputMatchesWindy/len(windy) PPlay = PAllYes/ PEvidence PNoPlay = PAllNo/PEvidence if PPlay > PNoPlay: print("You can play golf today :)") else: print("You can't play golf today :(")

Conversions - Decimal, Hexadecimal, and Binary Numbers

This code converts decimal, hexadecimal, and binary numbers into another type of number.

import math ##OTHER METHODS def turnToHexaNum(remainder): if(remainder == '10'): remainder = 'A' elif(remainder == '11'): remainder = 'B' elif(remainder == '12'): remainder = 'C' elif(remainder == '13'): remainder = 'D' elif(remainder == '14'): remainder = 'E' elif(remainder == '15'): remainder = 'F' return remainder ##CONVERSION METHODS def BinaryToDecimal(Binary): Binary = Binary [::-1] arrayBinary = [] index = 0 decimal = 0 for ch in Binary: array = (ch, index) arrayBinary.append(array) index += 1 for num in arrayBinary: decimal += int(num[0]) * int(2 ** num[1]) return decimal def DecimalToBinary(decimal): remainders = '' while decimal > 0: remainder = decimal % 2 decimal = decimal // 2 remainders += str(remainder) return remainders [::-1] def DecimalToHexadecimal(decimal): remainders = '' while(decimal > 16): remainder = str(decimal % 16) decimal = decimal // 16 remainder = turnToHexaNum(remainder) remainders += remainder remainder = str(decimal) remainder = turnToHexaNum(remainder) remainders += remainder return remainders [::-1] def BinaryToHexadecimal(Binary): decimal = BinaryToDecimal(Binary) return DecimalToHexadecimal(decimal) def HexadecimalToDecimal(Hexadecimal): decimal = 0 Hexadecimal = Hexadecimal [::-1] index = 0 for ch in Hexadecimal: if ch == 'A': ch = '10' elif ch == 'B': ch = '11' elif ch == 'C': ch = '12' elif ch == 'D': ch == '13' elif ch == 'E': ch == '14' elif ch == 'F': ch == '15' decimal += int(ch) * (16 ** index) index += 1 return decimal def HexadecimalToBinary(Hexadecimal): decimal = HexadecimalToDecimal(Hexadecimal) return DecimalToBinary(decimal) print('Binary to Decimal: ' + str(BinaryToDecimal('110101010'))) print('Decimal to Binary: ' + DecimalToBinary(426)) print('Decimal to Hexadecimal: ' + DecimalToHexadecimal(426)) print('Binary to Hexadecimal: ' + BinaryToHexadecimal('110101010')) print('Hexadecimal to Decimal: ' + str(HexadecimalToDecimal('1AA'))) print('Hexadecimal to Binary: ' + HexadecimalToBinary('1AA'))
1 2