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

Write a function append() that takes a variable number of arguments. Each argument should be a sequence, such as a list. The function should return a sequence formed by concatenating all of the sequences. For example:

>>> append([1, 2], [5, 6], [8, 9])
[1, 2, 5, 6, 8, 9]
>>> append()
[]

3. Max

Write a function my_max() that takes one or more arguments. If there is just one argument, it should be a sequence, and my_max() should return the maximum value in the sequence. Otherwise, each argument should be a value, and my_max() should return the maximum of these values. For example:

>>> my_max([2, 4, 6])
6
>>> my_max(2, 4, 6)
6

3. Building a List

In the lecture, we considered these two programs:

(1)

n = int(input('Enter n: '))
a = []
for i in range(n):
    a.append(i)

(2)

n = int(input('Enter n: '))
a = []
for i in range(n):
    a = a + [i]

We found that program 1 runs in O(N), and program 2 runs in O(N2), an important difference.

Now consider this third program:

(3)

n = int(input('Enter n: '))
a = []
for i in range(n):
    a += [i]

Do you think it will run in O(N), or O(N2)? Perform an experiment to find out which is the case.

(Recall that on lists += is a synonym for Python's extend() method.)

4. Word Length Histogram

Write a program that prints a histogram of the lengths of all words found in all input lines. For example, if the input is

there is a big green tree
in the park
on a sunny day

the program's output might look like this:

1: **
2: ***
3: ***
4: **
5: ***

You may assume that all words found in the input will be at most 30 characters long.

5. Matrix Sum

Write a function that takes two matrices, and returns the sum of the matrices. Assume that the matrices have the same dimensions.

6. Matrix Product

Write a function that takes two matrices, and returns the product of the matrices. Assume that the matrices have dimensions that are compatible for multiplication.

7. Lots of References

Recall that a[:] makes a copy of the list a. It's the same as a[0:len(a)], or as a.copy().

What will this program print? Why?

def bar(a):
    for i in range(len(a)):
        a[i] += 1
        a = a[:]

def foo(a):
    for b in a + a[:]:
        bar(b)
        bar(b[:])

m = [[1, 2], [3, 4]]
foo(m)
print(m)