Google Open Source

Ever wonder what goes on behind the scenes with googles various products, languages, and frameworks? Google is a huge advocate for open source projects, and along with GitHub, they have their own version management system. You can find their public repositories listed on their website linked below:

https://opensource.google/
I <3 OpenSource

Web Server written in GoLang

This is a basic web server made with the language Go. I added a basic mdbootstrap landing template as a placeholder for an index.html, though the main focus was the language itself. Go is a language that was developed by google employees in 2009 and has developed into a large open-source project. The reason Go is unique is because of its Async functionality, low level functionality, and simplicity. It is similar to scripting languages (such as python, javascript, etc.) because of its simplicity and learning curve, though has features such as pointers similar to lower level languages. Furthermore, since Go is a compiled language, it is fast as it compiles into machine code. Also, Go is a statically typed language similar to Java, C++, and C. Statically-typed languages require type definitions initialized before said variable is used, while dynamically-typed languages perform type checking at runtime; most programmers don't find this too limiting, though it is something to account for. I have been currently learning GoLang through the website linked below.

https://gobyexample.com/
Adam Blumenfeld Mar 20

Example of static typing: int num; num = 4 Example of dynamic typing: num = 4

Adam Blumenfeld May 09

Awesome Post

Adam Blumenfeld Mar 20

**Side note The official name of the language is "Go". Though some people refer to it by "GoLang" due to their website being named https://golang.org/

This is a user-friendly Hangman game. I was working on it for three weeks.

https://repl.it/@BYLDOG/hangman
print("Starting a game of Hangman.") from random import randint valid1 = 0 x = 0 hg = 0 valid2 = 0 valid27000 = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ] valid30 = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25" ] valid900 = ["3", "4", "5", "6", "7", "8", "9", "10"] allwords = [ "dog", "cat", "man", "woman", "drums", "cousin", "brother", "epidemic", "pencilcase" ] y = len(allwords) validwords = [] while valid1 == 0: attempts = input("How many incorrect attempts do you want? [1-25] ") if attempts not in valid30: print("Not a valid number from 1 to 25") else: valid1 = 1 attempts = int(attempts) while valid2 == 0: minlen = input("What's the minimum length of the word? [3-10] ") if minlen not in valid900: print("Not a valid number from 3 to 10") else: valid2 = 1 minlen = int(minlen) while x in range(-1, y - 1): x = x + 1 lenx = int(len(allwords[x])) valid3 = max(lenx, minlen) if valid3 == lenx: validwords.append(allwords[x]) wordnm = randint(0, len(validwords) - 1) word = validwords[wordnm] wordlen = len(word) guess = [] wordlist = [] for x in range(0, wordlen): x = x + 1 guess.append("*") wordlist.append(word[x - 1]) while attempts > 0: print(guess) guess1 = input("Enter your guess: ") if guess1 not in valid27000: print( "This is not a valid guess. Try inputting a lowercase English letter" ) else: if guess1 not in wordlist: if attempts != 1: print("This letter is not in the word. Try again") else: print( "This letter is not in the word. You have ran out of attempts." ) attempts = attempts - 1 else: print("This letter is in the word") while hg in range(0, len(wordlist)): if wordlist[hg] == guess1: guess[hg] = guess1 hg = hg + 1 if guess == wordlist: print("You won! Congrats. The word is " + word) while True: aohuni = 1 hg = 0

Update For Code On Web Scraper

I accidentally forgot to include a filter for prices, here's the updated code.

