What does the reason for RecursionError while Compiling the Code?
Basically, Recursion errors are raised where we implement or test our code by giving large input to the Recursive Python Function. Python Recursion by default set the Recursion calling limit up to (10^3). Dynamic programing Algorithm, DFS, factorial, competitive programming are majorly used recursion calling to manipulate the output of repetitive equations.
Recursion Calling can also be done by Factorial. Factorials are used in power series of an exponential function, and they also have applications in algebra, number theory, probability theory, and computer science.
Manually Handling RecursionError limit –
We use Python's < import sys > module to set the recursion limit manually which has been set by python up to (103) and give the new limit up to (106). The setrecursionlimit() Function provides the functionality to implement this scenario.
Check Current Python recursion Limit.
>>>import sys
>>>print(sys.getrecursionlimit())
1000
Set new Python recursion Limit.
>>>import sys
>>>sys.setrecursionlimit(10**6)
>>>print(sys.getrecursionlimit())
1000000
>>>print(sys.getrecursionlimit())
1000000
Python Recursion Example 1: Calculate Total Number Of Handshakes in Python. (HackerRank Solution)
#Question: Number of handshakes such that a person shakes hands only once
# File Name: handshakes.py
import math
import random
import sys
sys.setrecursionlimit(10**6)
#
def handshake(n):
# Write your code here
if n==1:
return 0
return (n - 1) + handshake(n - 1)
if __name__ == '__main__':
#fptr = open(os.environ['OUTPUT_PATH'], 'w')
Test_limit = int(input().strip())
result=[]
for limit in range(Test_limit):
n = int(input().strip())
result.append( handshake(n))
#fptr.write(str(result) + '\n')
for items in result:
print(items)
#fptr.close()
#ENDInput:
Tommy@Gilbert:~/Desktop$ python handshakes.py
3 # Number of TestCase
6 # Case 1: Total Number of people 6.
5 # Case 2: Total Number of people 5.
1 # Case 3: Total Number of people 1. Output:
15 # Total Shake hands
10 # Total Shake hands
0 # Total Shake hands
3 # Number of TestCase
6 # Case 1: Total Number of people 6.
5 # Case 2: Total Number of people 5.
1 # Case 3: Total Number of people 1.
Python Recursion Example 2: Calculate Total Number Of Handshakes in Python. (Using Mathematic Formula.)
# file name: handshakes2.py
#Take user inputs
#Take user inputs
N = int(input('TOTAL NUMBERS OF PERSONS :'))
def no_of_handshakes():
return int(N *((N-1)/2)) # Mathematic Formula of Sum of N numbers.
result = no_of_handshakes(N)
#Print number of Total_Number_of_handshakes
print('Maximum number of handshakes can be :' + str(result))
Tommy@Gilbert:~/Desktop$ python handshakes2.py
#Input
TOTAL NUMBERS OF PERSONS : 6
#Output
Maximum number of handshakes can be : 15 # Total Shake hands
#Input
TOTAL NUMBERS OF PERSONS : 6
python fibonacci recursive
How to Write count function using recurrence in data structure?