30.1.1. Recursion - An overview
(a) A function call when made within the definition of the same function is known as a recursion function.
(c) Every time a recursive call is made, the arguments passed to the function should be closer to the base criteria.
30.1.2. Classification of recursive functions
(b) Recursion involves calling only one function, which calls itself repeatedly until a condition is met.
30.1.3. A simple program using recursion
def recurfact(n):
if n == 0:
return 1
else:
return(n * recurfact(n-1))
num = int(input("num: "))
if num < 0:
print("factorial not exist for negative number")
else:
print("factorial:",recurfact(num))
30.1.4. Write a program that calculates recursive sum
def r_sum(nested_num_list):
tot = 0
#fill in the missing code
for element in nested_num_list:
if type(element) == type([]):
tot += r_sum(element)
else:
tot += element
return tot
L1 = [1, 10, 9, [3, 5, 7], [5, [6, 7], 97]]
print(r_sum(L1))
30.1.5. Write a program to add two numbers using recursion
def add(x, y):
tot = x
#fill in the missing code..
if y == 0:
return x
else:
return tot + add(1, y - 1)
a = int(input("a: "))
b = int(input("b: "))
print(add(a, b))