Unit 3.9/3.11 Hacks
3 Components of an algorithm: Selection, Sequence, Iteration
pizzaPrice = 10
money = 9
if pizzaPrice < money:
print("great! i have more than enough money")
elif pizzaPrice > money:
print("oh no! i don't have enough money")
else:
print("phew! i have just enough money")
## TO ##
money = 11
hasEnough = pizzaPrice < money
hasNotEnough = not hasEnough
if hasEnough:
print("great! i have more than enough money")
elif hasNotEnough:
print("oh no! i don't have enough money")
else:
print("phew! i have just enough money")
3.9.2
Algorithm: make a PB & J sandwich
- If hungry, make a sandwich
- Find bread. If there is, go to step 4.
- If there is no bread, buy bread. Return to step 2.
- Find PB & J. If there is, go to step 6.
- If there is no PB & J, go to buy PB & J. Return to step 4.
- Make sandwich with PB & J and bread.
- Eat sandwich. No longer hungry. Return to step 1.
hungry = True
bread = True
pbj = False
def buy_bread():
global bread
bread = True
print("bought bread")
def buy_pbj():
global pbj
pbj = True
print("bought pbj")
def make_sandwich():
global hungry
hungry = False
print("yum")
while hungry:
if bread:
if pbj:
make_sandwich()
else:
buy_pbj()
else:
buy_bread()
import random
#sets variables for the game
num_guesses = 0
user_guess = 0
upper_bound = 100
lower_bound = 0
#generates a random number
number = random.randint(1,100)
# print(number) #for testing purposes
print(f"I'm thinking of a number between 1 and 100.")
#Write a function that gets a guess from the user using input()
def guess():
num = input("Guess a number! ")
return int(num)
#Change the print statements to give feedback on whether the player guessed too high or too low
def search(number, guess):
global lower_bound, upper_bound
if guess < number:
print("Nice try! too low") #change this
lower_bound = guess
elif guess > number:
print("Nice try! too high") #change this
upper_bound = guess
return lower_bound, upper_bound
while user_guess != number:
user_guess = guess()
num_guesses += 1
print(f"You guessed {user_guess}.")
lower_bound, upper_bound = search(number, user_guess)
print(f"Guess a number between {lower_bound} and {upper_bound}.")
print(f"You guessed the number in {num_guesses} guesses!")
import math
def binary_search1(xs, x, start, end):
if start > end: return -1
mid = math.floor((start + end) / 2)
if xs[mid] == x:
print("x =", x)
return mid
if xs[mid] > x:
print("x <", xs[mid])
return binary_search1(xs, x, start, mid-1)
if xs[mid] < x:
print("x >", xs[mid])
return binary_search1(xs, x, mid+1, end)
def binary_search(xs, x):
return binary_search1(xs, x, 0, len(xs) - 1)
arr1 = [12, 14, 43, 57, 79, 80, 99]
arr2 = [92, 43, 74, 66, 30, 12, 1]
arr3 = [7, 13, 96, 111, 33, 84, 60]
arr2.sort()
arr3.sort()
for (arr, needle) in zip([arr1, arr2, arr3], [14, 12, 84]):
print("constructing binary search tree:", arr, "searching for", needle)
print("found {} at idx {}\n".format(needle, binary_search(arr, needle)))