Wednesday, 19 June 2013

Tracing function call in Python

We know that function is a building part of a program in python so we need to pass a function as another functions argument this is done using higher order functions .Tracing a function call means find the number of times a function is called.  
                Higher order functions are functions which can take function as argument and returns new function from function call.Lets explain tracing function call using a Fibonacci function here is the code for Fibonacci.

1:  def fib(n):  
2:    if n is 0 or n is 1:  
3:      return 1  
4:    else:  
5:      return fib(n-1) + fib(n-2)  

This function is calling recursively now we trace how many times fib is called using the function trace

1:  def trace(f):  
2:    def g(x):  
3:      print f.__name__, x  
4:      value = f(x)  
5:      print 'return', repr(value)  
6:      return value  
7:    return g  
8:  f = trace(fib)  
9:  print f(3)     

The trace returns the output as:

1:  fib 3  
2:  fib 2  
3:  fib 1  
4:  return 1  
5:  fib 0  
6:  return 1  
7:  return 2  
8:  fib 1  
9:  return 1  
10:  return 3  
11:  3  

f= trace(fib) that means fib is replaced by f and f return the value of function   call before the actual call of fib.this is the way to how to trace a function call
 

No comments:

Post a Comment