0

How can I run the following program in python 2.7.3

import sys
sys.setrecursionlimit(2 ** 20)
def f(x):
    if (x==0): return 0
    else: return f(x-1)+1
print f(200000)

This code receives segmentation fault in Ubuntu.

2
  • It appears that you're overrunning your stack. You can increase your recursion limit, but that doesn't increase your stack size. Try rewriting it as a loop instead. Commented Apr 8, 2013 at 14:36
  • See stackoverflow.com/a/2918118/90308 Commented Apr 8, 2013 at 14:36

1 Answer 1

2

The Python interpreter runs out of stack space. Like any other process in the same situation, it is getting killed by the operating system.

You could try increasing the OS stack size limit (ulimit -c).

A better approach might be to rewrite your code so that it does not require recursion this deep (your particular example can be trivially converted into iteration).

Sign up to request clarification or add additional context in comments.

2 Comments

My code is an example which I know about this problem. Original code is hard for rewriting without recursion. ulimit -c 5000000 But I get SF again.
It should be "ulimit -s" ss64.com/bash/ulimit.html. "ulimit -a" should give you all the system defaults and the necessary flags when used to set these values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.