它是一个函数,用于计算列表中的倒数并返回计数。你知道吗
def count_inversion(sequence):
count = 0
def merge_count_inversion(L):
if len(L) > 1:
# split them.
mid = len(L) // 2
leftL = L[:mid]
rightL = L[mid:]
merge_count_inversion(leftL)
merge_count_inversion(rightL)
# merge them.
i = j = k = 0
while i < len(leftL) and j < len(rightL):
if leftL[i] < rightL[j]:
L[k] = leftL[i]
i += 1
else:# no equal situation.
L[k] = rightL[j]
j += 1
count+=j
k += 1
while i < len(leftL):#all right is inversion.
count+=j
L[k] = leftL[i]
i += 1
k += 1
while j < len(rightL):
L[k] = rightL[j]
j += 1
k += 1
merge_count_inversion(list(sequence))
return count
我使用一个封闭的计数,我希望它可以保存所有合并进程的总数。但是,它将是一个局部变量。你知道吗
UnboundLocalError: local variable 'count' referenced before assignment
我想我失去了一些递归和python变量范围的概念。请告诉我哪里错了,怎么解决?你知道吗
先谢谢你。你知道吗
这个消息意味着
count
不是merge_count_inversion
的局部变量,您在这里使用了count += j
。您应该在函数merge_count_inversion
中移动count = 0
。你知道吗使用Python 3
相关问题 更多 >
编程相关推荐