-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path10_Recursion.py
More file actions
46 lines (36 loc) · 1011 Bytes
/
10_Recursion.py
File metadata and controls
46 lines (36 loc) · 1011 Bytes
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
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # Output: 120
# tail recursion -> A function is tail-recursive if the recursive call is the last thing the function does.
def tail_factorial(n, acc=1):
if n == 0:
return acc
else:
return tail_factorial(n - 1, acc * n)
print(tail_factorial(5))
# non-tail recursion -> In non-tail recursion, the recursive call is not the last operation — something still has to be done after it returns.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def print_numbers(n):
if n == 0: # base case
return
print_numbers(n - 1)
print(n)
print_numbers(5)
# Sum of First N Natural Numbers
def sum_n(n):
if n == 0:
return 0
return n + sum_n(n - 1)
print(sum_n(5)) # Output: 15
def power(a,b):
if b == 0:
return 1
return a * power(a, b - 1)
print(power(2, 3)) # Output: 8