Functions and Recursion Chapter 5 Prof. Mauro Gaspari: gaspari@cs.unibo.it
Example import math def area(radius): temp = math.pi * radius**2 return temp # or def area(radius): return math.pi * radius**2
Absolute value Which one is correct? def absolutevalue(x): if x < 0: return x else: return x def absolutevalue(x): if x < 0: return x elif x > 0: return x
Incremental development Writing larger functions implies spending more time debugging. Incremental development: an approach to deal with increasingly complex programs.. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time.
Example: distance between two points Pitagora Theorem - (x1,y1) - (x2,y2) distance = x2 x1 2 y2 y1 2
First step The first step is to consider what a distance functions should look like in Python. what are the inputs (parameters)? what is the output (return value)? def distance(x1, y1, x2, y2): return 0.0 TEST? >>> distance(1, 2, 4, 6) 0.0
Second step def distance(x1, y1, x2, y2): dx = x2 x1 dy = y2 y1 print "dx is", dx print "dy is", dy return 0.0
Third step def distance(x1, y1, x2, y2): dx = x2 x1 dy = y2 y1 dsquared = dx**2 + dy**2 print "dsquared is: ", dsquared return 0.0
Fourth step def distance(x1, y1, x2, y2): dx = x2 x1 dy = y2 y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) return result
Summary 1) Start with a small working program and modify it introducing and testing small incremental changes. 3) Use local variables to store intermediate values so that you can print and test them. 3) Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.
Exercise 1 - Debugging
Exercise 2 Write a function that takes two points, the center of the circle and a point on the perimeter, and computes the area of the circle. Hints: Represent the two points respectively with variables x1, y1 and variables x2, y2. Can you compute the radius of this circle?
Recursion It is legal for one function to call another. It is also legal for a function to call itself. A function that calls itself is recursive; the process is called recursion. def countdown(n): if n == 0: print "Blastoff!" else: print n countdown(n 1)
Tracing a recursive function def countdown(n): if n == 0: print "Blastoff!" else: print n countdown(n 1) >>>countdown(3) 3 2 1 Blastoff! countdown(3) 3 countdown(2) 2 countdown(1) 1 countdown(0) Blastoff! return return return return
What is doing? def nlines(n): if n > 0: print nlines(n 1)
Stack diagrams Stack diagrams can help interpret a recursive function. For a recursive function, there might be more than one frame on the stack at the same time. The four frames have different values for the parameter n. The bottom of the stack, where n=0, is called the base case.
Infinite recursion! The base case is fundamental for termination. If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. def recurse(): recurse() >>>recurse() File "<stdin>", line 2, in recurse (98 repetitions omitted) File "<stdin>", line 2, in recurse RuntimeError: Maximum recursion depth exceeded
Defining recursive functions Analyse the base case carefully (termination). Implement the function. Verify if the following conditions hold: The recursive call should approach the base case. The base case works (testing it) If these conditions hold the recursive function should work correctly.
Use of recursion We have seen two programs that use recursion to perform repetition, which is also called iteration. Thus, recursion can be used to perform repetition. Several mathematical functions are implemented in a natural way using recursive functions.
A calculator exit = False def calculator(command): prompt = "Enter an expression: " command = input(prompt) if not command: return print "the result is ", command calculator(command) calculator(true)
Exercise 3 & 4 There is a semantic error in the calculator program, are you able to find it? Write a dummy python interpreter that always returns syntax error.
Example Factorial 0! = 1 n! = n (n-1)! def factorial(n): if n == 0: return 1
Factorial (cont) def factorial(n): if n == 0: return 1 else: recurse = factorial(n 1) result = n * recurse return result def factorial(n): if n == 0: return 1 else: return n * factorial(n 1)
Exercise 5 One of the most common example of a recursively defined mathematical function is the the fibonacci function, which has the following definition: fibonacci(0) = 1 fibonacci(1) = 1 fibonacci(n) = fibonacci(n 1) + fibonacci(n 2); Write a python script which includes a recursive fibonacci function and test it with several values
Exercise: Ackermann Function