Hack #1 - Class Notes

  • Simulations are simple processes that mimic a more complex event in the real world
    • Can change parameters without real world concern
      • Time, money, etc.
  • Often necessary to remove details or simplify aspects
    • Can lead to bias due to some real world factor being left out
  • Variability created by RNG

Hack #2 - Functions Classwork

import random
n=int(input("Please enter a number"))
print("randomized number from 1 to",n,":",random.randint(1,n))
randomized number from 1 to 100 : 50
def mycloset():
    myclothes = ["red shoes", "green pants", "tie", "belt"]
    while True:
        print("your closet currently consists of:",", ".join(myclothes))
        command=input("please enter what you want to do (add/trash/end)")
        if command=="end":
            break
        elif command=="add":
            item=input("What you want to add?")
            myclothes.append(item)
        elif command=="trash":
            item=input("What you want to remove?")
            if myclothes.count(item)<0:
                print(item,"is not in your closet")
            else:
                myclothes.remove(item)
        else:
            print("Sorry, I did not understand what you said")
    print("your closet now consists of:",", ".join(myclothes))

mycloset()
your closet currently consists of: red shoes, green pants, tie, belt
Sorry, I did not understand what you said
your closet currently consists of: red shoes, green pants, tie, belt
your closet currently consists of: red shoes, green pants, tie, belt, blue shoes
your closet currently consists of: red shoes, green pants, tie, blue shoes
your closet now consists of: red shoes, green pants, tie, blue shoes

Hack #3 - Binary Simulation Problem

import random

def randomnum(l): # function for generating random int
    return random.randint(0,2**l-1) # generates a random int based on the length of a list

def converttobin(n,l): # function for converting decimal to binary
    ans = "" # starts the random
    for i in range(l-1,-1,-1): #goes from length down
        if n>=2**i: #if a number is greater than the greatest length:
            ans+='1' #add 1 to the and
            n-=2**i # subtract the 2 exponential
        else:
            ans+="0"
    return ans

def survivors(): # function to assign position
    survivorstatus = ["Jiya", "Shruthi", "Noor", "Ananya" , "Peter Parker", "Andrew Garfield", "Tom Holland", "Tobey Maguire"]
    binary=converttobin(randomnum(len(survivorstatus)),len(survivorstatus)) #generate a binary to simulate the status
    # print(binary)
    for i in range(len(survivorstatus)):
        if binary[i] == "1": #if the survivor is a zombie:
            print(survivorstatus[i],"is a zombie")
        else: # if not:
            print(survivorstatus[i],"is not a zombie")

survivors()
11001001
Jiya is a zombie
Shruthi is a zombie
Noor is not a zombie
Ananya is not a zombie
Peter Parker is a zombie
Andrew Garfield is not a zombie
Tom Holland is not a zombie
Tobey Maguire is a zombie

Hack #4 - Thinking through a problem

  • create your own simulation involving a dice roll
  • should include randomization and a function for rolling + multiple trials
import random

def dieRoll():
    return random.randint(1,6) #returns a number from 1 to 6

def diceRoll(a,b):
    aSum=0
    bSum=0
    for i in range(a):
        aSum+=dieRoll() # roll a dices
    for i in range(b):
        bSum+=dieRoll()# roll b dices
    print("Player A rolls",a,"dice and gets",aSum)# prints the results
    print("Player A rolls",b,"dice and gets",bSum)
    if aSum>bSum: # print who has the greatest value
        print("Player A goes first")
    else:
        print('Player B goes first')

diceRoll(int(input("Enter the amount of die player A has")),int(input("Enter the amount of die player B has")))
Player A rolls 4 dice and gets 15
Player A rolls 3 dice and gets 11
Player A goes first

Hack 5 - Applying your knowledge to situation based problems

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.

  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.
      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.
  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
      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 can be run more safely than an actual experiment
      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.
    • this question has 2 correct answers
  5. What is often used to create variablility in simulations?
    • anser options
      1. Telling the user to roll dice
      2. Using prestored value in the system to roll code
      3. Using a Random Number Generator
      4. Basing results off what other has said
  6. Which of the following options is used for simulating a die roll?
    • answer options
      1. random.random(1,6)
      2. random.randint(1,6)
      3. random.randrange(1,6)
      4. random.choice(1,6)
questions = 6
correct = 0

