Lessons 12, 13, 14, 15, and 16
Assignments and Vocab for lessons 12, 13, 14, 15, and 16 (For graders, 3.12/3.13 are on the top, 3.14/3.15 is near the middle, 3.16 is further down, 3.17/3.18 is at the end)
Unit 3 Sections 12-13
Homework/Hacks: For the hw, you have two options. The first hack is for a 0.7 + extra work for the full 1. Simply create your own procedure with your own creativity. Since there is a lot of leeway for this one, you must do a LOT additional work to get a 1. For the other option, below is the start to a character to binary convertor. This is just a template, but the goal is to translate "APCSP" into binary. The only contraint is that you must use a procedure. If this is completed along with extra work, you can get a 1.
def letter_to_binary(letter: str) -> str:
# Convert the letter to ASCII code
ascii_code = ord(letter)
# Convert the ASCII code to binary
binary = bin(ascii_code)
# Return the binary representation
return binary
# Test the function
print(letter_to_binary("F")) # Should print '0b1000001'
print(letter_to_binary("B")) # Should print '0b1000010'
print(letter_to_binary("C")) # Should print '0b1000011'
import datetime
import random
#user input
day = input("Enter a day (MM/DD/YYYY): ")
#turn user input to datetime form
user_day = datetime.datetime.strptime(day, '%m/%d/%Y')
#gen rand year
random_year = random.randint(1, 366)
random_day = datetime.datetime.strptime(str(random_year), '%j')
#calc dis
distance = abs(user_day - random_day).days
print(f"The distance in days between {user_day.strftime('%m/%d/%Y')} and {random_day.strftime('%m/%d/%Y')} is {distance} days.")
import random
x = random.randint (1,100)
input ("Try to guess the number")
y = input
if y==x:
print ("The number was" + x)
elif y<x:
print ("You didnt guess the number, the number was " + x + "... You guessed " + y)
elif y>x:
print ("You didnt guess the number, the number was " + x + "... You guessed " + y)
# insert your work with randomization/ functions and the mycloset code here # Hint: Use the functions we talked about in the beginning!
import random
def coinflip(): #def function
randomflip = random.randint(0, 1) #picks either 0 or 1 randomly (50/50 chance of either)
if randomflip == 0: #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()
import random
def randomnum(): # function for generating random int
random.randint(1,8)
def converttobin(n): # function for converting decimal to binary
binary = bin(n)
def survivors(binary): # function to assign position
survivorstatus = ["Archie", "Cookie", "Daisy", "Ollie" , "Orlando", "Colin", "Max", "Andrew"]
# replace the names above with your choice of people in the house
import random
def roll_dice():
# Generate a random number between 1 and 6 (inclusive)
roll = random.randint(1, 6)
return roll
# Roll the dice multiple times
trials = 10
for i in range(trials):
result = roll_dice()
print(f"Trial {i+1}: {result}")
import random
# Define a list of questions and a list of answer options for each question
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.",
"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?",
"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?",
"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?"
]
answers = [
["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."],
["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."],
["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"],
["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."]
]
# Correct answers
correct_answers = [2, 3, 3, 3]
# User Score
score = 0
# Shuffle q&a
random.shuffle(questions)
random.shuffle(answers)
# Ask question
for i, question in enumerate(questions):
print(f"Question {i+1}:")
print(question)
print()
for j, answer in
import random
names = ["Player A", "Player B", "Player C", "Player D", "Player E", "Player E"]
picked_name = random.choice(names)
print(f"The name picked from the hat is {picked_name}")
import datetime
import random
random_year = random.randint(1, 366)
random_day = datetime.datetime.strptime(str(random_year), '%j')
print({random_day.strftime('%m/%d/%Y')})
import math
# Read input from the user
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
# Round the numbers up and down
num1_rounded_up = math.ceil(num1)
num1_rounded_down = math.floor(num1)
num2_rounded_up = math.ceil(num2)
num2_rounded_down = math.floor(num2)
# Find the least common multiple of the rounded down numbers
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
lcm_rounded_down = lcm(num1_rounded_down, num2_rounded_down)
# Find the greatest common multiple of the rounded up numbers
def gcm(a, b):
return abs(a*b) // math.gcd(a, b)
gcm_rounded_up = gcm(num1_rounded_up, num2_rounded_up)
# Calculate the factorial of each number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
num1_factorial = factorial(num1)
num2_factorial = factorial(num2)
# Print the results
print("Rounded up:", num1_rounded_up, num2_rounded_up)
print("Rounded down:", num1_rounded_down, num2_rounded_down)
print("Least common multiple of rounded down numbers:", lcm_rounded_down)
print("Greatest common multiple of rounded up numbers:", gcm_rounded_up)
print("Factorials:", num1_factorial, num2_factorial)
Vocab
- Problem: a general description of a task that can or cannot be solved algorithmically
- Decision Problem: A problem with a yes or no answer
- Organization Problem: a problem with a goal of finding the best answer
- Instance: a problem with a specific input
- Efficiency: amount of computing needed to solve a problem
- Polynomial Efficiency (Good): more work takes a proportional amount of time (1 job is +2 time)
- Exponential Efficiency (Bad): more work takes an exponential amount more time (1 job is 2x time)
- Heuristic Approach: When optimal solutions are inefficient, look for a possibly optimal solution that is more efficient
- Decidable Problem: A decision problem that has a clear solution that will always make a correct output
- Undecidable Problem: A decision problem with no solution that is not guaranteed to produce the correct output
import time
numlist = [1,3,5,7,9,11,13,15,17,19]
valuelist = [0,3,6,9,12,15,18,21]
def isvalue(value,array):
#--------------------
exists = False
min = 0
tmax = 0
max = int(len(numlist) - 1)
while (max - min) > 1:
if numlist[max] > value:
tmax = max
max = int((min + max) / 2)
if max % 1 != 0:
max += .5
else:
min = max
max = tmax
for R in range (int(min), int(tmax)):
if numlist[R] == value:
exists = "True"
return(exists)
#--------------------
starttime = time.time()
for i in range(100000):
for i in range(len(valuelist)):
x = isvalue(valuelist[i],numlist)
endtime = time.time()
print(endtime-starttime,'seconds')
Homework
Make an algorithm that finds the fastest route that hits every location once starting and ending at Del Norte. Make sure to show your thinking. If you are strugling, try using a huristic approach. Remember, what matters more than having perfectly functioning code is that you tried your hardest.
dataset = {
'DelNorte':{
'Westview':15,
'MtCarmel':20,
'Poway':35,
'RanchoBernrdo':50
},
'Westview':{
'Del Norte':15,
'MtCarmel':35,
'Poway':25,
'RanchoBernrdo': 45
},
'MtCarmel':{
'Westview':35,
'Del Norte':20,
'Poway':40,
'RanchoBernrdo':30
},
'Poway':{
'Westview':25,
'MtCarmel':40,
'Del Norte':35,
'RanchoBernrdo':15
},
'RanchoBernardo':{
'Westview':45,
'MtCarmel':30,
'Poway':15,
'Del Norte':50
}
}
from itertools import permutations
def get_travel_time(route, times):
total_time = 0
for i in range(len(route) - 1):
total_time += times[route[i]][route[i+1]]
return total_time
def find_fastest_route(times):
locations = list(range(5))
routes = permutations(locations)
# Find the fastest route
fastest_time = float('inf')
fastest_route = None
for route in routes:
time = get_travel_time(route, times)
if time < fastest_time:
fastest_time = time
fastest_route = route
return fastest_route
times = [[0, 3, 6, 7, 8],
[3, 0, 4, 5, 6],
[6, 4, 0, 1, 2],
[7, 5, 1, 0, 3],
[8, 6, 2, 3, 0]]
fastest_route = find_fastest_route(times)
print(fastest_route)