Hack #1 - Class Notes

  • What are simulations?
    • Simulations are abstractions that mimic more complex objects or phenomena from the real world
    • They can use a mathematical description or model of a real thing in the form of a computer program
  • What are the purposes/uses of simulations?
    • Purposes include drawing inferences without the constraints of the real world
      • Essentially, they allow us to study systems or other things that cannot be easily or safely done so in real life
  • Simulations use varying sets of values to reflect the changing state of a real phenomenon
  • When developing a simulation, it is often necessary to remove specific details or simplify aspects, for simulations can often contain bias based on which details or real-world elements were included/excluded
  • Simulations allow the formulation of hypotheses or theories under consideration
  • The variability, randomness, and overall complex nature of the role is considered in using random number generators
  • Examples of well-known simulations include rolling dice, spinners, molecular models, and analysis of chemicals/reactions

Hack #2 - Functions Classwork

Below is my work that uses the randomization functions:

import random # imports the random library
x = random.randint(1,100) # x is a random integer between 1 and 100 and a number within this range will be printed out
print(x) # this prints out the random number chosen using the random functions that we can now used because of the import random at the top
37

I also allowed an option for user input so that the user can choose any random number between 1 and 100:

while True: 
    # prompts for a number between 1 and 100
    x = int(input('Please enter any number between 1 and 100:'))

    # if the user types in a valid input, the number chosen will be printed
    if x>=1 and x<=100:
        print("Number chosen: ",x)
        break
    # If the user tries to input something that is not in the acceptable range, they will get this error and will be able to try again
    else:
        print("Invalid input. Please make sure the number is between 1 and 100:")
        print("Attempted input: ",x)
Invalid input. Please make sure the number is between 1 and 100:
Attempted input:  493
Number chosen:  44

Below is the code I did to make an unfair coin (2/3 chance of heads, 1/3 chance of tails)

import random

def coinflip():         #def function 
    randomflip = random.randint(0, 2) #range is from 0 to 2
    if randomflip == 0 or randomflip == 1: #if the random number is 0 or 1, "Heads" will be printed (2/3 chance)
        print("Heads")
    else:
             # if the random number is 2, "Tails" will be printed (1/3 chance)
            print("Tails")

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

Here is my closet code that removes or adds a random item to the list of things:

def myCloset():
    myclothes = ["red shoes", "green pants", "tie", "belt"]
    
    while True:
        choice = input("Welcome to your closet! Do you want to add an item, remove an item, or quit? ") # prompts the user with a choice between adding or removing something from their closet or simply quitting
        if choice == "add": # if the user wants to add something, they will be prompted to include the name of the item they want to add
            new_item = input("Enter the name of the item you want to add: ")
            print(" {} has been added to your closet!".format(new_item))
            myclothes.append(new_item) # the item inputted by the user will then be added to the list as an item in myclothes
        elif choice == "remove": # if the user chooses "remove", they will be asked to name the item they want to remove 
            item_to_remove = input("Enter the name of the item you want to remove: ")
            print(" {} has been removed from your closet!".format(item_to_remove))
            myclothes.remove(item_to_remove)
        elif choice == "quit": # if the user chooses to quit, the code will exit and the final list myclothes will be returned
            print("You chose to quit. You may always come back later to your closet to add or remove stuff!")
            break

        else:
            print("Invalid action. Please choose 'add', 'remove', or 'quit'.") # if user tries to input something other than add, remove, or quit, they will be prompted with this message
    return myclothes

print(myCloset())
 black pants has been added to your closet!
 red shorts has been added to your closet!
 blue shoes has been added to your closet!
 green pants has been removed from your closet!
 belt has been removed from your closet!
You chose to quit. You may always come back later to your closet to add or remove stuff!
['red shoes', 'tie', 'black pants', 'red shorts', 'blue shoes']

Hack #3 - Binary Simulation Problem

import random

def randomnum():
    return random.randint(0, 255) # generate a random number between 0 and 255

def converttobin(n):
    return bin(n)[2:] # convert the number to binary and return the string, with the "0b" prefix removed

def survivors(binary):
    people = ["Emaad", "Eyaad", "Zeyaan", "Emaan" , "Azaan", "Messi", "Josh Allen", "Karen"]
    survivors = []
    zombies = []
    for i in range(len(binary)):
        if binary[i] == "1": # if the character is "1", then that person is a survivor
            survivors.append(people[i]) # this person is added to the survivors list
        else: # otherwise, the person has turned into a zombie
            zombies.append(people[i]) # this person will be added to the zombies list
    return survivors, zombies

# generates a random number
n = randomnum()

# converts the number to binary
binary = converttobin(n)

# determines the survivors and zombies
survivors, zombies = survivors(binary)

# print the result
print("Survivors:") # prints list of survivors
for survivor in survivors:
    print(survivor)

print("Zombies:") # prints list of zombies
for zombie in zombies:
    print(zombie)
Survivors:
Emaad
Eyaad
Emaan
Karen
Zombies:
Zeyaan
Azaan
Messi
Josh Allen

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 roll():
    return random.randint(1, 20) # generates a random number between 1 and 20, stimulates a 20 sided dice

# this rolls the dice ten times
for i in range(10):
    result = roll()
    print("You rolled a(n) {}".format(result))
You rolled a(n) 8
You rolled a(n) 1
You rolled a(n) 1
You rolled a(n) 6
You rolled a(n) 3
You rolled a(n) 5
You rolled a(n) 1
You rolled a(n) 3
You rolled a(n) 19
You rolled a(n) 8

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
import random

