Week 8: Exercises

1. 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?

2. 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.

3. 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.

4. 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.

5. 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.

6. 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.

7. Matrix Sum

Write a function add() that takes two matrices, represented as lists of lists. You may assume that the matrices have the same dimensions. The function should return the sum of the matrices, again represented as a list of lists. Use list comprehensions and the zip() function.

8. Index Sum

Write a function that takes lists a and b of the same length, and returns the largest value of i + a[i] + b[i] for any possible index i. Use the enumerate() and zip() functions in your solution.

9. Palindrome Product

Solve Project Euler problem #4 (Largest Palindrome Product). Use 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.