It's a function to count inversion in a list and return the count.
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
I use a enclosed count and I hope it can save the total number for all merge procession. However, it will be a local variable.
UnboundLocalError: local variable 'count' referenced before assignment
I think I lose some concepts of recursion and the variable scope of python. Please tell me where I am wrong and how to fix it?
Thank you in advance.