Hack #1 - Class Notes

Basics / extra notes from lesson

  • Simulations are abstractions that mimic more compelx objects or phenomena from the real world
  • it is necessart to remove specific details (example, the temperature of the sun on a certain day)
  • simulations allow the formulation of hypothesis under consideration
  • examples: rolling dice, spinners, molecular models, analyze chemical/reactions
  • We can use the python random module to run various simulations in our programs. For instance, random number generators could be used to simulate different probabilities and such
  • more examples include missle launchers and chemical reactions

This is copied from their fastpages about some basic commands often needed when creating 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(mylist) # 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.
from random import *
x = randint(1, 100) 
print(x)
80
def mycloset():
    myclothes = ["red shoes", "green pants", "tie", "belt"]

MC answer: 3

Hack #2 - Functions Classwork

import random

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

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

Hack #3 - Binary Simulation Problem

from random import randint

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

def converttobin(n): # function for converting decimal to binary
    x = n
    N = 7
    res = []
    while N >= 0:
        if (x - 2 ** N) >= 0:
            res.append(1)
            x-=2 ** N
            N-=1
        else:
            res.append(0)
            N-=1
    return res

def survivors(): # function to assign position
    survivorstatus = ["Jiya", "Shruthi", "Noor", "Ananya" , "Peter Parker", "Andrew Garfield", "Tom Holland", "Tobey Maguire"]
    chances = converttobin(randomnum())
    return [survivorstatus[i] for i in range(8) if chances[i] == 1]

def printsurvivors(survivors):
    print("These people survived: ")
    for i in survivors:
        print(format(i))

    # replace the names above with your choice of people in the house

survivor_list = survivors()
printsurvivors(survivor_list)
These people survived: 
Ananya
Tom Holland

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 # you can run this code multiple times with different outputs each time
repeat = True
while repeat:
    print("You rolled",random.randint(1,6))
    print("Want to roll again? Y/N")
    repeat = "Y" in input()
You rolled 3
Want to roll again? Y/N

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. YOUR OWN QUESTION; can be situational, pseudo code based, or vocab/concept based
  6. YOUR OWN QUESTION; can be situational, pseudo code based, or vocab/concept based
questions = 6
correct = 0


question = {
    "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) The simulation is an abstraction and therefore cannot contain any bias b) The simulation may accidentally contain bias due to the exclusion of details c) If the simulation is found to contain bias, then it is not possible to remove the bias from the simulation d) The only way for the simulation to be biased is if the researcher intentionally used data that favored their desired output": "b",
    "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.": "c",
    "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": "c",
    "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 can be run more safely than an actual experiment 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't test the parachute design in a wide range of environmental conditions that may be difficult to reliably reproduce in an experiment": "b",
    "Which of the following ways can we best simulate a random dice roll? a) Simulation b) Loops c) Strings d) Nested Conditionals": "a",
    "What module in python could be used to generate random values in simulations?, a) Random b) False c) Tensorflow d) Turtle": "a",
}

def qna(question, answer):
    answer = input(question + ' :pick a, b, c, or d')
    if answer == answer:
        print('Good job, you are correct')
        return 1
    else:
        print('Better luck next time, you are wrong')
        return 0

for i in question:
    y = qna(i, question[i])
    correct = correct + y

print("You scored " + str(correct) +"/" + str(questions) + ", which is " + str((correct / questions) * 100) + "%")
Good job, you are correct
Good job, you are correct
Good job, you are correct
Good job, you are correct
Good job, you are correct
Good job, you are correct
You scored 6/6, which is 100.0%

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...

from random import randint
 
# Function which generates a new random number everytime it executes
def generator():
    return randint(1, 10)
     
# Function takes user input and returns
def rand_guess():
    # calls generator() which returns random integer between 1 and 10
    random_number = generator()
    # defining the number of guesses the user gets
    guess_left = 3
    # Setting a flag variable
    flag = 0
    # looping the number of times the user gets chances
    while guess_left > 0:
        # Taking a input from the user
        guess = int(input("Pick your number to "
                      "enter the lucky draw\n"))
        # checking whether user's gues matches the win-condition
        if guess == random_number:
            # setting flag as 1 if user guesses correctly and then loop is broken
            flag = 1
            break
        else:
            # if user's choice doesn't match win-condition then it is printed
            print("Wrong Guess!!")
        guess_left -= 1
    if flag is 1:
        return True
    else:
        return False

if __name__ == '__main__': # driver code
    if rand_guess() is True:
        print("Congrats!! You Win.")
    else :
        print("Sorry, You Lost!")
<>:29: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:29: SyntaxWarning: "is" with a literal. Did you mean "=="?
/tmp/ipykernel_436/2394116528.py:29: SyntaxWarning: "is" with a literal. Did you mean "=="?
  if flag is 1:
Wrong Guess!!
Wrong Guess!!
Wrong Guess!!
Sorry, You Lost!