Programming 1, Winter 2021-2
Week 12: Exercises

1. File Count

Write a function file_count(dir) that takes a string containing a path to a directory, and returns the total number of files in the directory and its subdirectories (recursively).

2. File Search

Write a function search(dir, filename) that takes a string containing a path to a directory, plus a filename. The function should return True if there is any file with the given name in the directory or any of its subdirectories (recursively), otherwise False.

3. Vector Angle

Write a function angle(v, w) that takes two vectors (represented as lists of coordinates) and returns the angle between them in radians. You may not use any loops in your code (and so you will need to use list comprehensions, recursion or higher-order functions).

You will probably want to use the following formula, which relates the dot product of two vectors to the angle θ between them:

v · w = |v| |w| cos θ

4. Tree Values

Write a function that prints out all values in a binary search tree in order, separated by spaces.

5. Rebalancing a Tree

Write a function that takes a binary tree and constructs a second tree that contains all the values from the first tree and is as balanced as possible.

6. Flatten

Write a function flatten that takes a list of lists and returns a list containing all the values from all sublists:

>>> flatten([[5, 2], [6], [8, 3]])
[5, 2, 6, 8, 3]

7. Deep Flatten

Write a function deepFlatten that takes a list that may contain sublists nested to any level. The function should return a list containing all the values from all the sublists:

>>> deepFlatten([ [[5, 2], 6], [8, 3], [[[[10]]]] ])
[5, 2, 6, 8, 3, 10]

8. Drawing Squares

Write a program that lets the user draw squares by dragging the mouse. Each square should have a random color.

9. Dragging Squares

Extend the previous program so that the user can move a square to a new position by clicking and dragging it. A moved square should rise to the top of the Z-order.

10. Balloons

Write a program that displays balloons with random colors. Every 3 seconds, a new balloon should appear near the bottom of the screen. Each balloon should rise until it reaches the top of the screen, then vanish.

11. Balloon Game

Extend your program from the previous exercise, turning it into a simple video game. Each time the player clicks a balloon, it should pop and the user should gain a point. If any balloon reaches the top of the screen, the player has lost and the game is over. As the game proceeds, balloons should appear more frequently and move more quickly, so that the game becomes harder and harder. Display a score at the top of the screen.