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))
Related
I have a for loop which loops through initial guesses for a scipy.optimize.minimize routine. Some of the initial guesses fail, so I want to wrap the call to scipy.optimize.minimize in a try/except statement, so that when a guess fails, it moves on to the next.
Unfortunately this is not working. Once a guess fails, the next iterations also fail, even if the initial guess is a good one that I know works.
When I try to reproduce this failure in a MWE, I can't, so I am stumped.
Here is the MWE that works
import numpy as np
def f(x):
assert type(x) == float
return np.log(x)
def arbitrary_function():
vals = [ 0.5, "string", 5, 9.3]
v_list=[]
for num in vals:
try:
v = f(num)
if v > 0:
v_list.append(v)
except:
print("failed on {}".format(num))
continue
return v_list
my_list = arbitrary_function()
print(my_list)
Am I missing something with the try.. except usage?
The error that the real code raises on the failed attempts is due to
assert np.isclose(np.sum(x_tilde), 1.0)
AssertionError
for this reason I included the assert type(x) == float in the MWE, it raises the same exception, however, it carries on fine after hitting string, whereas my actual code only does the exceptions following a failure.
The real code has inside the try statement, where I have f(num)
try:
params = scipy.optimize.minimize(stuff)
if params.success:
stuff
except:
continue
Maybe the params.success is throwing it off since that doesn't exist when the scipy.optimize.minimize fails in the middle?
It does not appear to even attempt to do scipy.optimize.minimize on the next iteration once one of the initial guesses has caused scipy to fail.
Iam using break statement but it doesn't bring out of loop ,
I tried to find prime factors of given number but due to malfunctioning of break i cant do it
def fact(x):
for i in range(2,x+1):
if x%i==0:
xx.append(i)
x=x//i
if x==1:
break
else:
print('fact')
fact(x)
a=12
xx=[]
fact(a)
print(xx)
The main issue is that you are "double counting" factors.
having identified a factor, add it and call recursively with the number that results after removing the factor.
At the moment, you do that, but then also look for the next factor in the current function call.
There are of course little ways to improve this some more like skipping over values of i that we know cannot be factors of n and making the function return the array of results itself rather than updating a global, but this will get you going:
With the lightest modification to your existing code what you want to do is:
def fact(x):
for i in range(2,x+1):
if x%i == 0:
xx.append(i)
fact(x//i)
return
xx=[]
fact(12)
print(xx)
This will show you:
[2, 2, 3]
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 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
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