Professional Documents
Culture Documents
Lab Solution
Lab Solution
recursion.
1,1,2,3,5,8,13,21,34,55,89….
Ex:
fibonacci(7)->13
fibonacci(10)->55
********************************************************************************
Q1 : Write a Python program to get the sum of a non-negative integer.
Ex:
sumDigits(345) -> 12
sumDigits(45) -> 9
Sol:
def sumDigits(n):
if n == 0:
return 0
else:
return n % 10 + sumDigits(int(n / 10))
print(sumDigits(345))
print(sumDigits(45))
********************************************************************************
harmonic_sum(7)->2.5928571428571425
harmonic_sum(4)->2.083333333333333
Sol:
def harmonic_sum(n):
if n < 2:
return 1
else:
return 1 / n + (harmonic_sum(n - 1))
print(harmonic_sum(7))
print(harmonic_sum(4))
********************************************************************************
Q3: Write a Python program to calculate the value of 'a' to the power 'b'.
Ex:
power(3,4) -> 81
power(100,0) -> 1
Sol:
def power(a,b):
if b==0:
return 1
elif a==0:
return 0
elif b==1:
return a
else:
return a*power(a,b-1)
print(power(3,4))
********************************************************************************
Ex:
Recurgcd(12,14)->2
Recurgcd(21,11)->1
Sol:
def Recurgcd(a, b):
low = min(a, b)
high = max(a, b)
if low == 0:
return high
elif low == 1:
return 1
else:
return Recurgcd(low, high%low)
print(Recurgcd(12,14))
********************************************************************************
print(sum_series(6))
print(sum_series(10))
*********************************************************************************