def question_and_answer(prompt):
    print("Question:" +prompt)
    msg = input("Question:" +prompt)
    print("Answer:" +msg)
## defines the format of how the question will be asked
def question_with_response(prompt):
    print("Question: " + prompt)
    msg = input("Question: " + prompt)
    return msg

questions_list = ["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. \n(1) The simulation is an abstraction and therefore cannot contain any bias\n (2) The simulation may accidentally contain bias due to the exclusion of details\n (3) If the simulation is found to contain bias, then it is not possible to remove the bias from the simulation\n (4) 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 (1) No, it's not a simulation because it does not include a visualization of the results.\n (2) No, it's not a simulation because it does not include all the details of his life history and the future financial environment\n (3) Yes, it's a simulation because it runs on a computer and includes both user input and computed output.\n (4) 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?\n (1) Realistic sound effects based on the material of the baseball bat and the velocity of the hit\n (2) A depiction of an audience in the stands with lifelike behavior in response to hit accuracy\n (3) Accurate accounting for the effects of wind conditions on the movement of the ball\n (4) 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?\n (1) The simulation will not contain any bias that favors one body type over another, while an experiment will be biased\n (2) The simulation can be run more safely than an actual experiment\n (3) The simulation will accurately predict the parachute's safety level, while an experiment may be inaccurate due to faulty experimental design\n (4) 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",
    "What command is used to include other functions that were previously developed?\n (1) os\n (2) import\n (3) random\n (4) append",
    "How are simulations useful to us?\n (1) They allow us to study things that cannot be easily studied in real life\n (2) They give us a good model of what would happen if a certain thing were to occur\n (3) 1 and 2 are correct\n (4) Simulations can't be considered useful since they are not actually related to real life"
            ]       

answers_list = [
    "2",
    "3",
    "3",
    "2",
    "2",
    "3"
]

questions = len(questions_list)
correct = 0

for i in range(len(questions_list)):
        user_response = question_with_response(questions_list[i])
        if user_response == answers_list[i]:
            print(user_response + " is correct! Yay!")
            correct += 1
## If the answer the user inputted doesn't match any of the answers on the list (again depending on question), they will get a message saying they are wrong.
        else:
            print(user_response + " is incorrect! Sorry!")

## After completing the quiz, the user will get their score out of 6 and the percentage
print("You scored " + str(correct) +"/" + str(questions) + ", which is " + str((correct / questions) * 100) + "%")
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. 
(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 is correct! Yay!
Question: 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.
3 is correct! Yay!
Question: 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 is correct! Yay!
Question: 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?
 (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't test the parachute design in a wide range of environmental conditions that may be difficult to reliably reproduce in an experiment
2 is correct! Yay!
Question: What command is used to include other functions that were previously developed?
 (1) os
 (2) import
 (3) random
 (4) append
1 is incorrect! Sorry!
Question: How are simulations useful to us?
 (1) They allow us to study things that cannot be easily studied in real life
 (2) They give us a good model of what would happen if a certain thing were to occur
 (3) 1 and 2 are correct
 (4) Simulations can't be considered useful since they are not actually related to real life
3 is correct! Yay!
You scored 5/6, which is 83.33333333333334%

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

For this hack, I chose to write code that allows a user to input two colors and shows them what color they make when mixed.

def mix_colors(color1, color2):
    # define a dictionary that shows mixtures of two colors and their resulting color
    color_mixtures = {
        ("red", "white"): "pink",
        ("red", "blue"): "purple",
        ("black", "white"): "gray",
        ("red", "green"): "yellow",
        ("red", "yellow"): "orange",
        ("magenta", "yellow"): "red"
    }

    # this makes it so that the inputs are not case sensitive 

    color1 = color1.lower()
    color2 = color2.lower()

    # check if the color pair exists in the dictionary
    if (color1, color2) in color_mixtures:
        return color_mixtures[(color1, color2)] # return the resulting color

        # this makes it so that the order in which the user enters the colors does not matter
    elif (color2, color1) in color_mixtures:
        return color_mixtures[(color2, color1)] # return the resulting color
    else:
        return "unknown" # if the color pair inputted by the user is not found in the dictionary, return "unknown"

# accept user input for the two colors
color1 = input("Enter the first color: ")
print("Color entered: ",color1)
color2 = input("Enter the second color: ")
print("Color entered: ",color2)

# mixes the colors and prints the result
result = mix_colors(color1, color2)
print("When mixed, {} and {} make {}".format(color1,color2,result))
Color entered:  red
Color entered:  white
When mixed, red and white make pink

I also made a version of this code in which it randomly selects a color pair from the dictionary and tells us what colors the pair make when mixed:

import random

# dictionary that shows results of various color mixtures
color_mixtures = {
    "red, white": "pink",
    "red, blue": "purple",
    "black, white": "gray",
    "red, green": "yellow",
    "red, yellow": "orange",
    "magenta, yellow": "red"
}

# chooses a random color mixture from the dictionary above
color_mixture = random.choice(list(color_mixtures.keys()))

# Split the color pair string on the comma character
colors = color_mixture.split(",")

# Join the resulting list of colors with "and" 
colors_str = " and ".join(colors)

# Uses the dictionary above to determine the resulting color when the two colors are mixed
resulting_color = color_mixtures[color_mixture]

# Prints the two colors and the result when mixed
print("When mixed, {} make {}".format(colors_str, resulting_color))
When mixed, black and  white make gray