python逆序数的程序_计算逆序数(归并法)程序问题 (Python)
計算一個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?謝謝!
總結
以上是生活随笔為你收集整理的python逆序数的程序_计算逆序数(归并法)程序问题 (Python)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 北京林业大学计算机复试难度,北京林业大学
- 下一篇: 怎么做批注_BIM平台是什么?有何用?怎