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

Write a function consecutive(a, n, t) with parameters a (a list of integers) and n and t (both integers). The function should return true if any consecutive series of n values in a have the sum t.

For example, consecutive([9, 7, 5, 2, 3, 2], 3, 10) is true, because the consecutive values [5, 2, 3] have sum 10.

3. Second Largest

Write a program that reads a series of integers, all on the same line. The program should print the second largest value in the input. For example, if the input is

2 7 7 3 6 5

then the output will be 6.

4. Largest product in a series

Solve Project Euler's problem 8, reading the input number as a series of lines from standard input.

5. Longest Collatz sequence

Solve Project Euler's problem 14.