Mitlasóczki Bence Mitlasóczki Bence - 4 months ago 31
Python Question

What is wrong with this Python code about the Catalan numbers?

I'm new to Python. This is a homework problem, but it is tough as I only have a little experience in Java. The code is supposed to print the first Catalan-numbers using its recursive definition:

C(n + 1) = C(n) * (4n + 2) / (n + 2)


EDIT:

My current code looks like this, and the only remaining problem is to put all the C(n) numbers I get by this code in a txt using the savetxt() method.

import numpy

c = []
c.append(1)
for i in xrange(0,1000000000):
c.append((4*i+2)*c[i]/(i+2))
print (c[i])
if c[i]>= 1000000000:
break


numpy.savetxt("catalan",numpy.c_[i, c[i]])


After this last problem is solved, I will try some other versions suggested in the answers (like filling up an array of zeroes first).

Answer

Index out of range. Your first i is equal to 1 but c only has one element, which is index 0. So just change the range to (0,1000000000).

By the way, don't use range, use xrange, it'll be faster and take less memory. When you use range, Python creates an array of that size. An array of size 1000000000 takes a ton of memory. Instead, xrange create an iterator so it takes much less memory.

Comments