Programming 1, 2021-22
Week 6: 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. No Zeroes

Write a function no_zeroes(n) that takes an integer n and returns an integer formed by removing all zeroes from the end of n's decimal representation. For example:

As a special case, no_zeroes(0) = 0.

You may not use any loops in your solution, so you will need to write the function recursively.

3. Recursive Power

Write a recursive function isPowOfTwo(n) that returns True if n is a power of 2.

4. Recursive Sum

Write a function sum(a, i, j) that computes the sum of the values in the range a[i:j]. You may not use any loops or call the built-in sum() function, so you will need to use recursion.

5. Recursive Max

Write a function max(a, i, j) that computes the maximum value in the range a[i:j]. You may not use any loops or call the built-in max() function, so you will need to use recursion.

6. Tower of Hanoi

The Tower of Hanoi is a well-known puzzle that looks like this:

The puzzle has 3 pegs and a number of disks of various sizes. The player may move disks from peg to peg, but a larger disk may never rest atop a smaller one. Traditionally all disks begin on the leftmost peg, and the goal is to move them to the rightmost.

Write a program that reads an integer N and prints a solution to the Tower of Hanoi with N disks. Assume that pegs are numbered from 1 to 3, and all disks begin on peg 1 and must move to disk 3. For example:

How many disks? 2
move disk 1 from peg 1 to peg 2
move disk 2 from peg 1 to peg 3
move disk 1 from peg 2 to peg 3

7. Sum of Squares and Square of Sum

Solve Project Euler's problem 6 in one line of Python using list comprehensions.