""" Copyright Adam Blumenfeld All rights reserved """ # These are the variable you have to set Email = "email@example.com" Password = "examplepassword" # Imports import requests from bs4 import BeautifulSoup import smtplib import time import datetime import keyboard as k import sys wait = True def wait_false(): global wait wait = False k.add_hotkey("ctrl+g", lambda: wait_false()) # URLS you want to check URLS = ["https://www.amazon.com/Lysol-Bathroom-Cleaner-Island-Breeze/dp/B06ZZQSH77/ref=sr_1_5?dchild=1&keywords=lysol+spray&qid=1588110272&sr=8-5", "https://www.amazon.com/Lysol-Disinfectant-Spray-Morning-Breeze/dp/B01IAIMYF2/ref=sr_1_1?dchild=1&keywords=lysol+disinfectant&qid=1588133936&sr=8-1", "https://www.amazon.com/Scott-67805-Recycled-Bathroom-Tissue/dp/B0040ZOIZO/ref=pd_ybh_a_5?_encoding=UTF8&psc=1&refRID=Y73XTT0K4CR1PQMFPV3V", "https://www.amazon.com/AmScope-120X-1200X-M30-ABS-KT2-W-Beginner-Microscope/dp/B00GGY85EC/ref=sr_1_1?dchild=1&keywords=microscope&qid=1588207972&s=industrial&sr=1-1"] # Time you want to space out already made emails (If you want to never relese emails on an item again, set it to float('inf')) cooldown_time = 7200 headers = { "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36'} def check(URL, maillist): page = requests.get(URL, headers=headers) soup1 = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(soup1.prettify(), "html.parser") title = soup.find(id="productTitle").get_text().strip().split(',')[0] available = soup.find(id="availability") price = soup.find(id="priceblock_ourprice") if price != None: print("Product is available") send_mail(title, URL, maillist) return True if available == None: print("Product is available") send_mail(title, URL) return True available = available.findChild('span').get_text().strip()[0:15] if available == "Temporarily out": print("Product is available") send_mail(title, URL, maillist) return True print("Product isn't available") return False def send_mail(title, link, maillist): global email global password server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(email, password) subject = f'"{title}" is available!' body = f'Check the Amazon link to see availablility: {link}' msg = f"Subject: {subject}\n\n{body}" server.sendmail( email, maillist, msg ) print('Email Has Been Sent!') server.quit() wait = True cooldown = {} # The time you want between checks time_between_checks = 120 while True: print("Press CTRL+g to fast forward check") i = 0 while i < time_between_checks and wait: time.sleep(1) print("Time since last check:", i, "\\", time_between_checks, end="\r") i += 1 wait = True print("\n") for URL in URLS: time_ = datetime.datetime.now() print(f"Checking... <{time_}> <{URL}>\n") if cooldown.get(URL) != None: if time.time() - cooldown[URL] >= cooldown_time: del cooldown[URL] else: print(f"Cooldown time for URL <{URL}>: {cooldown_time-int((time.time() - cooldown[URL]) % 60)} seconds") continue availability = check(URL, sys.argv) if availability: cooldown[URL] = time.time() print("\n\n")

Web Scraper For Amazon Availibility

This web scraper checks amazon links by URL every two minutes, and emails you when those products are available. There is a cooldown of 4 hours for products that have been found available and emailed to you, but this cooldown only affects the particular item and not all of the URLs. By the way these parameters are completely customizable (you can have your wait time be 5 minutes, your cooldown be infinite, etc.) I made this scraper to help people out with panic buying and the lowered availability of basic items. In my original program, I made an email called amazonbot100@gmail.com to carry out the emails. To set up an email with this program, here are the steps: 1. Create a new email (Recommended, but not required) 2. Enable two-factor authentication for your account (This is required for the next step) 3. Set up App Passwords for your account and create a new one for your computer. 4. Paste in the email address to the Email variable at the top, and paste the app password into the Password variable under that. 4.5. Search up "my user agent" on google and paste it into the user agent 5. Run python -m pip install bs4 6. Run python -m pip install requests 7. Run python -m pip install keyboard Also, I understand that the code isn't the most efficient, especially towards the end, though I was in a rush so don't judge me xD. Usage: python scraper.py email-to-send-1@example.com email-to-send-2@example.com email-to-send-3@example.com email-to-send-you-get-the-point@example.com

