Recursion is a process where a function calls itself. It's used to solve problems that can be broken down into smaller sub-problems of the same type.
Recursion वह प्रक्रिया है जिसमें एक function खुद को call करता है। इसका उपयोग उन्हीं problems को solve करने के लिए किया जाता है जिन्हें छोटे-छोटे हिस्सों में divide किया जा सकता है।
Every recursive function must have a base condition that stops the recursion. Otherwise, it will run infinitely and cause an error.
हर recursive function में एक base condition होना चाहिए जो recursion को रोकता है, वरना infinite बार call होता रहेगा।
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print("Factorial:", factorial(5))
Output:
Factorial: 120
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
for i in range(6):
print(fib(i), end=' ')
Output:
0 1 1 2 3 5
def sum_n(n):
if n == 0:
return 0
return n + sum_n(n - 1)
print("Sum:", sum_n(10))
Output:
Sum: 55
def reverse(s):
if len(s) == 0:
return s
return reverse(s[1:]) + s[0]
print(reverse("hello"))
Output:
olleh
def countdown(n):
if n == 0:
print("Blast off!")
else:
print(n)
countdown(n - 1)
countdown(5)
Output:
5 4 3 2 1 Blast off!