def recursive_factorial(n):
if n == 1: #base case
return 1
else:
return n * recursive_factorial(n-1) #recursive call
pls help I am getting a runtime error:RuntimeError('maximum recursion depth exceeded'
So, you have reached your recursion limit. This can be reset by importing sys and setting but:
Seriously don't use setrecursionlimit
You definitely try to iterate before using recursion. Please try this, which should work if you cannot set recursion limits:
re(n):
g=n
while n>1:
g*=(n-1)
n-=1
return g
If you really, really want to set your recursion limit, make sure that you do so only temporarily. Otherwise other, heavier, functions may create issues if too recursive:
import sys
def thing_i_want_to_recurse(n)
c_limit = sys.getrecursionlimit()
sys.setrecurionlimit(n)
yield
sys.setrecurionlimit(c_limit)
Again iteration is best:
[in]: sys.setrecursionlimit(3)
[in]: recursive_factorial(5)
[out]:Error: maximum recusion depth exceeded
[in]: re(5) #no problem
[out]: 120
Related
I am a bit of a noob, please go easy on me.
I'm trying to solve this.
The input I'm using.
So I have written code using mammoth amount of input and it keeps on piling up every time function is called.
I want to understand how to approach this and not get the Maximum Recursion Depth Exceeded Error
count = 0
#a #I assign the whole input here
def count_bag(x):
#a #I assign the whole input here again
for x in a:
if x == "other bags":
continue
elif "shiny gold" in a[x]:
global count
count += 1
break
else:
for y in a[x]:
count_bag(y)
count_bag(a)
print(count)
In python the recursion depth is limited for most compilers, so if you want to do some deep recursion you can use sys.setrecursionlimit(some value) to get over this issue
import sys
sys.setrecursionlimit(10**6)
Why not use a queue and skip the recursion? That way, you don't even need to use a global count variable. I haven't compiled/linted this or anything, but something like this:
def count_bag(x, a):
count = 0
to_process = list()
to_process.extend(x)
while len(to_process) > 0:
item = to_process.pop(0) # pop item off front of list
if item == 'other bags':
continue
elif 'shiny gold' in a[item]:
count += 1
else:
for y in a[item]:
to_process.extend(y)
return count
import math
import sys
sys.setrecursionlimit(8000000)
f = {1:2,2:3,3:5}
def fib(n):
if n in f:
return f[n]
if n == 1:
return 2
if n == 2:
return 3
if n == 3:
return 5
val = fib(n-1) + fib(n-2)
if n not in f:
f[n] = val
return f[n]%1000000007
print(fib(4000))
This code fails to complete / command prompt crashes. How can I make this better?
Is there any setting that I need to enable to make this program complete?
Implementing the Fibonacci sequence directly from the mathematical definition is an exercise that illustrates problems with recursive solutions. It leads to an exponential explosion of recursive function calls that even modern computers cannot handle. The biggest problem is that for large values of n, you will calculate fib(1) an exponential number of times.
There are several solutions to this problem:
Use memoization to store values that have already been calculated. Then you look up the calculated value and return it immediately without doing any further calculations. This is a good exercise to learn how memoization works. However, it is still inefficient because you still unnecessarily execute recursive function calls.
Implement an iterative solution. I'm not going to get into the details here. I suggest you do some research to find the iterative solution that will implement fib(n) in linear time instead of exponential time.
Implement the closed formula. Mathematicians have already solved fib(n) as a closed formula. This solution will take constant time no matter how large of an n you use.
use automatic memorization of old vales so that it won't go into infinity loop.use lru_cache as a decorator on your function.
import sys
from functools import lru_cache
sys.setrecursionlimit(8000000)
f = {1:2,2:3,3:5}
#lru_cache(maxsize=None)
def fib(n):
if n in f:
return f[n]
if n == 1:
return 2
if n == 2:
return 3
if n == 3:
return 5
val = fib(n-1) + fib(n-2)
if n not in f:
f[n] = val
return f[n]%1000000007
print(fib(4000))
I have developed a code for finding max and min using recursion. But as soon as I make a list greater then 6 elements it throws a runtime error.
RecursionError: maximum recursion depth exceeded in comparison
Here is the below code:
def maxmin(a,i,j):
if(i==j):
return(a[i],a[j])
elif(i==j-1):
if(a[i]>a[j]):
return(a[i],a[j])
else:
return(a[j],a[i])
else:
mid =int(i+j/2)
value1 =maxmin(a,i,mid)
value2 =maxmin(a,mid+1,j)
if(value1[0]>value2[0]):
max=value1[0]
else:
max=value2[0]
if(value1[1]<value2[1]):
min = value1[1]
else:
min=value2[1]
return(max,min)
import sys
sys.setrecursionlimit(1000)
a =[2,3,90,0,-9,3]
maxmin(a,0,len(a)-1)
I have also increased the limit for recursion but still not working.
I tried another small code by recursion with a stack size of 1000 and its working fine. I think there is some issue in the code. The stack space occupied by the above program is not even 100.
import sys
sys.setrecursionlimit(1000)
def fib(n, sum):
if n < 1:
return sum
else:
return fib(n-1, sum+n)
c = 900
print(fib(c, 0))
The second program is working fine while the first is throwing errors.
I wouldn't use recursion:
print(min(a))
print(max(a))
I tried to build a simple code that solved square operational with value n using python, plus, i want to learn recursion. I made three different style code like below syntax:
First code
def pangkat(nilai, pangkat):
a = int(1)
for i in range(pangkat):
a = a * nilai
return a
if __name__ == "__main__":
print(pangkat(13, 8181))
Second Code
def pangkat(nilai, pangkat):
hasil = nilai**pangkat
return hasil
if __name__ == "__main__":
print(pangkat(13, 8181))
Third Code
def pangkat(nilai, pangkatnilai):
if pangkatnilai == 1:
return nilai
return nilai * pangkat(nilai, pangkatnilai-1)
if __name__ == "__main__":
print(pangkat(13,8181))
Note : param nilai as number that will be raised, and pangkat as number that will raised param nilai), all of these code works well for example, when i fill the nilai and param
Input 0
pangkat(13, 12)
Output 0
23298085122481
The problem occurred when i changed the param pangkat >= 1000, it will said , it will gave me an error but only in third code.
Traceback (most recent call last):
File "pang3.py", line 8, in <module>
print(pangkat(13,1000))
File "pang3.py", line 5, in pangkat
return nilai * pangkat(nilai, pangkatnilai-1)
File "pang3.py", line 5, in pangkat
return nilai * pangkat(nilai, pangkatnilai-1)
File "pang3.py", line 5, in pangkat
return nilai * pangkat(nilai, pangkatnilai-1)
[Previous line repeated 995 more times]
File "pang3.py", line 2, in pangkat
if pangkatnilai == 1:
RecursionError: maximum recursion depth exceeded in comparison
While the first and second code works well. What could go wrong with my recursion function ? plus i need the explanation for it, Thanks!
NB : As possible, is there any better approach for using recursion like i needed ? i build my recursion using my own logic, so i expect if someone had better approach for that code.
The Python interpreter limits how deeply you can recurse. By default, the depth is 1000 levels of function calls, after which you get an exception (the RecursionError you see from your third function). So in one respect, your code is working as expected. You wanted to recurse 8181 times and Python quit after 1000, since that's the default limit.
If you want to recurse more deeply, you can change the recursion limit, using the sys.setrecursionlimit function. Setting the recursion limit to 9000 would be enough for your function to run with the argument you were giving it in your example.
As for why Python only allows a limited depth of recursion, it's mostly because there's seldom a need for more. Recursion is much less efficient than iteration in most situations, so you generally don't want to use deep recursion for big problems, as it will be very slow. Most of the time that you hit the recursion limit, it will be because of a bug that made what was supposed to be a shallow recursion into an infinite recursion, and Python did the right thing by stopping the program rather than letting it go on forever.
Actually the default max depth for recursion is 1000. To get rid of that issue in this case you have to use the below 1 line at the top of your code.
sys.setrecursionlimit(1002)
It would be better to set to max value if you are also looking to try other values e.g. 1050,1400 etc. (It is also valid in your case).
sys.setrecursionlimit(1500)
Visit https://docs.python.org/3/library/sys.html#sys.setrecursionlimit to check the details. Here I am pasting the important part to be focused.
Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.
The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.
If the new limit is too low at the current recursion depth, a RecursionError exception is raised.
import sys
print(sys.getrecursionlimit()) # 1000
sys.setrecursionlimit(1002) # Set max depth for recursion
print(sys.getrecursionlimit()) # 1002 (Checing again)
def pangkat(nilai, pangkatnilai):
if pangkatnilai == 1:
return nilai
return nilai * pangkat(nilai, pangkatnilai-1)
if __name__ == "__main__":
print(pangkat(13, 1000))
I wanted to calculate a recursive function using lru_cache. Here is a simplified version of it:
from functools import lru_cache
#lru_cache(maxsize=None)
def f(n:int)->int:
if (n==0): return 1
return n+f(n-1)
### MAIN ###
print(f(1000))
It works well when I run f(100), but with f(1000) I get:
RecursionError: maximum recursion depth exceeded in comparison
One solution is to calculate a table of values for f myself. Is there a solution that does not require me to manually create a table of values?
Note that you can use your function as-is, but you need to ensure each fresh call doesn't have to recurse more than several hundred levels before it hits a cached value or recursive base case; e.g.,
>>> f(400)
80201
>>> f(800) # will stop recursing at 400
320401
>>> f(1000) # will stop recursing at 800
500501
I've resorted to that at times ;-) More generally, you could write a wrapper function that repeatedly tries f(n), catches RecursionError, and backs off to calling it with ever-smaller values of n. For example,
def superf(n, step=400):
pending = []
while True:
pending.append(n)
try:
f(n)
break
except RecursionError:
n = max(n - step, 0)
while pending:
x = f(pending.pop())
return x
Then
>>> superf(100000)
5000050001