Skip to content

Commit 5130f3a

Browse files
authored
Add simple recursion examples: factorial, fibonacci, sum_of_digits
1 parent 5c05335 commit 5130f3a

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

other/simple_recursion.py

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
"""
2+
Simple Recursion Examples.
3+
4+
This module contains a few basic examples of recursion for beginners.
5+
6+
Functions:
7+
- factorial(n): Calculate factorial of n.
8+
- fibonacci(n): Calculate nth Fibonacci number.
9+
- sum_of_digits(n): Calculate sum of digits of n.
10+
11+
Each function has doctests to verify correct behavior.
12+
"""
13+
14+
def factorial(n: int) -> int:
15+
"""
16+
Calculate the factorial of a non-negative integer n using recursion.
17+
18+
Args:
19+
n (int): Non-negative integer.
20+
21+
Returns:
22+
int: Factorial of n.
23+
24+
Raises:
25+
ValueError: If n is negative.
26+
27+
Examples:
28+
>>> factorial(5)
29+
120
30+
>>> factorial(0)
31+
1
32+
>>> factorial(1)
33+
1
34+
"""
35+
if n < 0:
36+
raise ValueError("Input must be a non-negative integer")
37+
if n == 0:
38+
return 1
39+
return n * factorial(n - 1)
40+
41+
42+
def fibonacci(n: int) -> int:
43+
"""
44+
Calculate the nth Fibonacci number using recursion.
45+
46+
Args:
47+
n (int): Non-negative integer index.
48+
49+
Returns:
50+
int: nth Fibonacci number.
51+
52+
Raises:
53+
ValueError: If n is negative.
54+
55+
Examples:
56+
>>> fibonacci(0)
57+
0
58+
>>> fibonacci(1)
59+
1
60+
>>> fibonacci(7)
61+
13
62+
"""
63+
if n < 0:
64+
raise ValueError("Input must be a non-negative integer")
65+
if n <= 1:
66+
return n
67+
return fibonacci(n - 1) + fibonacci(n - 2)
68+
69+
70+
def sum_of_digits(n: int) -> int:
71+
"""
72+
Calculate the sum of digits of a non-negative integer n using recursion.
73+
74+
Args:
75+
n (int): Non-negative integer.
76+
77+
Returns:
78+
int: Sum of digits of n.
79+
80+
Raises:
81+
ValueError: If n is negative.
82+
83+
Examples:
84+
>>> sum_of_digits(123)
85+
6
86+
>>> sum_of_digits(0)
87+
0
88+
>>> sum_of_digits(999)
89+
27
90+
"""
91+
if n < 0:
92+
raise ValueError("Input must be a non-negative integer")
93+
if n == 0:
94+
return 0
95+
return n % 10 + sum_of_digits(n // 10)
96+
97+
98+
if __name__ == "__main__":
99+
import doctest
100+
doctest.testmod()

0 commit comments

Comments
 (0)