Here we use a method that uses a stack instead of global variables. As shown, it counts the number of function calls, including the initial, and not just the number of recursive calls made by the function itself. To do this, simply move ncalls += 1 to the beginning of the else .
def f(n, ncalls=0): ncalls += 1 if n == 1: return 1, ncalls else: res, ncalls = f(n-1, ncalls) return n * res, ncalls for n in xrange(1, 6): print 'f({}): {:4d} ({} calls)'.format(n, *f(n))
Output:
f(1): 1 (1 calls) f(2): 2 (2 calls) f(3): 6 (3 calls) f(4): 24 (4 calls) f(5): 120 (5 calls)
source share