Unit III Lecture Hour 6
Unit III Lecture Hour 6
Function composition
Function composition is the way of combining two or more functions in such a way that the output of
one function becomes the input of the second function and so on. For example, let there be two functions
“F” and “G” and their composition can be represented as F(G(x)) where “x” is the argument and output
of G(x) function will become the input of F() function.
# Function to add 2
# to a number
def add(x):
return x + 2
# Function to multiply
# 2 to a number
def multiply(x):
return x * 2
Recursion
A physical world example would be to place two parallel mirrors facing each other. Any object in
between them would be reflected recursively
In Python, we know that a function can call other functions. It is even possible for the function to
call itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse
Factorial of a number is the product of all the integers from 1 to that number. For example, the
factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Let's look at an image that shows a step-by-step process of what is going on:
# Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10