Unit 3 Lesson 16, Student Copy
Hack #1 - Class Notes
Write any extra notes you have here
-
Simulations: Abstractions that mimic things that occur in the real world, you can use simulations to calculate things that you can't test in the real world
May contain bias because some real world elements can not be factored in
Use random number generators to simulate randomness and variability. Applications: Rolling a dice, flipping a coin, spinners
Contains varying set of values to demonstrate the variableness of real world phenomenon
Some details may need to be simplified within a simulation
-
Random number generator: You can use the random library:
import random
import random
x = random.randint(1, 100)
print(x)
def mycloset():
myclothes = ["red shoes", "green pants", "tie", "belt"]
trash = random.choice(myclothes)
print("Throwing away " + trash)
myclothes.remove(trash)
print("My clothes: " + str(myclothes))
mycloset()
def mycloset():
myclothes = ["red shoes", "green pants", "tie", "belt"]
extraclothes = ["white socks", "polka dot socks"]
choice = input("Add or remove clothes? ")
print("Add or remove clothes? ")
print(choice)
if choice == "add":
addItem = random.choice(extraclothes)
print("Adding item " + addItem + "...")
myclothes.append(addItem)
print("My clothes: " + str(myclothes))
if choice == "remove":
trash = random.choice(myclothes)
print("Throwing away " + trash)
myclothes.remove(trash)
print("My clothes: " + str(myclothes))
mycloset()
import random
def coinflip(): #def function
randomflip = random.randint(0, 2) #picks either 0 or 2 randomly (50/50 chance of either)
if randomflip == 0 or randomflip == 1: #assigning 0 and 1 to be heads--> if 0 or 1 is chosen then it will print, "Heads"
print("Heads")
else:
if randomflip == 2: #assigning 2 to be tails--> if 2 is chosen then it will print, "Tails"
print("Tails")
#Tossing the coin 5 times:
t1 = coinflip()
t2 = coinflip()
t3 = coinflip()
t4 = coinflip()
t5 = coinflip()
import random
def randomnum(): # function for generating random int
ranNum = random.randint(0, 255)
return ranNum
def converttobin(n): # function for converting decimal to binary
numOfBinary = 8
binary = [];
output = ""
for i in range(numOfBinary):
binary.append((2**(numOfBinary - 1 - i)))
for i in range(len(binary)):
if n - binary[i] >= 0:
n -= binary[i]
output += "1"
else:
output += "0"
return output
def survivors(binary): # function to assign position
survivorstatus = ["Jiya", "Shruthi", "Noor", "Ananya" , "Peter Parker", "Andrew Garfield", "Tom Holland", "Tobey Maguire"]
for i in range(0, len(survivorstatus)):
if binary[i] == "0":
print(survivorstatus[i] + " is a zombie")
else:
print(survivorstatus[i] + " is not a zombie")
# replace the names above with your choice of people in the house
ranNum = randomnum()
binaryNum = converttobin(ranNum)
survivors(binaryNum)
import random
print("Dice roll to see which player goes first (highest number goes first)")
def rollDice():
dice = random.randint(1, 6)
return dice
player1 = rollDice()
player2 = rollDice()
print("Player 1's roll is: " + str(player1))
print("Player 2's roll is: " + str(player2))
if (player1 > player2):
print("Player 1 goes first")
elif player2 > player1:
print("Player 2 goes first")
else:
rollDice()
- 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:
- The simulation is an abstraction and therefore cannot contain any bias
- The simulation may accidentally contain bias due to the exclusion of details.
- If the simulation is found to contain bias, then it is not possible to remove the bias from the simulation.
- The only way for the simulation to be biased is if the researcher intentionally used data that favored their desired output.
- answer options:
- 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
- No, it's not a simulation because it does not include a visualization of the results.
- No, it's not a simulation because it does not include all the details of his life history and the future financial environment.
- Yes, it's a simulation because it runs on a computer and includes both user input and computed output.
- Yes, it's a simulation because it is an abstraction of a real world scenario that enables the drawing of inferences.
- answer options
- 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
- Realistic sound effects based on the material of the baseball bat and the velocity of the hit
- A depiction of an audience in the stands with lifelike behavior in response to hit accuracy
- Accurate accounting for the effects of wind conditions on the movement of the ball
- A baseball field that is textured to differentiate between the grass and the dirt
- answer options
- 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
- The simulation will not contain any bias that favors one body type over another, while an experiment will be biased.
- The simulation can be run more safely than an actual experiment
- The simulation will accurately predict the parachute's safety level, while an experiment may be inaccurate due to faulty experimental design.
- 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
- answer options
- What library can be used when creating a simulation?
- answer
- random
- What code would you use to simulate a coin flip using the random library? (Use 0 and 1 to represent heads/tails)
- answer
- random.randint(0, 1)
import random
questions = [
"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."\
+ "\n1. The simulation is an abstraction and therefore cannot contain any bias" \
+ "\n2. The simulation may accidentally contain bias due to the exclusion of details"\
+ "\n3. If the simulation is found to contain bias, then it is not possible to remove the bias from the simulation"\
+ "\n4. The only way for the simulation to be biased is if the researcher intentionally used data that favored their desired output.",
"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? \n " \
+ "\n1. No, it's not a simulation because it does not include a visualization of the results." \
+ "\n2. No, it's not a simulation because it does not include all the details of his life history and the future financial environment." \
+ "\n3. Yes, it's a simulation because it runs on a computer and includes both user input and computed output."\
+ "\n4. Yes, it's a simulation because it is an abstraction of a real world scenario that enables the drawing of inferences.",
"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?" \
+ "\n1. Realistic sound effects based on the material of the baseball bat and the velocity of the hit" \
+ "\n2. A depiction of an audience in the stands with lifelike behavior in response to hit accuracy" \
+ "\n3. Accurate accounting for the effects of wind conditions on the movement of the ball" \
+ "\n4. A baseball field that is textured to differentiate between the grass and the dirt",
"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?" \
+ "\n1. The simulation will not contain any bias that favors one body type over another, while an experiment will be biased." \
+ "\n2. The simulation can be run more safely than an actual experiment" \
+ "\n3. The simulation will accurately predict the parachute's safety level, while an experiment may be inaccurate due to faulty experimental design." \
+ "\n4. The simulation can test the parachute design in a wide range of environmental conditions that may be difficult to reliably reproduce in an experiment." \
+ "\n* this question has 2 correct answers, answer with a comma and space in between (ex: a, b)",
"What library can be used when creating a simulation?",
"What code would you use to simulate a coin flip using the random library? (Use 0 and 1 to represent heads/tails)"
]
answers = [["2"],
["4"],
["3"],
["2, 4", "4, 2"],
["random"],
["random.randint(0, 1)"]
]
order = random.sample(range(0, len(questions)), len(questions))
for i in range (0, len(questions)):
storage = questions[i]
storageAnswer = answers[i]
questions[i] = questions[order[i]]
answers[i] = answers[order[i]]
questions[order[i]] = storage
answers[order[i]] = storageAnswer
number = 0
score = 0
def questionloop():
for question in questions:
global number
print(question)
usrAnswer = input(question)
print("Enter answer: " + usrAnswer)
answercheck(usrAnswer)
number += 1
print("Your score is: " + str(score) + "/" + str(len(questions)))
if score/len(questions) >= 0.7:
print("Congrats! You passed!")
else:
print("You did not pass. Try again.")
def answercheck(usrAnswer):
for i in range (0, len(answers[number])):
if usrAnswer == answers[number][i]:
print("Correct!")
global score
score += 1
return
print("Incorrect!")
questionloop()
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...
I made a book recommender based on the genre that the person likes. The quiz first asks some questions to identify the person's preferred genre based on the greatest number of answer choices they selected (A corresponds to action, B corresponds to thriller, C corresponds to tragedy, and D corresponds to fantasy).
This is pretty basic right now; but I wanted to create something to solve a problem in my life. I like reading books and sometimes it's hard for me to find a good one so I thought that making a book recommender would be cool.
questions = [
"What do you look for in movies?"\
+ "\n A. Something with a lot of action!! Otherwise it's too boring"\
+ "\n B. Something that keeps me at the edge of my seat"\
+ "\n C. Something sentimental! I love sad stories :3"\
+ "\n D. It must have magic!",
"What do you like most in a book?"\
+ "\n A. A fast paced story. I don't care if there are plot holes. Just give me the action!"\
+ "\n B. Plot twists are a MUST"\
+ "\n C. I LOVE BOOKS WITH A SAD ENDING"\
+ "\n D. Anything mythical! Take me to a land far, far away.",
"What do you hate most about in a book?"\
+ "\n A. Slow stories BORE ME TO DEATH"\
+ "\n B. I can't stand predictable plots"\
+ "\n C. I will cry if everyone gets a happy ending"\
+ "\n D. If the setting is in the modern world",
"Do you have a favorite genre?"
+ "\n A. Dystopian" \
+ "\n B. Thriller" \
+ "\n C. Tragedy" \
+ "\n D. Fantasy"
]
aCounter = 0
bCounter = 0
cCounter = 0
dCounter = 0
for i in range(len(questions)):
print(questions[i])
answer = input(questions[i])
print("Answer: " + answer)
if (answer == "A"):
aCounter += 1
if (answer == "B"):
bCounter += 1
if (answer == "C"):
cCounter += 1
if (answer == "D"):
dCounter += 1
if (aCounter > bCounter and aCounter > cCounter and aCounter > dCounter):
print("Your genre is dystopian")
print("Recommended books: Legend, The Hunger Games")
if (bCounter > aCounter and bCounter > cCounter and bCounter > dCounter):
print("Your genre is thriller")
print("Recommended books: One of us is Lying, Sherlock Holmes")
if (cCounter > aCounter and cCounter > bCounter and cCounter > dCounter):
print("Your genre is tragedy")
print("Recommended books: Salt to the Sea, The Fault in our Stars")
if (dCounter > aCounter and dCounter > bCounter and dCounter > cCounter):
print("Your genre is fantasy")
print("Recommended books: Lord of the Rings, The Hobbit")