Section #2 Solutions

April 19th, 2020

Written by Brahm Capoor, Juliette Woodrow, Parth Sarin, Kara Eng & Tori Qiu

This week in section, your goal is to practice and gain familiarity with the principles of variables and control flow.

Tracing

This program calculates output (y) values for input (x) values along a line with slope a and intercept b. First, it prompts the user for a slope a and intercept term b (remember that a line has an equation of the form y = ax + b). Then, the program prompts the user for x values until the user enters the SENTINEL (the value of which is specified using a named constant). For each entered number, it prints the y value that corresponds to the user's entered x value according to y = ax + b. The values for a and b do not change after the user initially enters them, while x and y change with each iteration of the while loop.

Here is a sample run of the program, with SENTINEL = -1 (user input is italicized).

                    
Enter a value for a: 2
Enter a value for b: 4
Enter a value for x: 5
Result for x = 5 is 14
Enter a value for x: 1
Result for x = 1 is 6
Enter a value for x: -1



The program works properly regardless of the value of SENTINEL.

What's that in dog years?

                    

SENTINEL = 0
DOG_YEARS_PER_HUMAN_YEAR = 7

def main():
while True:
user_input = int(input("Enter an age in human years: "))
if user_input < 0:
print("Sorry, please enter a positive number or 0 to exit")
elif user_input == SENTINEL:
break
else:
dog_age = user_input * DOG_YEARS_PER_HUMAN_YEAR
print("The age in dog years is " + str(dog_age))

if __name__ == "__main__":
main()



Finding Factors

                    

SENTINEL = 0

def main():
while True:
user_in = int(input("Enter a positive number to get its factors, or enter 0 to stop:"))
if user_in < 0:
print("Please input a positive number")
elif user_in == SENTINEL:
break
else:
for i in range(1, user_in+1):
if user_in % i == 0:
print(str(i))




Rock, Paper, Scissors

                    
import random

NUM_ROUNDS = 5

def main():
num_human_wins = 0

for i in range(NUM_ROUNDS):
user_choice = int(input("Your move (1, 2, or 3): "))
computer_choice = random.randint(1, 3)

if computer_choice == user_choice:
print("It's a tie!")
else:
if user_choice == 1:
if computer_choice == 3:
print("You Win! Rock crushes scissors")
num_human_wins += 1
else:
print("You Lose! Paper covers rock")

if user_choice == 3:
if computer_choice == 2:
print("You Win! Scissors cuts paper")
num_human_wins += 1
else:
print("You Lose! Rock crushes scissors")

if user_choice == 2:
if computer_choice == 1:
print("You Win! Paper covers rock")
num_human_wins += 1
else:
print("You Lose! Scissors cuts paper")

print("You won " + str(num_human_wins) + " rounds!")

if __name__ == "__main__":
main()




Estimating $\pi$

                    
"""
File: solution.py
-----------------

Solutions for the Estimate Pi problem on CS 106A, Section 2, Spring 2020.
"""
import random

NUM_POINTS = 100_000

def estimate_pi():
"""
Estimates the value of π by randomly choosing points in the square and
calculating the percentage of points that lie in the circle. Prints out
the estimated value of π.
"""
num_in_circle = 0 # Counter variable

for i in range(NUM_POINTS):
"""
Pick a random point in the square. To do this, we need to pick a random
x coordinate and random y coordinate, each in the interval [-1, 1].
"""
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)

"""
The formula for a circle is x^2 + y^2 = r^2. In this case, since the
circle has radius 1, it can be described by x^2 + y^2 = 1. Points that
lie *inside* the circle have x^2 + y^2 <= 1.
"""
if x ** 2 + y ** 2 <= 1:
# (x, y) is inside the circle
num_in_circle += 1

"""
The area of the square is 4, the area of the circle is π. Thus, the
percentage of points in the circle is approximately π / 4.
"""
percent_in_circle = num_in_circle / NUM_POINTS # ~ π / 4
π = percent_in_circle * 4

print("π is roughly " + str(π))

if __name__ == '__main__':
# random.seed(8675309)
estimate_pi() # => 3.14224 (when seeded with Jenny's phone #)



Part B Solution

                    
import random

NUM_POINTS = 100_000
NUM_ESTIMATES = 100

def estimate_pi():
"""
Estimates the value of π by randomly choosing points in the square and
calculating the percentage of points that lie in the circle. Prints out
the estimated value of π.

Returns
-------
float -- The estimated value of π.
"""
num_in_circle = 0 # Counter variable

for i in range(NUM_POINTS):
"""
Pick a random point in the square. To do this, we need to pick a random
x coordinate and random y coordinate, each in the interval [-1, 1].
"""
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)

"""
The formula for a circle is x^2 + y^2 = r^2. In this case, since the
circle has radius 1, it can be described by x^2 + y^2 = 1. Points that
lie *inside* the circle have x^2 + y^2 <= 1.
"""
if x ** 2 + y ** 2 <= 1:
# (x, y) is inside the circle
num_in_circle += 1

"""
The area of the square is 4, the area of the circle is π. Thus, the
percentage of points in the circle is approximately π / 4.
"""
percent_in_circle = num_in_circle / NUM_POINTS # ~ π / 4
π = percent_in_circle * 4

print("π is roughly " + str(π))
return π

def main():
"""
Calls estimate_pi() 100 times and averages the estimates. Then, prints out
that value.
"""
running_total = 0

for i in range(NUM_ESTIMATES):
running_total += estimate_pi()

average_value = running_total / 100

print("The average of those estimations is: " + str(running_total))

if __name__ == '__main__':
# random.seed(8675309)
main() # => 3.142082... (when seeded with Jenny's phone #)