日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python逆序数的程序_计算逆序数(归并法)程序问题 (Python)

發(fā)布時間:2024/7/5 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python逆序数的程序_计算逆序数(归并法)程序问题 (Python) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

計算一個tuple里面的逆序數(shù),用merge sort的辦法。我寫了以下代碼,但是每次統(tǒng)計的時候,count設(shè)置為全局變量了:

'''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))

如果只運(yùn)行一次,那么這個程序是對的。但是如果要運(yùn)行好幾次,由于count是global變量,計算逆序數(shù)時每次都會再上一次運(yùn)算的基礎(chǔ)上再加上這一次計算得到的逆序數(shù),造成了錯誤,怎么才能改掉這個bug?謝謝!

總結(jié)

以上是生活随笔為你收集整理的python逆序数的程序_计算逆序数(归并法)程序问题 (Python)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。