count = 0
def merge(L1,L2):
m = len(L1)
n = len(L2)
i = 0
j = 0
c = []
k = 0
while i<m and j<n:
if L1[i]<=L2[j]:
c.append(L1[i])
i += 1
else:
c.append(L2[j])
j += 1
while i<m:
c.append(L1[i])
i += 1
while j<n:
c.append(L2[j])
j += 1
return c
def subordinates(L):
length = len(L)
global count
count = count + 1
if length <= 1:
return L
L1 = subordinates(L[:length//2])
L2 = subordinates(L[length//2:])
sorted_list = merge(L1,L2)
return sorted_list
x = [10, 33, 45, 67, 92, 100, 5, 99, 105]
print(subordinates(x))
上面的代码对 x 进行了正确排序并返回列表。
但是当我跑步时: return (sorted_list,count) 它不允许我返回计数。它给出了类型错误:
类型错误:'<=' not supported between instances of 'int' and 'list'
您尝试返回一个元组,但在分配给 L1 和 L2 时没有考虑到这一点。
您可以按如下方式补救:
count = 0
def merge(L1, L2):
m = len(L1)
n = len(L2)
i = 0
j = 0
c = []
k = 0
while i < m and j < n:
if L1[i] <= L2[j]:
c.append(L1[i])
i += 1
else:
c.append(L2[j])
j += 1
while i < m:
c.append(L1[i])
i += 1
while j < n:
c.append(L2[j])
j += 1
return c
def subordinates(L):
length = len(L)
global count
count = count + 1
if length <= 1:
return L, 0
L1, _ = subordinates(L[: length // 2])
L2, _ = subordinates(L[length // 2 :])
sorted_list = merge(L1, L2)
return sorted_list, count
x = [10, 33, 45, 67, 92, 100, 5, 99, 105]
print(subordinates(x))
输出:
([5, 10, 33, 45, 67, 92, 99, 100, 105], 17)