Programming 1, 2022-23
Week 8: Exercises

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

2. Diagonal Matrix

Write a function diagonal() that takes an integer n and returns a diagonal matrix of dimensions n x n. Recall tha a diagonal matrix has ones along its main diagonal and zeroes everywhere else. For example, diagonal(4) will return

[ [1, 0, 0, 0],
  [0, 1, 0, 0],
  [0, 0, 1, 0],
  [0, 0, 0, 1] ]

Use a nested list comprehension.

3. Matrix Sum

Write a function that computes the sum of two matrices A and B, represented as lists of lists. Assert that the matrices have the same dimensions. Use a nested list comprehension.

4. Flip a Dictionary

Write a function that takes a dictionary such as { 'green' : 'zelený', 'red' : 'červený' } and returns a corresponding dictionary in which the keys and values have been flipped, e.g. { 'zelený' : 'green', 'červený' : 'red'} . Assume that all values in the dictionary are unique. Use a dictionary comprehension.

5. Grep

The well-known UNIX utility 'grep' prints all lines in a file that contain a given string. It has the syntax

grep <string> <filename>

For example:

$ grep world ulysses
Gleams that untravell'd world whose margin fades 
'T is not too late to seek a newer world.
$

If you include the '-i' option, it matches lines without regard to case:

$ grep -i achilles ulysses
And see the great Achilles, whom we knew.

Write 'grep' in Python:

$ python3 grep.py -i achilles ulysses
And see the great Achilles, whom we knew.

6. Pythagorean Triplet

Solve Project Euler problem #9 (Special Pythagorean triplet).

7. Largest Product

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