Hack #1 - Class Notes

In this section, I take my own notes on the section. I have split it up into a vocabulary section and a section for miscellaneous class notes.

Vocabulary

Simulations: abstractions that mimic more complex objects or phenomena from the real world. (The purpose is drawing inferences without the contraints of the real world.)

Variance: random chance, simulated through random number generation in simulations.

Miscellaneous Class Notes

  • Typically, simulations leave out specific details or simplify complex aspects. It is crucial, however, to have variables to represent variance in the situation.
  • Simulations often contain some amount of bias.
  • Variability and randomness exists inherently in the world, and we can represent this with random number generation.

Here are some helpful functions for these simulations:

import random # a module that defines a series of functions for generating or manipulating random integers
random.choice() #returns a randomly selected element from the specified sequence
random.choice([1, 2, 3]) # returns random value from list
random.randint(0,10) #randomly selects an integer from given range; range in this case is from 0 to 10
random.random() #will generate a random float between 0.0 to 1.

Check-in Simulation Problem

Question: The following code simulates the feeding of 4 fish in an aquarium while the owner is on a 5-day trip:

numFish ← 4
foodPerDay ← 20
foodLeft ← 160
daysStarving ← 0
REPEAT 5 TIMES {
    foodConsumed ← numFish * foodPerDay
    foodLeft ← foodLeft - foodConsumed
    IF (foodLeft < 0) {
        daysStarving ← daysStarving + 1
    }
}

Why is this simulation considered an abstraction?

  1. It uses a conditional to execute one part of the code only when a particular condition is met.
  2. It uses a REPEAT loop to run the same block of code multiple times.
  3. It simplifies a real-world scenario into something that can be modeled in code and executed on a computer.
  4. It does not request input from the user or display output to the user.

Explanation: The simulation is considered an abstraction because it is represented in separate terms (abstracted) into a computer language, but still made to function in its intended circumstances.

Hack #2 - Functions Classwork

Below is the functions we were asked to use for the classwork.

Trying Randomization Functions

We were asked to do this:

Randomly select select a number from 1-100, assign it to be x, and print it. (If you have time, add a user input box!)

I did it below. Here's the first one that generates a random integer from 1 to 100.

import random
x = random.randint(1, 100)
print(x)
41

And here's something that encorporates user input.

import random
print("Please pick the lower bound of the RNG.")
x = int(input())
print("You picked", str(x) + ".")
print("Please pick the upper bound of the RNG.")
y = int(input())
print("You picked", str(y) + ".")
print("Your random number is...", str(random.randint(x, y)) + ".")
Please pick the lower bound of the RNG.
You picked 10.
Please pick the upper bound of the RNG.
You picked 20.
Your random number is... 11.

Closet User Input Function

Here is my program that lets you add to and remove things from your clothes list.

myclothes = ["red shoes", "green pants", "tie", "belt"]

def mycloset():
    print("Your clothes:")
    for clothing in myclothes:
        print("-", clothing.capitalize())
    print("What would you like to do?\n1. Add clothes\n2. Remove clothes\n3. All done")
    rsp = input("Pick one of the two numbers?")
    if rsp == "1":
        print("What clothing would you like to add?")
        rsp = input("What would you like to call it?")
        myclothes.append(rsp)
        mycloset()
    elif rsp == "2":
        print("What clothing would you like to remove?")
        i = 0
        while i < len(myclothes):
            print(str(i + 1) + ".", myclothes[i].capitalize())
            i += 1
        rsp = (int(input("Input an integer in range.")) - 1)
        if 0 <= rsp < len(myclothes):
            myclothes.pop(rsp)
            mycloset()
        else:
            print("Invalid input.")
    elif rsp == "3":
        return "Thanks!"
    else:
        print("invalid input.")
mycloset()
Your clothes:
- Red shoes
- Green pants
- Tie
- Belt
What would you like to do?
1. Add clothes
2. Remove clothes
3. All done
What clothing would you like to remove?
1. Red shoes
2. Green pants
3. Tie
4. Belt
Your clothes:
- Red shoes
- Tie
- Belt
What would you like to do?
1. Add clothes
2. Remove clothes
3. All done

