Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
125 views

Recursion in Python

The document discusses recursion in Python. It defines recursion as a function that calls itself, directly or indirectly. It provides examples of direct recursion, where a function calls itself, and indirect recursion, where functions call each other in a loop. It also discusses the importance of a base case for recursion to terminate. Finally, it provides examples of calculating sums and factorials recursively in Python.

Uploaded by

Rinki Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views

Recursion in Python

The document discusses recursion in Python. It defines recursion as a function that calls itself, directly or indirectly. It provides examples of direct recursion, where a function calls itself, and indirect recursion, where functions call each other in a loop. It also discusses the importance of a base case for recursion to terminate. Finally, it provides examples of calculating sums and factorials recursively in Python.

Uploaded by

Rinki Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

https://www.getsmarter.

com/blog/career-advice/how-artificial-neural-
networks-can-be-used-for-data-mining/It means a defined function can call
itself.

https://www.dataminingapps.com/2016/05/theres-something-fuzzy-in-data-
mining/

Introduction: 

Hello Readers, hope all of you are doing great. In this article, we will be
covering all the basics needed for a beginner to start with recursion in
python.

What is Recursion?  

In many programs, you must have implemented a function that


calls/invokes some other function. For example :

def A():
b()

Here we see that the function ‘A’ calls the function ‘B’

So a basic example of recursion would be the case, when the function


would call itself, in place of some other function.

A function is said to be a recursive function if it calls itself.

They are of two types: indirect and direct recursion.

When a function calls itself directly, from within its body, it is direct
recursion. Example :

def rec():
rec()

On the other hand, when a function calls some other function, which in turn
calls its caller function again, is called indirect recursion. Example :

def A():
B()
def B():
A()

This article was published as a part of the Data Science Blogathon

Introduction: 

Hello Readers, hope all of you are doing great. In this article, we will be
covering all the basics needed for a beginner to start with recursion in
python.

What is Recursion?  

In many programs, you must have implemented a function that


calls/invokes some other function. For example :

def A():
b()

Here we see that the function ‘A’ calls the function ‘B’

So a basic example of recursion would be the case, when the function


would call itself, in place of some other function.

A function is said to be a recursive function if it calls itself.


They are of two types: indirect and direct recursion.

When a function calls itself directly, from within its body, it is direct
recursion. Example :

def rec():
rec()

On the other hand, when a function calls some other function, which in turn
calls its caller function again, is called indirect recursion. Example :

def A():
B()
def B():
A()

Base Case for Recursion in Python 

Let us consider the following code :

def fun1():
print("Hello function 2")
fun2()
def fun2():
print("Hello function 1")
fun1()

Can you predict what shall be the output?

Yes, you guessed it right, the code will print endlessly !!

This is because the functions will keep on calling each other endlessly.
But does this mean, that the entire memory will be used up in the process?
NO, python will return an error to prevent that and stop right there.

The error will be something like:

RuntimeError: maximum recursion depth 1 exceeded...

So clearly, when using recursion, we must write a sensible code, that


instructs the compiler, when to stop the process, this is where Base Case
comes into play.

A Base Case is a case, whose result is known or predetermined, without any


recursive calling. you will have a better understanding of a base case when u
see an example.

Example to calculate the sum of ‘n’ numbers using


recursion in Python

Shown below, is the code, to calculate e the sum of first ‘n’ numbers, using
recursion.

def rec(n):
if n==1 :
return 1    # This is a Base Case
else:
return (n+rec(n-1))
last = int(input("Enter the upper limit"))
s = rec(last)
print("Sum of series from 1 to  ", last," is :", s)

The output of the above code came out to be :


Enter the upper limit 4
Sum of series from 1 to 4 is :10

Recursive Definition 

A Recursive definition is a definition that is made in terms of the smaller


version of itself. Consider the following example :

xn = x*x*x*x…n times

Now it can be represented in terms of recursive definition as follows :

xn = x*(xn-1) for n > 1  (This is the recursive definition)

=x (for n=1) or 1 (for n=0)

Example of a recursive function

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))

Output

The factorial of 3 is 6
Each function multiplies the number with the factorial of the number below
it until it is equal to one. This recursive call can be explained in the
following steps.

factorial(3) # 1st call with 3

3 * factorial(2) # 2nd call with 2

3 * 2 * factorial(1) # 3rd call with 1

3 * 2 * 1 # return from 3rd call as number=1

3 * 2 # return from 2nd call

