I had a hard time understanding recursion, so I thought I'd put it together for myself. We may add more in the future. The language is Python3.
--A recursive function is a function that calls itself within a function. --Must be implemented so that it always ends somewhere --The method used in the ** Divide and Conquer Act ** to divide a large problem into smaller problems and solve them.
sum.py
def sum(n):
if n <= 1:
return n
return n + sum(n-1)
print(sum(100)) # 5050
sum.py
def sum(n):
res = 0
if n >= 1:
res = n + sum(n-1)
return res
print(sum(100)) # 5050
factorical.py
def fractorial(n):
if n <= 1:
return n
return n * fractorial(n-1)
print(fractorial(5)) # 120
factorical.py
def factorial(n):
res = 1
if n >= 1:
res = n * factorial(n-1)
return res
print(factorial(5)) # 120
def double_list(lst):
if lst == []:
return []
first = lst[0]
rest = lst[1:]
return [first*2] + double_list(rest)
print(double_list([1,2,3])) # [2, 4, 6]
An easy-to-understand explanation is here
euclidean.py
def gcd(m, n):
r = m % n
if r == 0:
return n
return gcd(n, r)
print(gcd(1071, 1029)) # 21
The simplest example for understanding recursive functions [Recursive functions understood in Python] (https://qiita.com/dhirabayashi/items/2f079e62fa2e286f1766) [Understanding recursive functions in Python] (https://note.com/shimakaze_soft/n/nf17633fe257c) The idea of making a loop a recursive function
It's hard to imagine recurrence and I'm still struggling ... The code looks simple, but it takes time to figure out how it works. That point for statement is easy to understand, isn't it?
Recommended Posts