0% found this document useful (0 votes)
1 views7 pages

Recursion

The document provides examples of recursive functions in Python, including calculating the factorial of a number, summing elements of a list, generating Fibonacci numbers, and summing the digits of a number. It includes code snippets demonstrating each function and prompts for user input. Additionally, it suggests writing recursive functions for summing whole numbers and reversing a string.

Uploaded by

aakashps214
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views7 pages

Recursion

The document provides examples of recursive functions in Python, including calculating the factorial of a number, summing elements of a list, generating Fibonacci numbers, and summing the digits of a number. It includes code snippets demonstrating each function and prompts for user input. Additionally, it suggests writing recursive functions for summing whole numbers and reversing a string.

Uploaded by

aakashps214
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

RECURSIVE

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)

fibo( fibo( fibo( fibo(


+ +
3) 2) 2) 1)

fibo( fibo( fibo( fibo(


+
2) 1) +
1) 0)

fibo( fibo( fibo( fibo(


+ + 0)
1) 0) 1)
# Sum of digits of a number

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.

2) Write a recursive function to reverse a string.

You might also like