6 # return from 1st call

Let's look at an image that shows a step-by-step process of what is going


on:

Working of a recursive
factorial function
Our recursion ends when the number reduces to 1. This is called the base
condition.

Advantages of Recursion
1. Recursive functions make the code look clean and elegant.

2. A complex task can be broken down into simpler sub-problems using


recursion.

3. Sequence generation is easier with recursion than using some


nested iteration.
4. def recur_fibo(n):
5.    # Base Case
6.    if n <= 1:
7.        return n
8.    else:
9.    # Recursive Case
10.       return(recur_fibo(n-1) + recur_fibo(n-2))
11. 
12.# Driver Code
13.num = 10
14.print (recur_fibo(num))

Output

55

The sum() function keeps calling itself as long as its argument is greater than zero.

The following defines the recursive version of the sum() function:

def sum(n):
if n > 0:
return n + sum(n-1)
return 0

result = sum(100)
print(result)
As you can see, the recursive function is much shorter and more readable.

If you use the ternary operator, the sum() will be even more concise:

def sum(n):
return n + sum(n-1) if n > 0 else 0

result = sum(100)
print(result)

Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.

2. Recursive calls are expensive (inefficient) as they take up a lot of


memory and time.

3. Recursive functions are hard to debug.

Every recursive function consists of two major parts or cases, the second part having three
components.

 base case(s),:- In which the problem is simple enough to be solved directly, It is also
known as termination condition i.e., based on condition function must terminates else
it enters in infinite loop.
 recursive case(s). A recursive case has three components:
1. divide the problem into one or more simpler or smaller parts of the problem,
2. call the function (recursively) on each part, and
3. combine the solutions of the parts into a solution for the problem.

1. Write a function to compute the sum of all numbers from 1


to n.
2. Write a function to compute 2 to the power of a non-
negative integer.
3. def power(N, P):
4.
5.     # if power is 0 then return 1
6.     if P == 0:
7.         return 1
8.
9.     # if power is 1 then number is
10.     # returned
11.     elif P == 1:
12.         return N
13.
14.     else:
15.         return (N*power(N, P-1))
16.
17. # Driver program
18. N = 5
19. P = 2
20.
21. print(power(N, P))

Output:
25

22. Write a function to compute the nth Fibonacci number.


23. Write a function to compute the greatest common
divisor (GCD) of two positive integers with Euclid's
algorithm.
24. Write a function to compute GCD based on the
following relations
o GCD(2m, 2n) = 2 * GCD(m, n)
o GCD(2m, 2n+1) = GCD(m, 2n+1)
o GCD(2m+1, 2n+1) = GCD(n-m, 2m+1) if m < n
o GCD(m, m) = m

(after "ML for the Working Programmer", page 49).

1. # write a program to understand the GCD of two number in python using the 
recursion.  
2. def gcd_fun (x, y):  
3.     if (y == 0): # it divide every number  
4.         return x  # return x  
5.     else:  
6.         return gcd_fun (y, x % y)  
7. x =int (input ("Enter the first number: ")) # take first no.   
8. y =int (input ("Enter the second number: ")) # take second no.   
9. num = gcd_fun(x, y) # call the gcd_fun() to find the result  
10. print("GCD of two number is: ")  
11. print(num) # call num  

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output

How many terms? 7


Fibonacci sequence:
0
1
1
2
3
5
8

Python Lambda
A lambda function is a small anonymous function.

In Python, an anonymous function is a function that is defined without a


name.

A lambda function can take any number of arguments, but can only have
one expression.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:

Example
Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:

Example
Multiply argument a with argument b and return the result:

x = lambda a, b : a * b
print(x(5, 6))
Summarize argument a, b, and c and return the result:

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

Difference Between Lambda functions and def


defined function

Let’s look at this example and try to understand the difference between a
normal def defined function and lambda function. This is a program that
returns the cube of a given value:  

 Python

# Python code to illustrate cube of a number


# showing difference between def() and lambda().
def cube(y):
    return y*y*y

lambda_cube = lambda y: y*y*y

# using the normally


# defined function
print(cube(5))

# using the lambda function


print(lambda_cube(5))

Output:
125
125
As we can see in the above example both the cube() function and
lambda_cube() function behave the same and as intended. Let’s analyze the
above example a bit more:
 Without using Lambda: Here, both of them return the cube of a
