Chapter 6 Recursion Solutions
Chapter 6 Recursion Solutions
CHAPTER 6
TYPE A SOLUTIONS
Answer 12 In the give code, only n>0 is the recursive case and rest is the base cases or
terminating cases.
TYPE B SOLUTIONS
Answer 1 (c) compute(3) = compute(2) + 2*3-1
Answer 2
(b)
def compute(N):
if N == 1:
return 1
else:
return compute(N-1)+2*N-1
Answer 3 (D) 6
Reason – There will be 6 invocations as follows –
1. The first call is compute(5)
2. Next individual call to compute(N) = compute(N-1)+2*N-1 for N from 5 to 1.
Answer 4
(a)
15
12
9
6
3
Finally
(b)
Infinite loop
(c)
10
8
6
4
2
Finally
(d)
Infinite loop
Page 1 of 5
Answer 5 Nothing will be displayed on the output screen as absence of print() function.
Hence, no output. If the print function is included or the result of the return statement
is stored in a variable and its value is printed, then the result will be printed as 32.
Answer 6 True
Answer 7 Yes, the last condition will make an infinite recursion to occur. If any number
odd and greater than 1 is passed than the code will enter in infinite recursion. Hence, in
the case of check(3) an infinite loop will occur.
Answer 8 Output:
(a) 12 6 3 1 1 2 4 2 1 -3
(b) 10 5 2 1 3 1 1 1
(c) 7 3 1 1 2 -2
Answer 9 This code will act as infinite recursion as the p=p-1 will never going to run
as of positioning.
recur(5)
Page 2 of 5
TYPE C SOLUTIONS
Answer 1
def prime(n, i=2):
if(n<=2):
return True if(n==2) else False
if(n%i==0):
return False
if(i*i>n):
return True
return prime(n,i+1)
print(prime(15))
print(prime(25))
print(prime(23))
Output :
False
False
True
Answer 2
def prod(a,b,p=0):
p+=a
if b==1:
return p
return prod(a,b-1,p)
print(prod(7,5))
print(prod(8,9))
Output :
35
72
Answer 3
def generate_hail_seq(n):
lnum=[n]
while n!=1:
if(n%2)==0:
n=n//2
lnum.append(n)
else:
n=(n*3)+1
lnum.append(n)
return lnum
Page 3 of 5
print(generate_hail_seq(10))
print(generate_hail_seq(7))
print(generate_hail_seq(8))
Output:
[10, 5, 16, 8, 4, 2, 1]
[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
[8, 4, 2, 1]
Answer 4
def sum_sq_digits(n):
ans=0
for i in str(n):
ans+=int(i)*int(i)
return ans
def is_happy(n):
if len(str(n))==1:
if n==1:
return 'It is a Happy Number'
else:
return 'It is not a happy number'
else:
n=sum_sq_digits(n)
return is_happy(n)
print(is_happy(12))
print(is_happy(100))
Output:
It is not a happy number
It is a Happy Number
Answer 5
def adm_search(arr, x, f=0, l=10):
if l >= f:
mid = (f+l)//2
if arr[mid] == x: # Found
return mid
elif arr[mid] > x:
return adm_search(arr, x, f, mid-1) # search below
else:
return adm_search(arr, x, mid+1, l) # search above
else:
return 'Not Found'
Page 4 of 5
# adm list can be of any number
adm = [456, 467, 489, 500, 546, 567, 588, 599, 600, 612, 613]
print(adm_search(adm, 234))
print(adm_search(adm, 500))
Output:
Not Found
3
Page 5 of 5