-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16.Recursion.py
More file actions
83 lines (41 loc) · 1.18 KB
/
16.Recursion.py
File metadata and controls
83 lines (41 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# ====================
# Recursion in Python
# ====================
# Recursion is when a function calls itself to solve a smaller version of the same problem.
# It keeps calling itself until it reaches a base case (a stopping condition).
# Without a base case, it will go infinite loop → crash.
# Factorial of a number:
def factorial(n):
# Base case: if n is 0 or 1, return 1
if n == 0 or n == 1:
return 1
# Recursive case: multiply n with factorial of (n-1)
else:
return n * factorial(n-1)
print(factorial(5)) # Output: 120
# Sum of first n natural numbers:
def sum_natural(num):
if num == 0:
return 0
else:
return num + sum_natural(num-1)
print(sum_natural(5))
# Fibonacci sequence
def fibonacci(n):
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return fibonacci(n-1) + fibonacci(n-2)
# Example: 6th Fibonacci number
print(fibonacci(6)) # Output: 8
# =============
# Questions
# =============
#? Q1:
#? Write a recursive function to reverse a string.
#? Q2:
#? Write a recursive function to find maximum element in a list.