Skip to content

Commit f662053

Browse files
committed
Explanations with examples on recursion (solving sum of integers)
1 parent abfd1f0 commit f662053

File tree

2 files changed

+56
-39
lines changed

2 files changed

+56
-39
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
def sum_first_num_normal(n):
2+
return n * (n + 1) // 2
3+
4+
5+
def sum_first_num_recursive(n):
6+
if n == 0:
7+
# all of the calculation is actually based on this line!
8+
return 0
9+
10+
# ↓ the order for pushing call frames ↓
11+
# 5 + { f(5-1) }
12+
# 4 + { f(4-1) }
13+
# 3 + { f(3-1) }
14+
# 2 + { f(2-1) }
15+
# 1+ { f(1-1) } (0==0, base condition)
16+
# ↑ the order for calculating the returned values ↑
17+
18+
# got the result then return (0->1->2 || 0 or n-1 MEETS 0)
19+
# 1+0
20+
# 2+(1+0)
21+
# +(2+(1+0)))
22+
# 4+(3+(2+(1+0))))
23+
# 5+(4+(3+(2+(1+0)))))
24+
25+
# note that the leftmost 4,3,2,1 above do NOT "exist" (VERIFY-NEEDED)
26+
# they do not influence/being-included in the calculation
27+
# they are merely the returned values
28+
# they are the product of each returning (end-of-function)
29+
30+
# PUSH the funcs onto the stack
31+
# POP the funcs off the stack once funcs weren't called anymore (==1)
32+
33+
# my own explanation
34+
# > it follows LIFO operations
35+
# > stacked (fig & ds-type) functions won't change
36+
# > variable could change, therefore providing a 'base condition' (end/stp)
37+
38+
# It's all about the RETURNED values, the former n does NOT matter
39+
return n + sum_first_num_recursive(n - 1)
40+
41+
42+
# references
43+
# concept with examples
44+
# https://dev.to/kaxmoglan/recursive-functions-explained-5hie
45+
46+
47+
def main():
48+
_input = int(input("Enter a non-negative and non-zero integer: "))
49+
50+
print(
51+
sum_first_num_normal(_input), sum_first_num_recursive(_input), sep="\n"
52+
)
53+
54+
55+
if __name__ == "__main__":
56+
main()

chap03_recursion/sum_of_integers.py

Lines changed: 0 additions & 39 deletions
This file was deleted.

0 commit comments

Comments
 (0)