# [12-Nati] ฝึกทำโจทย์ Data Structures and Algorithms – Recursion/Array/Stack/Queue/Linked Lists

R4.6 Describe a recursive function for computing the nth Harmonic number, Hn = Σni =1 1/i.

ตัวอย่างโค๊ด

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))

C4.12 Give a recursive algorithm to compute the product of two positive integers,
m and n, using only addition and subtraction.

ตัวอย่างโค๊ด

def product(m, n):
sign = (n >= 0)
n = abs(n)
if n > 0:
result = m + product(m, n-1)
else:
result = 0
return result if sign else -result

if __name__ == ‘__main__’:
for x in range(5):
print(‘the product of {0} and {1} is {2}’
.format(x, x+1, product(x, x+1)))
print(‘the product of {0} and {1} is {2}’
.format(-x, x+1, product(-x, x+1)))

P5.33 Write a Python program for a matrix class that can add and multiply twodimensional arrays of numbers, assuming the dimensions agree appropriately for the operation.

นาย นที ไทยธรรม 1590901581

•
•
•
•
•
•
at GlurGeek.Com