Recursion
Recursion
FUNCTIONS
2*
Recursive Function 1
2 * fact ( 1)
- function calling itself
3*
2
def fact(x): 3 * fact ( 2)
'''Factorial of a number''' 4*
6
if x==1: return 1 4 * fact ( 3)
else: return x * fact( x - 1 ) 5*
24
5 5 * fact ( 4)
num = int(input('Enter number : ')) 12
0
if num>=1: print('Factorial = %d‘ % fact(num))
#2 Sum of elements of a list
Sum of elements of list [5, 10, 15,
def sum(seq): 20, 25] = 75
''' Finds sum of elements of
a list '''
if len(seq)==1:
return seq[0]
else: return seq[0] + sum(seq[1:]) 20 + sum([25])
l = [5,10,15,20,25] 15 +
sum([20,25])
print('Sum of elements of list ',l,' = ',sum(l))
10 +
sum([15,20,25])
5+
sum([10,15,20,25
])
def fibo(n):
''' Generate n th Fibonacii number''‘
a, b = 0, 1 C:\Users\Sonia>python samplex.py
if n==0:
for return 0
i in range(n): Enter number : 5
if n==1: return
a, b = b, a+b 1 5 th fibonacci number is 5
else:
return areturn fibo (n-1) +
fibo(n-2)
n = int(input('Enter number : '))
print('%d th fibonacci number is %d'%(n,fibo(n)))
C:\Users\Sonia>python samplex.py
Enter number : 10
10 th fibonacci number is 55
fibo(
5)
fibo( fibo(
+ 3)
4)
def sum_digits(n):
if not (n//10): return n
else: return (n%10) + sum_digits(n//10)
print(sum_digits(1234))
1) Write a recursive function to find sum of first N whole numbers.