Programming 1, Winter 2021-2
Week 10: Exercises

1. Time It

a) Write a function time_it(f, n) that calls the function f n times and returns the average time (in seconds) of each call to f. Use the library function time.time() to calculate the elapsed time.

b) Consider these two functions that compute the sum of all integers i in the range 0 ≤ i < 1,000,000:

def sum1():
    return sum(range(1_000_000))

def sum2():
    t = 0
    for x in range(1_000_000):
        t += x
    return t

Use your time_it() function to determine whether one of these functions is significantly faster than the other.

2. Sort By

Write a function sort_by(list, f) that sorts a list of values. The given function f will produce a comparison key for each value and you should sort by these keys, not by the values themselves. For example, if l is a list of strings, then sort_by(l, len) will sort the strings by length, i.e. from shortest to longest.

3. Bijective Function

Write a function bijective(f, n) that takes a function f whose domain and range are the integers 0 .. N – 1. The function should return True if f is bijective, i.e. f is both injective (i.e. f(x) ≠ f(y) whenever x ≠ y) and surjective (for every y in the range 0 ≤ y < N, there is some x such that f(x) = y).

4. Random Lines

Write a Tkinter program that draws 1000 random lines of length 300 pixels, each with a random color. All line angles should be equally likely.

5. Click the Circle

Write a program that displays a colored circle in the center of the window with the number 0 at the center. Each time the user clicks the window, the circle should change to a new random color, and the number should increment by 1.

6. Czech Flag

Write a program that draws a Czech flag:

Do not use any external image files – instead, the program should draw the flag itself using filled rectangles and/or polygons.