""" Copyright Adam Blumenfeld All rights reserved """ # These are the variable you have to set Email = "email@example.com" Password = "examplepassword" # Imports import requests from bs4 import BeautifulSoup import smtplib import time import datetime import keyboard as k import sys wait = True def wait_false(): global wait wait = False k.add_hotkey("ctrl+g", lambda: wait_false()) # URLS you want to check URLS = ["https://www.amazon.com/Lysol-Bathroom-Cleaner-Island-Breeze/dp/B06ZZQSH77/ref=sr_1_5?dchild=1&keywords=lysol+spray&qid=1588110272&sr=8-5", "https://www.amazon.com/Lysol-Disinfectant-Spray-Morning-Breeze/dp/B01IAIMYF2/ref=sr_1_1?dchild=1&keywords=lysol+disinfectant&qid=1588133936&sr=8-1", "https://www.amazon.com/Scott-67805-Recycled-Bathroom-Tissue/dp/B0040ZOIZO/ref=pd_ybh_a_5?_encoding=UTF8&psc=1&refRID=Y73XTT0K4CR1PQMFPV3V", "https://www.amazon.com/AmScope-120X-1200X-M30-ABS-KT2-W-Beginner-Microscope/dp/B00GGY85EC/ref=sr_1_1?dchild=1&keywords=microscope&qid=1588207972&s=industrial&sr=1-1"] # Time you want to space out already made emails (If you want to never relese emails on an item again, set it to float('inf')) cooldown_time = 7200 headers = { "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36'} def check(URL, maillist): page = requests.get(URL, headers=headers) soup1 = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(soup1.prettify(), "html.parser") title = soup.find(id="productTitle").get_text().strip().split(',')[0] available = soup.find(id="availability") if available == None: print("Product is available") send_mail(title, URL) return True available = available.findChild('span').get_text().strip()[0:15] if available == "Temporarily out": print("Product is available") send_mail(title, URL, maillist) return True print("Product isn't available") return False def send_mail(title, link, maillist): global email global password server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login(email, password) subject = f'"{title}" is available!' body = f'Check the Amazon link to see availablility: {link}' msg = f"Subject: {subject}\n\n{body}" server.sendmail( email, maillist, msg ) print('Email Has Been Sent!') server.quit() wait = True cooldown = {} # The time you want between checks time_between_checks = 120 while True: print("Press CTRL+g to fast forward check") i = 0 while i < time_between_checks and wait: time.sleep(1) print("Time since last check:", i, "\\", time_between_checks, end="\r") i += 1 wait = True print("\n") for URL in URLS: time_ = datetime.datetime.now() print(f"Checking... <{time_}> <{URL}>\n") if cooldown.get(URL) != None: if time.time() - cooldown[URL] >= cooldown_time: del cooldown[URL] else: print(f"Cooldown time for URL <{URL}>: {cooldown_time-int((time.time() - cooldown[URL]) % 60)} seconds") continue availability = check(URL, sys.argv) if availability: cooldown[URL] = time.time() print("\n\n")

Unstable Spiral (In Development) STATUS

Unstable Spiral is a legacy project dedicated to Howard Blumenfeld, author of 𝘔𝘦𝘯𝘵𝘢𝘭 𝘈𝘳𝘤𝘩𝘪𝘵𝘦𝘤𝘵𝘶𝘳𝘦 and Mathematics professor at Laspositas college. Unstable Spiral was a website that he worked on in college and for his birthday I'm recreating it with modern taste. I'm using bootstrap for the styling and PHP for the back end. The websites homepage is done and I am currently working on database integration. This website is still in development.

WEBSITE URL: https://repl.it/@Snakebiking49/Unstable-Spiral

Unstable Spiral (In Development)

Unstable Spiral is a legacy project dedicated to Howard Blumenfeld, author of 𝘔𝘦𝘯𝘵𝘢𝘭 𝘈𝘳𝘤𝘩𝘪𝘵𝘦𝘤𝘵𝘶𝘳𝘦 and Mathematics professor at Laspositas college. Unstable Spiral was a website that he worked on in college and for his birthday I'm recreating it with modern taste. I'm using bootstrap for the styling and PHP for the back end. The websites homepage is almost done and the rest of the website is in development. Go on the link below to see the website in development.

@AdamBlumenfeld The link to the website is https://unstable-spiral--snakebiking49.repl.co/ IN DEVELOPMENT

Linear Regression with any amount of variables