Coin Flip Example

Here is the example provided in class.

import random

def coinflip():         #def function 
    randomflip = random.randint(0, 1) #picks either 0 or 1 randomly (50/50 chance of either) 
    if randomflip == 0: #assigning 0 to be heads--> if 0 is chosen then it will print, "Heads"
        print("Heads")
    else:
        if randomflip == 1: #assigning 1 to be tails--> if 1 is chosen then it will print, "Tails"
            print("Tails")

#Tossing the coin 5 times:
t1 = coinflip()
t2 = coinflip()
t3 = coinflip()
t4 = coinflip()
t5 = coinflip()
Tails
Tails
Tails
Heads
Heads

We were asked to make the coinflip weighted. I made heads twice as likely to be selected as tails in the code below.

def weightedcoin():
    flip = random.randint(0, 2)
    if flip >= 1:
        return "Heads"
    else:
        return "Tails"

t1 = weightedcoin()
t2 = weightedcoin()
t3 = weightedcoin()
t4 = weightedcoin()
t5 = weightedcoin()
print("Outcomes:", t1 + ",", t2 + ",", t3 + ",", t4 + ",", t5)
Outcomes: Heads, Heads, Heads, Tails, Heads

Hack #3 - Binary Simulation Problem

Here's the function to simulate the zombie apocalypse. Each bit of binary in the 8-bit string corresponds to a person's index in the survivorstatus list.

import random

def randomnum(): # function for generating random int
    return random.randint(0, 255)

def converttobin(num): # function for converting decimal to binary
    i = 7
    binary = ""
    while i >= 0:
        if num % (2**i) == num:
            binary += "0"
            i -= 1
        else:
            binary += "1"
            num -= 2**i
            i -= 1
    return binary

def survivors(binary): # function to assign position
    survivorstatus = ["Drew", "AJ", "Tony", "Katie" , "Fatso", "Elfen Child", "Kiddo", "Kid in Basement"]
    i = 0
    while i < len(survivorstatus):
        if binary[i] == "1":
            temp = "Zombie"
        else:
            temp = "Human"
        survivorstatus[i] = (survivorstatus[i], temp)
        i += 1
    for human, state in survivorstatus:
        print(human + ":", state)

survivors(converttobin(randomnum()))
Drew: Human
AJ: Human
Tony: Zombie
Katie: Zombie
Fatso: Human
Elfen Child: Human
Kiddo: Human
Kid in Basement: Human

Hack #4 - Thinking Through a Problem

For the dice roll program, I involved an integer parameter that determines how many trials of dice rolls will be simulated. The results are appended to a list that is then returned. That function is found below.

import random

def diceroll(times):
    results = []
    i = 0
    while i < times:
        results.append(random.randint(1, 6))
        i += 1
    return results

results = diceroll(5)
print("Rolls: ", end = '')
for roll in results:
    print(str(roll) + " ", end = '')
Rolls: 4 3 1 6 6 

Hack 5 - Applying your knowledge to situation based problems

This was the assignment.

Using the questions bank below, create a quiz that presents the user a random question and calculates the user's score. You can use the template below or make your own. Making your own using a loop can give you extra points.

I decided to make my own loop, which randomly selects a question (and never repeats the same question). The two additional questions are mostly vocabulary-based.

The Questions

