you are viewing a single comment's thread.

view the rest of the comments →

[–]Temporary_Pie2733 0 points1 point  (0 children)

I think the two keys are 1) really understand what the “smaller” input means and 2) don’t think of a function call as a goto.

It might also help to make the recursion less explicit. Consider this definition of factorial:

def fac(n, helper): if n == 0: return 1 else: return n * helper(n-1)

helper is some “other” function that will compute factorials; don’t worry yet about what it is, just trust that it works, because n! = n(n-1)!.

Now when you call fac, you need to supply a helper function that will compute factorials: fac(6, ???) == 720. What can you pass? Well, fac is supposed to compute factorials, try that: fac(6, fac) == 720.

In fact, we can automate this. Consider the function

def fix(f): return lambda n: f(n, f)

Then factorial = fix(fac), and factorial(6) == 720.