given number. But, while using def, we needed to define a function
with a name cube and needed to pass a value to it. After execution,
we also needed to return the result from where the function was
called using the return keyword.
 Using Lambda: Lambda definition does not include a “return”
statement, it always contains an expression that is returned. We
can also put a lambda definition anywhere a function is expected,
and we don’t have to assign it to a variable at all. This is the
simplicity of lambda functions.

 Python Lambda Function with if-else

 Python3

# Example of lambda function using if-else


Max = lambda a, b : a if(a > b) else b

print(Max(1, 2))

# Program to show the use of lambda functions


double = lambda x: x * 2

print(double(5))

is nearly the same as:

def double(x):

return x * 2

>>> add_one = lambda x: x + 1


>>> add_one(2)
3
The above lambda function is equivalent to writing this:

def add_one(x):
return x + 1

Need for Lambda Functions


There are at least 3 reasons:
1.
1. Lambda functions reduce the number of lines of code when
compared to normal python function defined
using def  keyword. But this is not exactly true because, even
functions defined with def can be defined in one single line.
But generally, def functions are written in more than 1 line.
 
1.
1. They are generally used when a function is needed temporarily
for a short period of time, often to be used inside another
function such as filter , map  and reduce .
 
1. Using lambda function, you can define a function and call it immediately
at the end of definition. This can’t be done with def  functions.

How to use lambda functions: Simple Example


You don’t need to specify a name for the function as discussed above about the syntax
of lambda function. Let’s try to define a function for calculating the squares of given values.

# calculate squares using lambda

squares = lambda x: x*x

print('Using lambda: ', squares(5))

Using lambda: 25

Let’s also look at how to do the same function using def keyword, and compare them.

# calculate squares using def

def squares_def(x):

return x*x

print('Using def: ', squares_def(5))

Output:
Using def: 25

Do the same in a single line.


# calculate squares using def in one line

def squares_def(x): return x*x


print('Using def: ', squares_def(5))

Using def: 25

Lambda functions can have 0 or 1 expression,


not more.
1. No expression : contains no expression, will give the same output for all
arguments.
x = lambda : "hello world"

print(x())

Output:
hello world

1. Single expression: They can contain either one expression or no


expression. We cannot put more than one expression in a lambda function.
new_single = lambda x : (x%2)

print(new_single(10))

Lambda functions accept all kinds of


arguments, just like normal def function
lambda function supports all kinds of arguments just like the normal def function. 1. Keyword
Arguments: keyword argument is an argument preceded by an identifier (e.g. name=) in a
function call. Named Arguments: Example
(lambda x, y=3, z=5: x*y*z)(7)

#> 105

Variable list of Arguments: Example


(lambda x, y=3, z=5: x*y*z)(x=7)

#> 105

Variable list of keyword arguments: Example


(lambda *args : sum(args))(3,5,7)
#> 15

2. Positional arguments: positional argument is an argument that is not a keyword argument.

(lambda x,y,z : x*y*z)(3,5,7)

#> 105

Using if else in Lambda function


Using if else in lambda function is little tricky, the syntax is as follows,

lambda <arguments> : <Return Value if condition is True> if <condition> else <Return Value if
condition is False>

For example let’s create a lambda function to check if given value is between 10 to 20 i.e.
lambda x : True if (x > 10 and x < 20) else False

# Lambda function to check if a given vaue is from 10 to 20.


test = lambda x : True if (x > 10 and x < 20) else False
# Check if given numbers are in range using lambda function
print(test(12))
print(test(3))
print(test(24))

Output:
True
False
False

Creating conditional lambda function without if else


lambda x : x > 10 and x < 20

Using if, elif & else in a lambda function


cases when we need to check multiple conditions in a lambda function. Like we need to
use if , else if & else in a lambda function. We can not directly use elseif in a lambda
function. But we can achieve the same effect using if else & brackets i.e.

lambda <args> : <return Value> if <condition > ( <return value > if <condition> else <return
value>)
Create a lambda function that accepts a number and returns a new number based on
this logic,

 If the given value is less than 10 then return by multiplying it by 2


 else if it’s between 10 to 20 then return multiplying it by 3
 else returns the same un-modified value

converter = lambda x : x*2 if x < 10 else (x*3 if x < 20 else x)

Let’s use this lambda function,


print('convert 5 to : ', converter(5))
print('convert 13 to : ', converter(13))
print('convert 23 to : ', converter(23))

Output:
convert 5 to : 10
convert 13 to : 39
convert 23 to : 23

You might also like