Chapter 2 Project
Guoliang Ma
The Chow Institute, 2025
A few practice questions on functions
from past exams
the ones mimicking what you expect to see in the midterm
If we toss a coin, it has two possible outcomes: head and tail. When a head (the number 1) appears, we write a “1” on a piece of paper. If a tail (flower) appears, we write a “0”. We toss the coin n times, and record all the outcomes.
For example:
This sequence is recorded as 1 0 1 1 1 0 1 0 1 1 0 0.
We define consecutive 1s as a run. So this sequence has 4 runs.
In Python, you can use the following code to generate a random sequence:
Please make a function to compute the number of runs of a sequence.
import random
n = 10
s1 = [random.randint(0, 1) for _ in range(n)]

For programmers, an important aspect of their code is the speed. Hence, it is common for programmers to try different ways to write functions. They will then test how long it takes to run each version of their code. To simplify the process, please make a decorator that can run the decorated function 100 times. Then after the function call, print a line including the average time and standard deviation of the 100 times. Please name this decorator timer_100.
sample usage:
sample output:
import random
@timer_100
def sums():
numbers = [random.random() for _ in range(10000)]
sum(numbers)
sums()
The average run time is 0.000609s; the std is 0.000076s.
Newton’s method needs a derivative and a suitable starting point. The secant method approximates the derivative using two previous iterates:
Implement the method and solve f(x) = |x − 3| − 1 = 0.
Choose two initial values and a stopping rule. Consider what to do if the denominator becomes zero.
Make two generators.
generator 1 is in charge of printing a line: “it is an odd second.” and saves the current time for future use.
generator 2 is in charge of printing a line: “it is an even second.” and saves the current time for future use.
Then write a function, which calls the two generators depending on if the current time.time() has an even or odd integer part.