Week 5: Exercises

1. Closest Points

Write a program that reads a series of points, one per line. Each point will consist of N floating-point coordinates separated by spaces, for some N ≥ 2. It is guaranteed that all points will have the same number of coordinates. Determine which two points are closest to each other. Write those points, along with the distance rounded to 1 decimal point. For example, if the input is

0.0 0.0
4.0 3.0
20.0 20.0

then the output will be

Points (0.0, 0.0) and (4.0, 3.0) are closest, with distance 5.0

2. Column with Largest Number

Write a program that reads a square matrix of integers. The program should print the largest value in the matrix and the column number that contains it.

Input:

2 8 3
9 6 7
0 3 -1

Output:

Column 1 contains 9.

4. Symmetric Matrix

A matrix M is symmetric if Mij = Mji for all i and j. For example, here is a symmetric matrix:

1 2 3
2 5 4
3 4 6

Write a function that takes a square matrix M represented as a list of lists, and returns True if the matrix is symmetric.

5. Identity Matrix

The identity matrix of size N x N contains ones along its main diagonal, and zeroes everywhere else. For example, here is the identity matrix of size 4 x 4:

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

Write a function identity_matrix(n) that returns the identity matrix of size n x n, represented as a list of lists.

6. Largest Row or Column Sum

Write a program that reads a square matrix of integers. The program should print the largest sum of any row or column in the matrix.

Input:

2 4 8 10
5 3 7 1
9 6 9 4
2 2 8 3

Output:

32

7. Local and Global

What will this program print?

a = 2
b = 3

def foo():
  a = b + 1
  a = a + 1
  return a

def bar():
  global b
  b = a + 3
  return b

def baz():
  return a + b

def thud():
  a = b + 1
  b = a + 1
  return a

print(foo())
print(bar())
print(baz())
print(thud())

8. Largest product in a series

Solve Project Euler's problem 8:

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

Read the input number as a series of lines from standard input.

9. Special Pythagorean triplet

Solve Project Euler's problem 9:

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

10. Summation of primes

Solve Project Euler's problem 10:

Find the sum of all the primes below two million.