Recursion in Python
Recursion in Python
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?
def A():
b()
Here we see that the function ‘A’ calls the function ‘B’
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()
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?
def A():
b()
Here we see that the function ‘A’ calls the function ‘B’
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()
def fun1():
print("Hello function 2")
fun2()
def fun2():
print("Hello function 1")
fun1()
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.
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)
Recursive Definition
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.
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.
Output
55
The sum() function keeps calling itself as long as its argument is greater than zero.
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.
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.
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.
Output:
25
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
Output
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have
one expression.
Syntax
lambda arguments : expression
Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
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))
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
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.
Python3
print(Max(1, 2))
print(double(5))
def double(x):
return x * 2
def add_one(x):
return x + 1
Using lambda: 25
Let’s also look at how to do the same function using def keyword, and compare them.
def squares_def(x):
return x*x
Output:
Using def: 25
Using def: 25
print(x())
Output:
hello world
print(new_single(10))
#> 105
#> 105
#> 105
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
Output:
True
False
False
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,
Output:
convert 5 to : 10
convert 13 to : 39
convert 23 to : 23