Lecture Notes on 09 November 2009 # Solution to Class Work on 9 Nov 2009 def func (n): if (n == 0): return 0 else: return 2 * func(n - 1) + 1 # Iterative version of the above code def funcIter (n): f = 0 for i in range (1, n + 1): f = 2 * f + 1 return f # Recursive Fibonacci function def fib (n): if ((n == 1) or (n == 2)): return 1 else: return fib(n - 1) + fib(n - 2) # Iterative Fibonacci function def fibIter (n): f1 = 1 f2 = 1 f = 1 for i in range (3, n + 1): f1 = f2 f2 = f f = f1 + f2 return f # Recursive Towers of Hanoi function def tower (n, source, spare, destination): if (n == 1): print "Move disk from", source, "to", destination else: tower (n - 1, source, destination, spare) print "Move disk from", source, "to", destination tower (n - 1, spare, source, destination) def main(): # Test first two functions for i in range (1, 10): print func(i), funcIter(i print # Test the two Fibonacci functions for i in range (1, 10): print fib(i), fibIter(i) print # Test Towers of Hanoi code for i in range (1, 6): print "Num disks = ", i tower (i, 'A', 'B', 'C') print main()