Chapter 10 : Recursion

Example: 1, Page No.: 5.67

In [7]:
#Factorial of an integer number.

def rec(x):
    f=0
    if x==1:
        return (1)
    else:
        f=x*rec(x-1)
        return(f)

a=input("Enter the number:")
print "The Factorial value of %d:"%a,rec(a)
Enter the number:5
The Factorial value of 5: 120

Example: 2, Page No.:5.67

In [16]:
#Program to read characters and print reversely using recursion.

def reverse(c):
    if len(c)<=0:
        return c
    return reverse(c[1:])+c[0]

c=raw_input("Enter the Line of Text...")
print reverse(c)
Enter the Line of Text...munilak
kalinum

Example: 3, Page No.:5.68

In [37]:
#concept of recursion

def add(pk, pm):
    if pm==0:
        return pk
    else:
        return(1+add(pk,pm-1))
    
    
k=70
m=20

i=add(k,m)

print "The Value of addition is %d"%i
The Value of addition is 90

Example: 4, Page No:5.70

In [1]:
#Tower of honoi
n=int(raw_input("How many Disks ...\n"))

def honoi(n,fro,to,t):
    if(n>0):
        honoi(n-1,fro,t,to)
        print "Move disk %d from %c to %c\n"%(n,fro,to)
        honoi(n-1,t,to,fro)
        
fro='L'
to='R'
t='C'
        
honoi(n,fro,to,t)
            
How many Disks ...
3
Move disk 1 from L to R

Move disk 2 from L to C

Move disk 1 from R to C

Move disk 3 from L to R

Move disk 1 from C to L

Move disk 2 from C to R

Move disk 1 from L to R

Case Study: 1, Page No. : 5.76

In [15]:
#user defined function that computes 'x' raised to the power 'y'

import math 

x,y=input("Enter the Values of X and Y ")

print "%d to the power of %d is ... "%(x,y),math.pow(x,y)
Enter the Values of X and Y 10,2
10 to the power of 2 is ...  100.0

Case Study: 2, page No.5.76

In [34]:
#nesting of function

def ratio(x,y,z):
    
    def diff(m,n):
        if(m!=n):
            return(1)
        else:
            return(0)
    
    diff(y,z)
    if diff(y,z):
       return(x/(y-z))
    else:
       return(0)
        
    
x,y,z=input("Enter the values of X,Y,Z: ")

    
print "Ratio is..%f\n"%ratio(x,y,z)
Enter the values of X,Y,Z: 10,10,5
Ratio is..2.000000

Case Study: 3, Page No. 5.78

In [39]:
#Demonstration of Global Variable

a=39               #Global Variable
print "A... %d\n"%a

def f1():
    global a
    a=a+10
    return a

def f2():
    global a
    a=a+20
    return a

def f3():
    global a
    a=a+30
    return a



print "A...%d\n"%f1()
print "A...%d\n"%f2()
print "A...%d\n"%f3()
A... 39

A...49

A...69

A...99