See the last two for my own (they're both vocabulary-based).

  1. A researcher gathers data about the effect of Advanced Placement®︎ classes on students' success in college and career, and develops a simulation to show how a sequence of AP classes affect a hypothetical student's pathway. Several school administrators are concerned that the simulation contains bias favoring high-income students, however.
    • answer options:
      1. The simulation is an abstraction and therefore cannot contain any bias
      2. The simulation may accidentally contain bias due to the exclusion of details. (right)
      3. If the simulation is found to contain bias, then it is not possible to remove the bias from the simulation.
      4. The only way for the simulation to be biased is if the researcher intentionally used data that favored their desired output.
  2. Jack is trying to plan his financial future using an online tool. The tool starts off by asking him to input details about his current finances and career. It then lets him choose different future scenarios, such as having children. For each scenario chosen, the tool does some calculations and outputs his projected savings at the ages of 35, 45, and 55. Would that be considered a simulation and why?
    • answer options
      1. No, it's not a simulation because it does not include a visualization of the results.
      2. No, it's not a simulation because it does not include all the details of his life history and the future financial environment.
      3. Yes, it's a simulation because it runs on a computer and includes both user input and computed output.
      4. Yes, it's a simulation because it is an abstraction of a real world scenario that enables the drawing of inferences. (correct)
  3. Sylvia is an industrial engineer working for a sporting goods company. She is developing a baseball bat that can hit balls with higher accuracy and asks their software engineering team to develop a simulation to verify the design. Which of the following details is most important to include in this simulation?
    • answer options
      1. Realistic sound effects based on the material of the baseball bat and the velocity of the hit
      2. A depiction of an audience in the stands with lifelike behavior in response to hit accuracy
      3. Accurate accounting for the effects of wind conditions on the movement of the ball (correct)
      4. A baseball field that is textured to differentiate between the grass and the dirt
  4. Ashlynn is an industrial engineer who is trying to design a safer parachute. She creates a computer simulation of the parachute opening at different heights and in different environmental conditions. What are advantages of running the simulation versus an actual experiment?
    • answer options
      1. The simulation will not contain any bias that favors one body type over another, while an experiment will be biased.
      2. The simulation will be biased in favor of Ashlynn's design
      3. The simulation will accurately predict the parachute's safety level, while an experiment may be inaccurate due to faulty experimental design.
      4. The simulation can test the parachute design in a wide range of environmental conditions that may be difficult to reliably reproduce in an experiment. (correct)
    • I edited the second correct answer to avoid confusion
  5. PERSONAL QUESTION: What is the purpose of simulations?
    • answer options
      1. To draw inferences without the contraints of the real world (correct)
      2. To perfectly recreate a situation without any bias
      3. To prove that the simulated situation is only practical in theory
      4. To ignore distracting details that may influence the outcome of a situation
  6. PERSONAL QUESTION: How is random variability accounted for in simulations?
    • answer options
      1. Clear frontend that shows visual aspects of the scenario
      2. Connection to an extensive API with historical data
      3. Random or pseudo-random number generation (correct)
      4. Inconsistent interpretation of concrete conditions

My Quiz

I made sure to include a randomization system for the questions. There is also a failsafe system in place in case the user accidentally inputs an invalid response.

import random #used to randomize the questions

questions = [
    {"q": "1. A researcher gathers data about the effect of Advanced Placement®︎ classes on students' success in college and career, and develops a simulation to show how a sequence of AP classes affect a hypothetical student's pathway. Several school administrators are concerned that the simulation contains bias favoring high-income students, however.",
    "a": "a. The simulation is an abstraction and therefore cannot contain any bias.\nb. The simulation may accidentally contain bias due to the exclusion of details.\nc. If the simulation is found to contain bias, then it is not possible to remove the bias from the simulation.\nd. The only way for the simulation to be biased is if the researcher intentionally used data that favored their desired output.",
    "correct": "b"},
    {"q": "Jack is trying to plan his financial future using an online tool. The tool starts off by asking him to input details about his current finances and career. It then lets him choose different future scenarios, such as having children. For each scenario chosen, the tool does some calculations and outputs his projected savings at the ages of 35, 45, and 55. Would that be considered a simulation and why?",
    "a": "a. No, it's not a simulation because it does not include a visualization of the results.\nb. No, it's not a simulation because it does not include all the details of his life history and the future financial environment.\nc. Yes, it's a simulation because it runs on a computer and includes both user input and computed output.\nd. Yes, it's a simulation because it is an abstraction of a real world scenario that enables the drawing of inferences.",
    "correct": "d"},
    {"q": "Sylvia is an industrial engineer working for a sporting goods company. She is developing a baseball bat that can hit balls with higher accuracy and asks their software engineering team to develop a simulation to verify the design. Which of the following details is most important to include in this simulation?",
    "a": "a. Realistic sound effects based on the material of the baseball bat and the velocity of the hit.\nb. A depiction of an audience in the stands with lifelike behavior in response to hit accuracy.\nc. Accurate accounting for the effects of wind conditions on the movement of the ball.\nd. A baseball field that is textured to differentiate between the grass and the dirt.",
    "correct": "c"},
    {"q": "Ashlynn is an industrial engineer who is trying to design a safer parachute. She creates a computer simulation of the parachute opening at different heights and in different environmental conditions. What are advantages of running the simulation versus an actual experiment?",
    "a": "a. The simulation will not contain any bias that favors one body type over another, while an experiment will be biased.\nb. The simulation will be biased in favor of Ashlynn's design.\nc. The simulation will accurately predict the parachute's safety level, while an experiment may be inaccurate due to faulty experimental design.\nd. The simulation can test the parachute design in a wide range of environmental conditions that may be difficult to reliably reproduce in an experiment.",
    "correct": "d"},
    {"q": "What is the purpose of simulations?",
    "a": "a. To draw inferences without the contraints of the real world\nb. To perfectly recreate a situation without any bias\nc. To prove that the simulated situation is only practical in theory\nd. To ignore distracting details that may influence the outcome of a situation",
    "correct": "a"},
    {"q": "How is random variability accounted for in simulations?", "a": "a. Clear frontend that shows visual aspects of the scenario\nb. Connection to an extensive API with historical data\nc. Random or pseudo-random number generation\nd. Inconsistent interpretation of concrete conditions",
    "correct": "c"}
] #six questions, selected randomly
validresponse = ["a", "b", "c", "d"] #a list of valid inputs
score = 0 #score is set at zero, incremented later unless you suck

def quizloop():
    i = 0 #represents the number of questions asked, starting at 0 (meaning 1)
    while i < 5:
        quesnum = int(random.randrange(len(questions))) #question number is generated randomly based on the number of questions remaining in "questions"
        question = questions[quesnum]["q"] #pulling the question from the randomly-selected dictionary
        answers = questions[quesnum]["a"] #pulling the answer from the randomly-selected dictionary
        print(question + "\n" + answers) #printing the question
        answercheck(quesnum) #receiving and checking the accuracy of the user's answer
        questions.pop(quesnum) #removing the already asked question from the list so that it isn't repeated
        i += 1 #i incremented to indicate that one more of the five questions has already been asked
    scorecheck() #a reflection on your score

def answercheck(quesnum):
    global score #retrieving global element "score"
    choice = input("Pick an option: a, b, c or d. Do not include the period.").lower() #using .lower() so that capital answers are still detected correct
    if choice in validresponse: #ensuring the response is one of the four valid letters
        pass
    else:
        print("Invalid response.")
        answercheck(quesnum)
        return
    if choice == questions[quesnum]["correct"]: #if the choice is correct
        print('Good job! "' + choice + '" is the correct answer.')
        score += 1
    else: #if the choice isn't correct
        print('Unfortunately, "' + questions[quesnum]["correct"] + '" was the correct answer.')
    
def scorecheck():
    percent = int(100 * (int(score) / 5)) #calculating percent value of score, converted with int() for no ugly decimal
    print("You scored", str(int(score)), "out of 5 on the quiz. That's", str(percent) + "%!")
    if percent < 80: #if you didn't score a passing score
        print("Unfortunately, you needed at least 80% (3 out of 5) to pass.\nBetter luck next time!")
    else: #if you did score a passing score
        print("Congratulations, that's a passing score! You're a real expert at simulations.")

#all of the quiz happens with just this one function
quizloop()
Sylvia is an industrial engineer working for a sporting goods company. She is developing a baseball bat that can hit balls with higher accuracy and asks their software engineering team to develop a simulation to verify the design. Which of the following details is most important to include in this simulation?
a. Realistic sound effects based on the material of the baseball bat and the velocity of the hit.
b. A depiction of an audience in the stands with lifelike behavior in response to hit accuracy.
c. Accurate accounting for the effects of wind conditions on the movement of the ball.
d. A baseball field that is textured to differentiate between the grass and the dirt.
Good job! "c" is the correct answer.
How is random variability accounted for in simulations?
a. Clear frontend that shows visual aspects of the scenario
b. Connection to an extensive API with historical data
c. Random or pseudo-random number generation
d. Inconsistent interpretation of concrete conditions
Good job! "c" is the correct answer.
What is the purpose of simulations?
a. To draw inferences without the contraints of the real world
b. To perfectly recreate a situation without any bias
c. To prove that the simulated situation is only practical in theory
d. To ignore distracting details that may influence the outcome of a situation
Good job! "a" is the correct answer.
Jack is trying to plan his financial future using an online tool. The tool starts off by asking him to input details about his current finances and career. It then lets him choose different future scenarios, such as having children. For each scenario chosen, the tool does some calculations and outputs his projected savings at the ages of 35, 45, and 55. Would that be considered a simulation and why?
a. No, it's not a simulation because it does not include a visualization of the results.
b. No, it's not a simulation because it does not include all the details of his life history and the future financial environment.
c. Yes, it's a simulation because it runs on a computer and includes both user input and computed output.
d. Yes, it's a simulation because it is an abstraction of a real world scenario that enables the drawing of inferences.
Good job! "d" is the correct answer.
Ashlynn is an industrial engineer who is trying to design a safer parachute. She creates a computer simulation of the parachute opening at different heights and in different environmental conditions. What are advantages of running the simulation versus an actual experiment?
a. The simulation will not contain any bias that favors one body type over another, while an experiment will be biased.
b. The simulation will be biased in favor of Ashlynn's design.
c. The simulation will accurately predict the parachute's safety level, while an experiment may be inaccurate due to faulty experimental design.
d. The simulation can test the parachute design in a wide range of environmental conditions that may be difficult to reliably reproduce in an experiment.
Good job! "d" is the correct answer.
You scored 5 out of 5 on the quiz. That's 100%!
Congratulations, that's a passing score! You're a real expert at simulations.

Hack #6 / Challenge - Taking real life problems and implementing them into code

I made a simulation that lets you breed flowers together and, based on their phenotype, there is a chance of various new colors of flowers being bred.

There are even some rare types of flowers that can be created by combining breeds of flowers and getting lucky. You can find out more about the flowers by choosing "Info" in the simulation options.

The simulation runs as long as you want it to. Please try it out on your own if you want! It's kind of fun.

from IPython.display import clear_output as clr
from random import randint as rng
import time
#defining flower classes
class Flower:
    def __init__(self, id, name, phenos, rarity):
        self.name = name
        self.id = id
        self.phenos = phenos
        self.rarity = rarity
#initializing types of flowers
red = Flower(0, "Red", ["A"], "Common")
purered = Flower(1, "Pure Red", ["A", "A"], "Rare")
blue = Flower(2, "Blue", ["B"], "Common")
pureblue = Flower(3, "Pure Blue", ["B", "B"], "Rare")
yellow = Flower(4, "Yellow", ["C"], "Common")
pureyellow = Flower(5, "Pure Yellow", ["C", "C"], "Rare")
white = Flower(6, "White", ["D"], "Common")
purewhite = Flower(7, "Pure White", ["D", "D"], "Rare")
violet = Flower(8, "Violet", ["A", "B"], "Hybrid")
green = Flower(9, "Green", ["B", "C"], "Hybrid")
orange = Flower(10, "Orange", ["A", "C"], "Hybrid")
pink = Flower(11, "Pink", ["A", "D"], "Hybrid")
skyblue = Flower(12, "Sky Blue", ["B", "D"], "Hybrid")
cream = Flower(13, "Cream", ["C", "D"], "Hybrid")
gold = Flower(14, "Gold", ["A", "B", "C", "D"], "Super Rare")
#list of various flower types
flowerlist = [red, purered, blue, pureblue, yellow, pureyellow, white, purewhite,
violet, green, orange, pink, skyblue, cream, gold]
#initializing starting garden
garden = [red, blue, yellow, white]
#priorities for breeding
priolist = {"A": 0, "B": 1, "C": 2, "D": 3}
def breedchoice():
    tempgarden = []
    for flower in garden:
        tempgarden.append(flower)
    print("Which flower would you like to breed?")
    for i in range(len(tempgarden)):
        print(str(i + 1) + ".", tempgarden[i].name)
    rsp = input("Choose one of these flowers.")
    try:
        f1 = tempgarden[int(rsp) - 1]
        tempgarden.pop(int(rsp) - 1)
        print("Which other flower would you like to breed?")
        for i in range(len(tempgarden)):
            print(str(i + 1) + ".", tempgarden[i].name)
        rsp = input("Choose one of these flowers.")
        try:
            f2 = tempgarden[int(rsp) - 1]
            breed(f1, f2)
        except:
            print('Invalid input.')
            breedchoice()
    except:
        print('Invalid input.')
        breedchoice()
#function for breeding flowers
def breed(f1, f2):
    result = []
    print("Breeding", f1.name, "and", f2.name + "...")
    if f1.rarity == "Rare" and f2.rarity == "Rare":
        odds = rng(0, 2)
        if odds == 0:
            print("WOW! You bred the rare Gold flower!")
            garden.append(gold)
        elif odds == 1:
            print("You bred a", f1.name + "!")
        else:
            print("You bred a", f2.name + "!")
        flowersim()
        return
    temp = rng(0, (len(f1.phenos) - 1))
    result.append(f1.phenos[temp])
    temp = rng(0, (len(f2.phenos) - 1))
    temp = f2.phenos[temp]
    if priolist[temp] < priolist[result[0]]:
        result.insert(0, temp)
    else:
        result.append(temp)
    for flower in flowerlist:
        if flower.phenos == result:
            print("You bred a(n)", flower.name + "!")
            if flower not in garden:
                garden.append(flower)
            time.sleep(1)
    flowersim()
#function for getting flower info
def flowerinfo():
    print("Which flower would you like to know about?")
    for i in range(len(garden)):
        print(str(i + 1) + ".", garden[i].name)
    rsp = input("Choose one of these flowers.")
    try:
        chosen = garden[int(rsp) - 1]
        print("Name:", chosen.name)
        print("Phenotype:", chosen.phenos)
        print("Rarity:", chosen.rarity)
        print('Press the "ENTER" key when finished.')
        done = input()
        flowersim()
    except:
        print("Invalid input.")
        flowerinfo()
def flowersim():
    clr(wait=True)
    print("Your Garden:")
    for i in range(len(garden)):
        print(str(i + 1) + ".", garden[i].name, "(" + garden[i].rarity + ")")
    print("What would you like to do?\n1. Breed\n2. Info\n3. Finish")
    asking = True
    while asking:
        rsp = input("Please choose one of these options.")
        if rsp == "1":
            breedchoice()
            asking = False
        elif rsp == "2":
            flowerinfo()
            asking = False
        elif rsp == "3":
            print("Thank you for playing!")
            asking = False
        else:
            flowersim()
            return
flowersim()
Your Garden:
1. Red (Common)
2. Blue (Common)
3. Yellow (Common)
4. White (Common)
5. Violet (Hybrid)
6. Orange (Hybrid)
7. Pink (Hybrid)
8. Green (Hybrid)
9. Sky Blue (Hybrid)
10. Cream (Hybrid)
11. Pure Red (Rare)
12. Pure Blue (Rare)
13. Pure Yellow (Rare)
14. Pure White (Rare)
15. Gold (Super Rare)
What would you like to do?
1. Breed
2. Info
3. Finish
Thank you for playing!

As you can see here, I went through and bred every flower in the simulation. I hope you enjoy messing with it if you end up doing so.