pythonrecursioncatalan

How does the catalan() function works here?


I stumbled across this function to calculate the catalan number:

def catalan(n):
    if n == 0:
        return 1
    else:
        sum = 0
        for i in range (n):
            sum +=(catalan(i))*(catalan(n-1-i))
    return sum

My question is how sum gets values when for example n=2:

sum = (catalan(0))*(catalan(2-1-0)) + (catalan(1))*(catalan(2-1-1) + (catalan(2))*(catalan(2-1-2))

How did catalan(2-1-0) or for any other than 0 argument get it's value, if we defined only value for n=1?


Solution

  • Pen and paper evaluation

    catalan (0)

    # 1
    

    catalan (1)

    #  = 0 + catalan (0) * catalan (1-1-0)
    #  = 0 + 1 * catalan (0)
    #  = 0 + 1 * 1
    #  = 0 + 1
    

    catalan (2)

    #  = 0
    #  + catalan (0) * catalan (2-1-0)
    #  + catalan (1) * catalan (2-1-1)
    
    #  = 0 
    #  + 1 * catalan (1) 
    #  + 1 * catalan (0)
    
    #  = 0
    #  + 1 * 1
    #  + 1 * 1
    
    #  = 1
    #  + 1
    
    #  = 2
    

    catalan (3)

    #  = 0
    #  + catalan (0) * catalan (3-1-0)
    #  + catalan (1) * catalan (3-1-1)
    #  + catalan (2) * catalan (3-1-2)
    
    #  = 0
    #  + 1 * catalan (2) 
    #  + 1 * catalan (1)
    #  + 2 * catalan (0)
    
    #  = 0
    #  + 1 * 2
    #  + 1 * 1
    #  + 2 * 1
    
    #  = 0
    #  + 2
    #  + 1
    #  + 2
    
    #  = 5
    

    Wasted cycles

    Let's look at a naive fibonacci process –

    def fib (n):
      if n < 2:
        return n
      else:
        return fib (n-1) + fib (n-2)
    

    This procedure is instructive as a prototypical tree recursion, but it is a terrible way to compute Fibonacci numbers because it does so much redundant computation. Notice below that the entire computation of fib(3), almost half the work, is duplicated. In fact, it is not hard to show that the number of times the procedure will compute fib(1) or fib(0) (the number of leaves in the above tree, in general) is precisely fib(n + 1). To get an idea of how bad this is, one can show that the value of fib(n) grows exponentially with n — SICP - Tree Recursion

    wasteful fibonacci

    A similar problem is happening with you catalan program, but to an even worse degree. Calling catalan(3) will yield six (6) additional catalan calls

    # catalan (3)
    #  = 0
    #  + catalan (0) * catalan (3-1-0)
    #  + catalan (1) * catalan (3-1-1)
    #  + catalan (2) * catalan (3-1-2)
    #  ...
    #  = 5
    

    There are multiple techniques available to avoid this problem. Follow the citation above for more help on the topic.