#to compute the recursive functions
def f(n):
if n==0:
return 3
else:
n=n-1
result=2*f(n)+3 #recursive call
return result
for num in range(1,5):
r=f(num)
print "The value of f(",num,") is",r #Prints the result for individual instance
#To compute the factorial of a given number using recursion
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1) #recursive function call
num=input("Enter a number whose factorial is to be found");
print "The factorial of",num,"is",factorial(num);
#To compute power using recursive algorithm
def power(a,n):
if n==0:
return 1
else:
return a*power(a,n-1) #recursive call algorithm
num=input("Enter the number");
p=input("Enter the power");
print "The value of",num,"to the power",p,"is",power(num,p);
#To compute gcd using modular recursion
def gcd(a,b):
if a==0:
return b
else:
return gcd(b%a,a) #recursive call
num1=input("Enter the first number")
num2=input("Enter the second number")
print "The gcd of",num1,",",num2,"is",gcd(num1,num2)
#To compute mpower function using recursion
def mpower(b,n,m):
if n==0:
return 1
else:
if n%2==0:
return ((mpower(b,n/2,m))**2) % m #recursive call
else:
return ((mpower(b,n/2,m)**2)%m*(b%m))%m #recursive call
number=input("Enter the number")
power=input("Enter the power")
modulo=input("Enter the modulo number");
print "The answer of mpower(",number,",",power,",",modulo,") is",mpower(number,power,modulo)
def msort2(x): #function for merge sort
if len(x) < 2:
return x
result = []
mid = int(len(x)/2) #divides the elements into halves
y = msort2(x[:mid])
z = msort2(x[mid:])
while (len(y) > 0) and (len(z) > 0):
if y[0] > z[0]:
result.append(z[0]) #merges to append the elements
z.pop(0)
else:
result.append(y[0])
y.pop(0)
result += y
result += z
return result
l=[]
r=[]
l=raw_input("enter the numbers to be merge sorted").split(",")
r=msort2(l)
print "Ther Merge sort is", r