Week 4: Exercises

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

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.

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

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

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

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

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

8. Summation of primes

Solve Project Euler's problem 10:

Find the sum of all the primes below two million.