简体   繁体   English

算法反转次数(Python)

[英]Algorithm Number of Inversions (Python)

I'm attempting to complete a code assignment for the Algorithmic Toolbox offered by UC San Diego on Coursera. 我正在尝试为Coursera上的加州大学圣地亚哥分校提供的算法工具箱完成代码分配。 The assignment requires that you count the number of inversions in a sequence of numbers using a variation of the merge-sort algorithm. 分配要求您使用合并排序算法的变体来计算数字序列中的求反数。 For a better description of the problem: 为了更好地描述问题:

https://i.stack.imgur.com/CCBU8.jpg https://i.stack.imgur.com/CCBU8.jpg

I've used a variation of a merge-sort algorithm but am getting an incorrect answer and am frankly stuck. 我使用了合并排序算法的一种变体,但得到的答案不正确,并且坦率地说被卡住了。

Of note is that before explaining what I've attempted is that this code involves recursion which I admit I'm finding tricky to understand. 值得注意的是,在解释我尝试过的内容之前,这段代码涉及到递归,我承认我很难理解。

Mostly beyond the usual debugging I've tried to compare my code to known solutions to see where I may be going wrong. 在通常的调试之外,我试图将我的代码与已知的解决方案进行比较,以查看可能出问题的地方。 I could submit those as my solution but as far as I'm concerned that would be a cheat and I'd like to know where I've gone wrong with my code (and it's quite honestly driving me nuts). 我可以提交这些作为我的解决方案,但是就我所担心的那是个骗子,我想知道我的代码出了什么问题(老实说,这让我发疯了)。

#Uses python3
import sys

def merge_sort(A):
    if len(A) <= 1:
        return A, 0    
    else:
        middle = (len(A)//2)
        left, count_left = merge_sort(A[:middle])
        right, count_right = merge_sort(A[middle:])
        result, count_result = merge(left,right)
        return result, (count_left + count_right + count_result)

def merge(a,b):
    result = []
    count = 0
    while len(a) > 0 and len(b) > 0:
        if a[0] < b[0]:
            result.append(a[0])
            a.remove(a[0])
        else:
            #count = count + (len(a) - 1)
            result.append(b[0])
            b.remove(b[0])
            count += (len(a) - 1) #this is the important line
    if len(a) == 0:
        result = result + b
    else:
        result = result + a
    return result, count 

if __name__ == '__main__':
    input = sys.stdin.read()
    n, *a = list(map(int, input.split()))
    c = n * [0]
    array, inversion = merge_sort(a)
    print(array)
    print(inversion)

Listed below are two sample inputs I have been using in my testing: 下面列出了我在测试中一直使用的两个示例输入:

# ex 1:
3
3 1 2

Note that the first digit is the number of values in the sequence (required for the grader). 请注意,第一个数字是序列中的值的数量(对于平地机是必需的)。 Expected answer for inversions is 2. I'm getting 0 with my code. 求反演的答案是2。我的代码得到0。

# ex 2:
6
3 1 9 3 2 1

Expected answer for inversions is 9. I'm getting 4. 求反演的答案是9。我得到4。

Two corrections: 两项更正:

if a[0] <= b[0]: (note that a lot of internet examples and courses ignore or equal case, destroying intrinsic algorithm stability, this case also is important for correct inv. counting) if a[0] <= b[0]:请注意,许多Internet示例和课程都忽略or equal情况,从而破坏了算法的内在稳定性,此情况对于正确的Inv。计数也很重要)

and count += len(a) - we need to account that all items in a form inversions with current b item count += len(a) -我们需要考虑到当前ba形式反转中的所有项

def merge(a,b):
    result = []
    count = 0
    while len(a) > 0 and len(b) > 0:
        if a[0] <= b[0]:   
            result.append(a[0])
            a.remove(a[0])
        else:
            result.append(b[0])
            b.remove(b[0])
            count += len(a)
    if len(a) == 0:
        result = result + b
    else:
        result = result + a
    return result, count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM