Recursion
Difference between recursion and iteration
based functions
 Recursion uses selection structure.
 Infinite recursion occurs if the recursion step does not reduce the problem in a
manner that converges on some condition (base case) and Infinite recursion can
crash the system.
 Recursion terminates when a base case is recognized.
 Recursion is usually slower than iteration due to the overhead of maintaining the
stack.
 Recursion uses more memory than iteration.
 Recursion makes the code smaller.
continued
 Iteration uses repetition structure.
 An infinite loop occurs with iteration if the loop condition test never becomes false
and Infinite looping uses CPU cycles repeatedly.
 An iteration terminates when the loop condition fails.
 An iteration does not use the stack so it's faster than recursion.
 Iteration consumes less memory.
 Iteration makes the code longer.
Definition
Recursion is one of the most powerful
tool in a proramming language.Recursion
is a way of proramming where function
calls itself again and again.Recursion is
defined as defining something in terms
of itself.
Recursion Essentials
 There must be terminating condition for the problem,
 There must be an if condition in the recursive routine.This if clause specifies the
terminatin condition for the recursion.
 Reversal in te order of execution is the characteristics of every recursive problem.wen a
recursive program is taken for execution , the recursive function calls are not executed
immidiately.They are pushed on the stack as long as terminating condition is
encountered. Asoon as recursive condition is encountered the recursive calls which were
pushed on to stack are removed in reverse order and executed one by one.It means that
last call made would execute first,then the second last call will execute and so on till the
stack is empty.
 Each time a new recursive call is made new memory space will be allocated to each local
variableused by the recursive routine.In oter words during each recursive call to
recursive function the local variables of recursive functions gets a different set of values
but withh the same name.
Contd...
 The duplicated values of a local variables of a recursive calls are pushed on to stack
with its respective calls all there values are available to the respective calls when it
is popped off from the stack.
Disadvantages:it consumes more storage space between the recursive calls along with
local variables are stored on the stack.
The computer may run out of memory if recursive calls are not checked.
It is less efficient in terms of memory and execution speed.
So dividing the recursive problem into two parts:terminating part and recursive part.
Examples
def power(x,n):
if(n==0):
return 1
else:
return(x*power(x,n-1))
a=2
print(power(a,4))
Continued...
def recur_factorial(n):
if (n == 1):
return n
else:
return n*recur_factorial(n-1)
num = 5
# check if the number is negative
if (num < 0):
print("Sorry, factorial does not exist for negative numbers")
elif (num == 0):
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Continued...
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if (nterms <= 0):
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Continued...
def hcf(a,b):
if b==0:
return a
else:
return hcf(b, a%b)
# this is recursion as hcf() calls itself
# Reading numbers from user
first = int(input('Enter first number: '))
second = int(input('Enter second number: '))
# Function call & displaying output HCF (GCD)
print('HCF or GCD of %d and %d is %d' %(first, second, hcf(first, second)))
Activation record
An activation record usually contains the following information:
1. values for all parameters in the function
2. local variables which can be stored elsewhere
3. Return address to resume control by the caller,the address of the callers
instruction immidiately following the call
4. A dynamic link,which is a link to the callers activation record.
5. The returned value of a function.
Module
Modular programming is a software design technique to split your code into separate parts. These parts are called modules. The focus for
this separation should be to have modules with no or just few dependencies upon other modules. In other words: Minimization of
dependencies is the goal.
If you want to develop programs which are readable, reliable and maintainable without too much effort, you have to use some kind of
modular software design. Especially if your application has a certain size.
A1.py
def greeting(name):
print("Hello, " + name)
import A1
A1.greeting("JAIRAM")
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
A1.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
import A1
a = A1.person1["age"]
print(a)
Lambda function
A lambda function is a small anonymous function.A lambda function can take any
number of arguments, but can only have one expression.
lambda arguments : expression
x = lambda b : b + 10
print(x(7))
x = lambda a, b : a *b
print(x(4, 6))
x = lambda a, b, c : a + b + c
print(x(3, 3, 2))
Pass statement
 The pass statement is a null statement. But the difference between pass and comment is that
comment is ignored by the interpreter whereas pass is not ignroed.
 The pass statement is generally used as a placeholder i.e. when the user does not know what code
to write.
 user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any code
to execute.
 user simply places pass there as empty code is not allowed in loops, function definitions, class
definitions, or in if statements.
 using pass statement user avoids this error.
