数据结构与算法python语言实现-第四章答案
4.1
def findmax(S, index=0):
if index == len(S) - 1:
return S[index]
max=findmax(S, index + 1)
if max > S[index]:
return max
else:
return S[index]
print(findmax([2, 5, 6, 9, 2, 4, 56, 78, 213, 456, 2, 1, 23]))
时间复杂度为O(n) 空间复杂度为O(n)
4.6
def harmonic_number(n):
if n==1:
return 1
return 1/n+harmonic_number(n-1)
print(harmonic_number(2))
print(harmonic_number(3))
4.7
def trans(st, index=0):
if index == len(st) - 1:
return int(st[0])
return int(st[len(st) - 1 - index]) + 10 * trans(st, index + 1)
print(trans('1356432'))
#字符串的*是加倍,要先转为数字才能乘。
4.8
def sum(A):
if len(A) == 1:
return A[0]
B=[0]*int(len(A)/2)
for j in range(len(B)):
B[j] = A[2*j] + A[2*j + 1]
return sum(B)
print(sum([1, 2, 4, 5]))
内循环操作数为n/2,调用情况为len(A)/2 -> len(A)/4 -> …-> len(A)/2**r,即 n/2* *r<1,r>logn,r=floor(logn)+1,复杂度
为logn,所以总的复杂度为O(nlogn)
4.9
def minmax(st, index=0):
if index == len(st) - 1:
return st[index], st[index]
min, max = minmax(st, index + 1)
if min < st[index] and max < st[index]:
return min, st[index]
elif min < st[index] and max > st[index]:
return min, max
else:
return st[index], max
print(minmax([11, 3, 2, 52]))
4.10
def integer(num,index=0):
if num<1:
return index-1
return integer(num//2,index+1)
print(integer(14))
print(integer(16))
4.11
def unique(st,index=0):
if index==len(st)-1:
return True
if unique(st, index+1):
for j in range(index+1,len(st)):
if st[index]==st[j]:
return False
return True
else:
return False
print(unique([1,2,3,13,65]))
print(unique([1,2,3,13,2,65]))
4.12
#m加n次
def mul(m,n):
if n==1:
return m
return m+mul(m,n-1)
print(mul(3,5))
4.14
def move(n, a, buffer, c):
if(n == 1):
print(a,"->",c)
return
move(n-1, a, c, buffer)
move(1, a, buffer, c)
move(n-1, buffer, a, c)
move(3, "a", "b", "c")