Hack #1 - Class Notes

  • Simulations
  • Abstractions that mimic more complex objects or phenomena from the real word, able to draw inferences without constraints of the real world
  • Use varying sets of values to reflect the changing state of a real phenomnom
  • Remove specific details an simplify aspects, contain bias based on what is included or excluded
  • Formulation of hypothese un der consideration
  • Variability and randomess with random number generators
  • Ex: rolling dice, spinner, molecular models, analyze chmicals/reactions

Random: import random

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

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

Answer: #3 - An abstraction redefinesor simplifies something, which is what 3 talks about

Hack #2 - Functions Classwork

import random
x = random.randint(1,100)
print(x)
54
import random
def mycloset():
    myclothes = ["red shoes", "green pants", "tie", "belt"]
    x = random.choice(myclothes)
    ans = input("Would you like to keep your " + x + "? : (y/n)")
    if ans == "n":
        myclothes.remove(x)
        print(myclothes)
    else: 
        print(myclothes)
mycloset()
['red shoes', 'green pants', 'tie', 'belt']
import random

def coinflip():         #def function 
    randomflip = random.randint(0, 2) #picks either 0 or 1 randomly (50/50 chance of either) 
    if randomflip == 0 or randomflip == 2: #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
Heads
Tails
Heads
Heads

Explanation: Here, I changed the range of the random.randint() function. I also changed it so that if this outcome is 0 or 2 it is heads. Since there are 3 possible outcomes of this function, 0 or 1 or 2, and 2/3 of those options are heads, the coin flip is now unequal. 2/3 chance for heads, and 1/3 chance for tails.

Hack #3 - Binary Simulation Problem

import random

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

x = randomnum()

nums = []
def converttobin(x): # function for converting decimal to binary
    while x/2 != 0:
        rem = x % 2
        nums.append(rem)
        x = int(x/2)
    while len(nums) < 8:
        nums.append(0)
    nums.reverse()
    print(nums)
    return nums
   
def survivors(bin): # function to assign position
    survivorstatus = ["Aliya", "Tanisha", "Sharon", "Claire" , "Allie", "Olivia", "Kayla", "Makayla"]
    survivordict = {}
    i = 0
    for name in survivorstatus:
        if bin[i] == 1:
            survivordict[name] = "Zombie"
        else:
            survivordict[name] = "Human"
        i += 1
    
    for key, val in survivordict.items():
        print(key + " is a " + val)
 
 # Main program
bin = converttobin(x) 
survivors(bin)
143
[1, 0, 0, 0, 1, 1, 1, 1]
Aliya is a Zombie
Tanisha is a Human
Sharon is a Human
Claire is a Human
Allie is a Zombie
Olivia is a Zombie
Kayla is a Zombie
Makayla 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
  • Extra: Roll a random number of times, and function to see which number is the most frequently rolled
import random

def diceroll(n):
    results = {}
    i = 0
    while i < n:
        num = random.randint(1,6)
        results[i] = num
        i += 1
    return results, values

n = random.randint(5,10) 
print("roll " + str(n) + " times")
mydices = diceroll(n)[0]
values = []

i = 0
while i < n:
    print("roll #" + str(i+1) + " is " + str(mydices[i]))
    values.append(mydices[i])
    i+=1

values = diceroll(n)[1]
print(values)
def frequent(values):
    counter = 0
    num = values[0]
    for i in values:
        curr_frequency = values.count(i)
        if (curr_frequency > counter):
            counter = curr_frequency
            num = i
    return num, curr_frequency

print("You rolled the side " + str(frequent(values)[0]) + " most frequently, " + str(frequent(values)[1]) + " times.")
roll 7 times
roll #1 is 4
roll #2 is 6
roll #3 is 1
roll #4 is 6
roll #5 is 1
roll #6 is 4
roll #7 is 6
[4, 6, 1, 6, 1, 4, 6]
You rolled the side 6 most frequently, 3 times.

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 #used to randomize the questions

q1={"q": "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.\na) 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.",
"answer" : "b"}
q2 = {"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?\na) 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.",
"answer": "d"}

q3 = {"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?\na) 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", 
"answer":"c"}

q4 = {"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?\na) The simulation will not contain any bias that favors one body type over another, while an experiment will be biased.\nb)The simulation can be run more safely than an actual experiment\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.",
"answer": "d"}

q5 = {"q": "What does random.random() do?\na)generate a random float between 0.0 to 1\nb)randomly selects an integer from given range\nc)returns random value from list\nd)returns a randomly selected element from the specified sequence", "answer":"a"}
q6 = {"q": "What does random.choice() do?\nareturns a randomly selected element from the specified sequence\nb)returns random value from list\nc)randomly selects an integer from given range\nd)generate a random float between 0.0 to 1", "answer":"a"}

questions = [q1, q2, q3, q4, q5, q6]
 
#main program 
# loop the quiz
n = 4    # generate a randome number of questions to ask
total_qnum = len(questions)

i = 0 # loop index
correct = 0
questionAsked=[]
while i < n:
   
   qindex = random.randint(0,total_qnum-1)
   
   if qindex in questionAsked:  # questions has already been asked
       #print("This question has been asked")
      continue
   print("\n------Question # "+str(i+1)+"-------\n")       
   questionAsked.append(qindex)
   
   print(questions[qindex]["q"])
   youranswer=input("Please choose: a, b, c or d\n").lower()
   
   if youranswer == questions[qindex]["answer"]:
      correct +=1
      print("\nGood job! Answer "+str(youranswer)+" is correct\n")
   else:
      print("\nSorry! Answer "+str(youranswer)+" is NOT correct\n")
   i+=1

print( "You scored " + str(correct) +" out of " + str(n) +" questions")
------Question # 1-------

What does random.random() do?
a)generate a random float between 0.0 to 1
b)randomly selects an integer from given range
c)returns random value from list
d)returns a randomly selected element from the specified sequence

Sorry! Answer b is NOT correct


------Question # 2-------

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 test the parachute design in a wide range of environmental conditions that may be difficult to reliably reproduce in an experiment.

Good job! Answer d is correct


------Question # 3-------

What does random.choice() do?
areturns a randomly selected element from the specified sequence
b)returns random value from list
c)randomly selects an integer from given range
d)generate a random float between 0.0 to 1

Sorry! Answer d is NOT correct


------Question # 4-------

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! Answer d is correct

You scored 2 out of 4 questions

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

import random
my_num = random.randint(0,255)
win_num = random.randint(0,255)

def convert(x):
    nums = []
    while x/2 != 0:
        rem = x % 2
        nums.append(rem)
        x = int(x/2)
    while len(nums) < 8:
        nums.append(0)
    nums.reverse()
    binary = ""
    for i in nums:
        binary = binary + str(i)
    return binary

my_bin = convert(my_num)
win_bin = convert(win_num)

print(str(my_num) + " - your lottery ticket number is: " + my_bin)
print(str(win_num) + " - the winning ticket number is: " + win_bin)

same = 0
pos = 0
for x in my_bin:
    if x == win_bin[pos]:
        same += 1
    pos += 1
print("You had " + str(same) + " of the same numbers with the winning number, you get " + str(same*100) + " dollars.")
17 - your lottery ticket number is: 00010001
125 - the winning ticket number is: 01111101
You had 4 of the same numbers with the winning number, you get 400 dollars.