Week 8: Exercises

1. Time Class

Write a class Time that represents a time of day with 1-second resolution, e.g. 11:32:07.

2. Polynomial Class

Write a class Polynomial representing a polynomial of a single variable. The class should support these operations:

3. Comparing Dictionaries

Write a function same_dict(d1, d2) that returns true if two dictionaries have the same key-value pairs. You may not use the == method to compare the dictionaries directly (though you may use == on other types in your solution). For example:

>>> same_dict({ 10 : 20, 30 : 40 }, { 30 : 40, 10 : 20 })
True

If the two dictionaries have a total of N elements, what will be your function's expected big-O running time?

4. Swap the Pairs

Write a function that takes a list of pairs such as [(2, 3), (4, 1), (6, 5)] and returns a list in which the pairs have been swapped, e.g. [(3, 2), (1, 4), (5, 6)]. Use a list comprehension.

5. Flatten a Matrix

Write a function flatten() that takes a matrix and returns a list containing all the values from all rows:

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

Use a list comprehension.

6. Deep Flatten

Write a function deep_flatten 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:

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

7. Sum of All Numbers

Write a program that reads any number of lines from standard input, and prints out the sum of all numbers on all lines. For example, if the input is

2 6 4
3 3 2

then the program will print 20. Write the program in a single line using a list comprehension.

8. Matrix From Input

Write a function read_matrix() that will read a matrix from standard input. Each line will contain one row of the matrix, and the function should read standard input until it ends. For example, if the input is

6 2 4
7 5 3
1 8 9

then the function will return the list [[6, 2, 4], [7, 5, 3], [1, 8, 9]]. Write the function in a single line using a list comprehension.

9. Largest Matrix Value

Write a function largest_val that takes a matrix and returns the largest value in the matrix, along with its coordinates:

>>> largest_val([[1, 2, 3], [4, 5, 10], [6, 7, 8]])
(10, (1, 2))

Write the program in a single line using a list comprehension.

10. Pythagorean Triplet

Solve Project Euler problem #9 (Special Pythagorean triplet). Use a list comprehension.

11. Largest Product

Solve Project Euler problem #11 (Largest product in a grid). Read the grid from standard input.