quiz=[
        ["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.",
        {
            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",
            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?",
        {
            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"
        },
        "4"
    ],
    ["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?",
        {
            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",
            4: "A baseball field that is textured to differentiate between the grass and the dirt"
        },
        "3"
    ],
    ["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? (this question has 2 correct answers, input anser with one comma, ascending, and no spaces)",
        {
            1: "The simulation will not contain any bias that favors one body type over another, while an experiment will be biased",
            2: "The simulation can be run more safely than an actual experiment",
            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"
        },
        "2,4"
    ],
    ["What is often used to create variablility in simulations?",
        {
            1: "Telling the user to roll dice",
            2:  "Using prestored value in the system to roll code",
            3: "Using a Random Number Generator",
            4: "Basing results off what other has said"
        },
        "3"
    ],
    ["Which of the following options is used for simulating a die roll?",
        {
            1: "random.random(1,6)",
            2: "random.randint(1,6)",
            3: "random.randrange(1,6)",
            4: "random.choice(1,6)"
        },
        "2"
    ],
]
random.shuffle(quiz)
for question in quiz:
    print(question[0]) #prints the question
    for j in question[1]:
        print(str(j)+": "+question[1][j])#prints the answer choices
    if input()==question[2]:#if correct, add on eto the score
        print("Correct!")
        correct+=1
    else:
        print("Incorrect...")

print( " you scored " + str(correct) +"/" + str(len(quiz)))#prints the results
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?
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!
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.
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
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
Correct!
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? (this question has 2 correct answers, input anser with one comma, ascending, and no spaces)
1: The simulation will not contain any bias that favors one body type over another, while an experiment will be biased
2: The simulation can be run more safely than an actual experiment
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
Incorrect...
What is often used to create variablility in simulations?
1: Telling the user to roll dice
2: Using prestored value in the system to roll code
3: Using a Random Number Generator
4: Basing results off what other has said
Correct!
Which of the following options is used for simulating a die roll?
1: random.random(1,6)
2: random.randint(1,6)
3: random.randrange(1,6)
4: random.choice(1,6)
Correct!
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?
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
4: A baseball field that is textured to differentiate between the grass and the dirt
Correct!
 you scored 5/6

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

Create your own simulation based on your experiences/knowledge! Be creative! Think about instances in your own life, science, puzzles that can be made into simulations

Some ideas to get your brain running: A simulation that breeds two plants and tells you phenotypes of offspring, an adventure simulation...

# a disaster will come when a random variable is under a constant in certain number of rounds, wiping out all the recessive allele in a population
# individuals will mate at a set chance with another individual
# at end of the rounds, announce the number of genes
import random

def mate(a,b): #Function to simulate the mating of an individual with another
    i=a[random.randint(0,1)]
    j=b[random.randint(0,1)]
    if i>=j:
        return j+i
    else:
        return i+j

def count(population):
    AA=0
    Aa=0
    aa=0
    for indi in population:
        if indi == "AA":
            AA+=1
        if indi == "Aa":
            Aa+=1
        if indi == "aa":
            aa+=1
    print("AA: "+str(AA)+" Aa: "+str(Aa)+" aa: "+str(aa))

DISASTER=0.10# Declare the constants
MATE=0.10
ROUNDS=20
POP=100
population=[["A","a"][random.randint(0,1)]+["A","a"][random.randint(0,1)] for i in range(POP)]#Generate the population
for i in range(ROUNDS):
    if random.random()<DISASTER: # When disaster event occurs, wipe out all that has the recessive trait
        i=0
        kill=0
        while i<len(population):
            if population[i] == "aa":
                population.pop(i)
                kill+=1
            else:
                i+=1
        print("A disaster occured, killing",kill,"individuals.")
    child=[]
    for indi in population: # For each of individual, if a value under mate, they mate with another individual
        if random.random()<MATE:
            child.append(mate(indi,population[random.randint(0,len(population)-1)]))
    population+=child
    count(population)
AA: 30 Aa: 34 aa: 23
AA: 31 Aa: 44 aa: 28
A disaster occured, killing 28 individuals.
AA: 35 Aa: 48 aa: 1
AA: 38 Aa: 53 aa: 2
AA: 45 Aa: 57 aa: 2
AA: 50 Aa: 61 aa: 3
AA: 59 Aa: 64 aa: 6
AA: 74 Aa: 68 aa: 8
AA: 86 Aa: 72 aa: 8
AA: 98 Aa: 80 aa: 9
AA: 109 Aa: 90 aa: 11
AA: 120 Aa: 100 aa: 12
AA: 134 Aa: 105 aa: 12
AA: 153 Aa: 111 aa: 15
AA: 164 Aa: 124 aa: 18
AA: 187 Aa: 136 aa: 24
AA: 202 Aa: 154 aa: 27
AA: 218 Aa: 175 aa: 33
AA: 240 Aa: 196 aa: 36
AA: 273 Aa: 219 aa: 39