l =[‘u', ‘g', ‘j', ‘d']
for i in l:
if(i ==‘u'):
pass
else:
print(i)

Recursion vs. Iteration: Code Efficiency & Structure

  • 1.
  • 2.
    Difference between recursionand iteration based functions  Recursion uses selection structure.  Infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on some condition (base case) and Infinite recursion can crash the system.  Recursion terminates when a base case is recognized.  Recursion is usually slower than iteration due to the overhead of maintaining the stack.  Recursion uses more memory than iteration.  Recursion makes the code smaller.
  • 3.
    continued  Iteration usesrepetition structure.  An infinite loop occurs with iteration if the loop condition test never becomes false and Infinite looping uses CPU cycles repeatedly.  An iteration terminates when the loop condition fails.  An iteration does not use the stack so it's faster than recursion.  Iteration consumes less memory.  Iteration makes the code longer.
  • 4.
    Definition Recursion is oneof the most powerful tool in a proramming language.Recursion is a way of proramming where function calls itself again and again.Recursion is defined as defining something in terms of itself.
  • 5.
    Recursion Essentials  Theremust be terminating condition for the problem,  There must be an if condition in the recursive routine.This if clause specifies the terminatin condition for the recursion.  Reversal in te order of execution is the characteristics of every recursive problem.wen a recursive program is taken for execution , the recursive function calls are not executed immidiately.They are pushed on the stack as long as terminating condition is encountered. Asoon as recursive condition is encountered the recursive calls which were pushed on to stack are removed in reverse order and executed one by one.It means that last call made would execute first,then the second last call will execute and so on till the stack is empty.  Each time a new recursive call is made new memory space will be allocated to each local variableused by the recursive routine.In oter words during each recursive call to recursive function the local variables of recursive functions gets a different set of values but withh the same name.
  • 6.
    Contd...  The duplicatedvalues of a local variables of a recursive calls are pushed on to stack with its respective calls all there values are available to the respective calls when it is popped off from the stack. Disadvantages:it consumes more storage space between the recursive calls along with local variables are stored on the stack. The computer may run out of memory if recursive calls are not checked. It is less efficient in terms of memory and execution speed. So dividing the recursive problem into two parts:terminating part and recursive part.
  • 7.
  • 11.
    Continued... def recur_factorial(n): if (n== 1): return n else: return n*recur_factorial(n-1) num = 5 # check if the number is negative if (num < 0): print("Sorry, factorial does not exist for negative numbers") elif (num == 0): print("The factorial of 0 is 1") else: print("The factorial of", num, "is", recur_factorial(num))
  • 12.
    Continued... def recur_fibo(n): if n<= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) # take input from the user nterms = int(input("How many terms? ")) # check if the number of terms is valid if (nterms <= 0): print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibo(i))
  • 13.
    Continued... def hcf(a,b): if b==0: returna else: return hcf(b, a%b) # this is recursion as hcf() calls itself # Reading numbers from user first = int(input('Enter first number: ')) second = int(input('Enter second number: ')) # Function call & displaying output HCF (GCD) print('HCF or GCD of %d and %d is %d' %(first, second, hcf(first, second)))
  • 14.
    Activation record An activationrecord usually contains the following information: 1. values for all parameters in the function 2. local variables which can be stored elsewhere 3. Return address to resume control by the caller,the address of the callers instruction immidiately following the call 4. A dynamic link,which is a link to the callers activation record. 5. The returned value of a function.
  • 15.
    Module Modular programming isa software design technique to split your code into separate parts. These parts are called modules. The focus for this separation should be to have modules with no or just few dependencies upon other modules. In other words: Minimization of dependencies is the goal. If you want to develop programs which are readable, reliable and maintainable without too much effort, you have to use some kind of modular software design. Especially if your application has a certain size. A1.py def greeting(name): print("Hello, " + name) import A1 A1.greeting("JAIRAM") The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc): A1.py person1 = { "name": "John", "age": 36, "country": "Norway" } import A1 a = A1.person1["age"] print(a)
  • 16.
    Lambda function A lambdafunction is a small anonymous function.A lambda function can take any number of arguments, but can only have one expression. lambda arguments : expression x = lambda b : b + 10 print(x(7)) x = lambda a, b : a *b print(x(4, 6)) x = lambda a, b, c : a + b + c print(x(3, 3, 2))
  • 17.
    Pass statement  Thepass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignroed.  The pass statement is generally used as a placeholder i.e. when the user does not know what code to write.  user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any code to execute.  user simply places pass there as empty code is not allowed in loops, function definitions, class definitions, or in if statements.  using pass statement user avoids this error. l =[‘u', ‘g', ‘j', ‘d'] for i in l: if(i ==‘u'): pass else: print(i)