hm = int(input("Enter how many categories or inputs do you want: ")) boo = int(input("How many inputs per category do you want: ")) dataSet = [] for be in range(hm): print ("This is your " + str(be) + "th input set.") inputer = [] for i in range(boo): point = float(input("Enter value: ")) inputer.append(point) dataSet.append(inputer) outputs = [] for i in range(boo): print ("Enter you output.") output = float(input("Enter value: ")) outputs.append(output) dataSet.append(outputs) values = [] for i in range(hm): values.append(0) yIntercept = 0 def slopeDerivativeOne(dataSet, values, hm, boo, yIntercept, wanted): length = hm total = 0 wantedValues = [] a = dataSet[wanted] for i in range(len(a)): wantedValues.append(a[i]) for f in range(length): innerValues = [] for i in range(len(dataSet)): b = dataSet[i] val = b[f] innerValues.append(val) innerTotal = 0 for i in range(len(values)): bobby = values[i] * innerValues[i] innerTotal += bobby innerTotal += yIntercept jj = len(dataSet) - 1 nn = dataSet[jj] difference = (nn[f] - innerTotal) * wantedValues[f] total += difference returnValue = (-2/length) * total return returnValue def DerivativeOne(dataSet, values, hm, boo, yIntercept, wanted): length = hm total = 0 wantedValues = [] a = dataSet[wanted] for i in range(len(a)): wantedValues.append(a[i]) for f in range(length): innerValues = [] for i in range(len(dataSet)): z = dataSet[i] val = z[f] innerValues.append(val) innerTotal = 0 for i in range(len(values)): bobby = values[i] * innerValues[i] innerTotal += bobby innerTotal += yIntercept jj = len(dataSet) - 1 nn = dataSet[jj] difference = (nn[f] - innerTotal) total += difference print (total) returnValue = (-2/length) * total return returnValue def getCost(dataSet, values, hm, boo, yIntercept, wanted): total = 0 length = hm for f in range(length): innerValues = [] for i in range(len(dataSet)): z = dataSet[i] val = z[f] innerValues.append(val) innerTotal = 0 for i in range(len(values)): bobby = values[i] * innerValues[i] innerTotal += bobby innerTotal += yIntercept jj = len(dataSet) - 1 nn = dataSet[jj] difference = (nn[f] - innerTotal) total += difference print (total) return (abs(total)) l = 0.0001 iterations = 100000 previousValues = [] for x in range(len(values)): print (x) previousValues.append(5) previousYInt = 5 j = 0 while (True): j += 1 ds = [] for i in range(len(values)): d = slopeDerivativeOne(dataSet, values, hm, boo, yIntercept, i) word = values[i] - (l * d) values[i] = word d1 = DerivativeOne(dataSet, values, hm, boo, yIntercept, i) yIntercept = yIntercept - (l * d1) print (j) if j > 1000000: False break previousValues = (values) previousYInt = yIntercept for i in range(len(values)): bob = round(values[i], 2) print (bob) bobby = round(yIntercept, 2) print ("y-intercept" + str(bobby))

Linear Regression

This is Linear Regression


x = [15, 9, 12, 1, 10, 11, 4, 16, 2, 30, 4, 15, 18, 12, 14] y = [13 ,19, 16, 15, 24, 7, 18, 23, 28, 2, 26, 12, 18, 24, 17] def DerivativeSlope(x, y, slope, yInt): length = len(x) total = 0 for i in range(length): predicted = (slope * x[i]) + yInt difference = (y[i] - predicted) * x[i] total += difference returnValue = (-2/length) * total return returnValue def DerivativeIntercept(x, y, slope, yInt): length = len(x) total = 0 for i in range(length): predicted = (slope * x[i]) + yInt difference = (y[i] - predicted) total += difference returnValue = (-2/length) * total return returnValue m = 0 c = 0 l = 0.000001 iterations = 99999 for i in range(iterations): slope = DerivativeSlope(x, y, m ,c) intercept = DerivativeIntercept(x, y, m ,c) m = m - (l * slope) c = c - (l * intercept) print (m, c)

Linear Regression Using Gradient Decent

This is 𝓛𝓲𝓷𝓮𝓪𝓻 𝓡𝓮𝓰𝓻𝓮𝓼𝓼𝓲𝓸𝓷 𝓤𝓼𝓲𝓷𝓰 𝓖𝓻𝓪𝓭𝓲𝓮𝓷𝓽 𝓓𝓮𝓬𝓮𝓷𝓽 optimized to 50 milliseconds (average of 12).

