计算一个tuple里面的逆序数,用merge sort的办法。我写了以下代码,但是每次统计的时候,count设置为全局变量了:
'''Count inversion
Input: a sequence as tuple of integers
Output: The inversion number as an integer'''
#Merge Sort Method
def merge(ListA, ListB):
"""key subroutine
function: merge 2 sorted lists"""
newlist = []
while ListA and ListB:
if ListA[0] > ListB[0]:
newlist.append(ListB[0])
ListB = ListB[1:]
global count
count += len(ListA)
else:
newlist.append(ListA[0])
ListA = ListA[1:]
if ListA:
newlist = newlist + ListA
elif ListB:
newlist = newlist + ListB
return newlist
def merge_sort(A):
"""input: A(a list) the length of A can be odd
output: sorted list
"""
#base case: If n = 1, done
if len(A) == 1:
return A
#recursion: divide into two parts
else:#A[1, (n/2)] A[(n/2)+1, n] merge 2 lists
middle = len(A)/2 #if len(A) is odd number, in Python it will return the lower int of the result
A = merge(merge_sort(A[:middle]), merge_sort(A[middle:]))
return A
count = 0
def count_inversion(sequence):
sequence = list(sequence)
merge_sort(sequence)
return count
print count_inversion((1, 2, 5, 3, 4, 7, 6))
print count_inversion((0, 1, 2, 3))
print count_inversion((99, -99))
print count_inversion((5, 3, 2, 1, 0))
如果只运行一次,那么这个程序是对的。但是如果要运行好几次,由于count是global变量,计算逆序数时每次都会再上一次运算的基础上再加上这一次计算得到的逆序数,造成了错误,怎么才能改掉这个bug?谢谢!