Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Catalan Numbers [closed]

Tags:

python

catalan

I am trying to use this code to calculate the Catalan Number in Python, but it just does not work. How can I fix it?

Here is the code I have:

def catalan_rec(n):
    if n == 0:
        return 1
    else:
        b = 0
        for i in range (n):
            b += sum((catalan_rec(i))*(catalan_rec(n-1-i)))
    return b
like image 247
shaked Avatar asked Nov 27 '15 13:11

shaked


People also ask

What is the formula for calculating the Catalan number?

Catalan numbers are a sequence of positive integers, where the nth term in the sequence, denoted Cn, is found in the following formula: (2n)! / ((n + 1)! n!)

How do you find the closed form of a generating function?

We can get a closed form expression for G(S;z) by observing that G(S;z)−3zG(S;z)=1. Therefore, G(S;z)=11−3z. by application of the binomial formula. If Q(n)=n2, G(Q;z)=∑∞n=0n2zn=∑∞k=0k2zk.

How do I prove Catalan numbers?

This can be proved by using the asymptotic growth of the central binomial coefficients, by Stirling's approximation for. , or via generating functions. The only Catalan numbers Cn that are odd are those for which n = 2k − 1; all others are even. The only prime Catalan numbers are C2 = 2 and C3 = 5.


3 Answers

The problem is that you are summing, you should actually multiply. From Wikipedia the definition is:

catalan number formula

You can better use a for loop instead of recursion:

def catnumber(n):
  ans = 1.0
  for k in range(2,n+1):
     ans = ans *(n+k)/k
  return ans

Edit 2

I thought the formula was incorrect, but the problem was in fact that it was using integer division and therefore rounded sub results. The solution is to use a float variable, I do this by initializing with ans=1.0.

like image 175
agold Avatar answered Sep 30 '22 02:09

agold


Change the line:

b += sum((catalan_rec(i))*(catalan_rec(n-1-i)))

For:

b += (catalan_rec(i))*(catalan_rec(n-1-i))

You are passing an integer as argument to the function sum(), which only accepts an iterable.

like image 45
Javitronxo Avatar answered Sep 30 '22 00:09

Javitronxo


This seems to work for me(from your code)

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

print catalan_rec(5)

Out:

42
like image 45
Matjaž Dolgan Avatar answered Sep 30 '22 02:09

Matjaž Dolgan