""" @nexclap/AdamBlumenfeld """ # Imports import numpy as np from random import randint from matplotlib import pyplot as plt # Define Style Of Matplotlib Graphs plt.style.use("ggplot") # Define data X = np.array([1, 3, 5, 6, 8, 10, 11, 18, 19, 20, 24, 26, 30, 32, 36, 38, 39, 40, 43, 46, 52, 55, 56, 58, 59]) y = np.array([3, 4, 5, 7, 8, 9, 10, 12, 14, 15, 21, 36, 37, 38, 39, 40, 43, 46, 49, 51, 54, 56, 58, 60, 69]) # Plot data plt.scatter(X, y) plt.show() #Regressor Class class Regressor: # Training Function def fit(self, X, y, learning_rate=0.00001, converge=0.001, cst=False): # Cst is weather or not to make a history of cost for further analysis self.cst_b = cst if cst: self.cst = [[], []] # Dataset self.X = X self.y = y # Learning rate, or "a" in the gradient decent formula self.learning_rate = learning_rate # The M and B values in the hypothysis function self.theta = [0, 0] # Cost, which initialtes at infinity self.cost = float('inf') # The iterator of the gradient decent algorithm, mine is recursive (Lol, I just had to add that flex) self.gradient_decent_step(converge) # isub for theta, basically saying theta -= (whatever), only for practical reasons, I had to make it a seprete function def theta_isub(self, i, other): self.theta[i] -= other return self.theta[i] # Calculate and update (or store if cst is True) cost def _cost(self, iteration=None): # Cost function self.cost = (1/(2*len(X))*sum([(self.h(X[index]) - y[index])*X[index] for index in range(len(X))])**2) if self.cst_b: # Update cst self.cst[0].append(self.cost) self.cst[1].append(iteration) # Hypothesis function def h(self, x): # h_θ(x) = θ₁ + θ₀x (Yes, I know that in my hypothysis function is switched around) return x*self.theta[0] + self.theta[1] # Gradient decent iterator def gradient_decent_step(self, converge, iteration=1): # Base case: if the cost is less than the set convergence point than accept current theata values if self.cost <= converge: return None # Do one iteration of gradient decent self._step() # Compute cost self._cost(iteration) return self.gradient_decent_step(converge, iteration+1) # All the math of gradient decent, (Now you know why I made the theta_isub function) def _step(self): return [self.theta_isub(0, self.learning_rate * (1/len(X)*sum([(self.h(X[index]) - y[index])*X[index] for index in range(len(X))]))),self.theta_isub(1, self.learning_rate * (1/len(X)*sum([self.h(X[index]) - y[index] for index in range(len(X))])))] # Define a model model = Regressor() # Train model (With cst = True for graphing) model.fit(X, y, cst=True) # Get the theta (M and B values) and the cst variable (or history of cost to iterations) theta = model.theta cst = model.cst # Nerd plot stuff (Plot linear regression graph) x = np.linspace(0,60,100) y1 = theta[0]*x+theta[1] plt.title("Linear Regression") plt.scatter(X, y, c='teal') plt.plot(x, y1) #plt.savefig("linear_regression.png") (Saves graph to file) plt.show() # More nerd plot stuf (Plot cost graph (cst)) plt.title("Cost") plt.plot(cst[1], cst[0]) #plt.savefig("cost.png") (Saves graph to file) plt.show()

Linear Regression

This is linear regression from scratch. I used a Coursera course for help with this.

import numpy as np import pandas as pd import matplotlib.pyplot as plt x = [1, 5, 3, 4, 7, 9, 12, 13, 15, 16, 17, 4, 5, 2, 10, 23, 25] y = [5, 12, 23, 14, 17, 8, 20, 21, 25, 38, 42, 10, 13, 7, 23, 50, 55] plt.plot(x, y) plt.show() def slopeDerivative(x, y, slope, yInt): length = len(x) total = 0 for i in range(length): predicted = (slope * x[i]) + yInt difference = (y[i] - predicted) * x[i] total += difference returnValue = (-2/length) * total return returnValue def interceptDerivative(x, y, slope, yInt): length = len(x) total = 0 for i in range(length): predicted = (slope * x[i]) + yInt difference = (y[i] - predicted) total += difference returnValue = (-2/length) * total return returnValue m = 0 c = 0 l = 0.0001 iterations = 1000000 for i in range(iterations): derivativeSlope = slopeDerivative(x, y, m ,c) derivativeIntercept = interceptDerivative(x, y, m ,c) m = m - (l * derivativeSlope) c = c - (l * derivativeIntercept) print (m, c)

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()
1 2 ... 4