Python mergesort:在没有多个函数调用的情况下计算反转

时间:2015-07-06 03:48:03

标签: python algorithm mergesort

我正在尝试计算Python中以下mergesort算法实现中发生的反转次数,它只使用一个简单的函数定义(即,mergesort有一个def语句)。为清晰起见,我已对此mergesort算法进行了评论:

import csv

def safeint(val):
   try:
      return int(val)
   except ValueError:
      return val

list = []
with open('file.txt') as f:
    lines = csv.reader(f, delimiter='\n')
    for line in lines:
        line = map(safeint, line)
        list.append(line)

def mergesort(list):
    mid = len(list)//2  #MIDPOINT FOR DIVISION
    lft, rgt = list[:mid], list[mid:]
    if len(lft) > 1: lft = mergesort(lft)   #SORT BY HALVES
    if len(rgt) > 1: rgt = mergesort(rgt)
    res = []
    while lft and rgt:  #NEITHER HALF IS EMPTY
        if lft[-1] >=rgt[-1]:   #lft HAS GREATEST LAST VALUE
            res.append(lft.pop())   #APPEND IT
        else:   #rgt HAS GREATEST LAST VALUE
            res.append(rgt.pop())   #APPEND IT
    res.reverse()   #RESULT IS BACKWARD
    return (lft or rgt) + res   #ALSO ADD THE REMAINDER

print mergesort(list)

我的输入文件.txt的格式为:

1
2
3
4
5
55
60
82
19

我的输出是(正如预期的那样):

[[1], [2], [3], [4], [5], [19], [55], [60], [82]]

是否可以加入"反转计算器"进入此代码而不添加额外的def语句?已经有很多在线多功能示例,例如:Counting Inversions Using Merge Sorthttps://codereview.stackexchange.com/questions/12922/inversion-count-using-merge-sort

我们能比这更简洁吗?

1 个答案:

答案 0 :(得分:0)

Python-ish伪代码:

while lft and rgt:  #NEITHER HALF IS EMPTY
    if lft[-1] >=rgt[-1]:   #lft HAS GREATEST LAST VALUE
        # if the last of lft is greater than the last of rgt (which is sorted),
        # then it is also greater than everything before the last element of rgt, 
        # so it generates as many inversions as the remaining elements in rgt
        inversions += len(rgt)
        res.append(lft.pop())   #APPEND IT
    else:   #rgt HAS GREATEST LAST VALUE
        res.append(rgt.pop())   #APPEND IT

其中inversions是一个全局变量,一个参数(例如,使它成为一个1元素列表,因此它是可变的)或者你返回的东西(确保返回两半中的反转总和)在那种情况下)。