简体   繁体   English

搜索反转时打印

[英]Printing when Searching for Inversions

I'm trying to implement an algorithm that searches for inversions. 我正在尝试实现一种搜索反演的算法。 I'm having trouble printing the updated global variable c . 我在打印更新的全局变量c遇到问题。 Where should I put the print statement? 我应该把打印报表放在哪里?

I'd prefer using a method that involves the boilerplate(?) because I'm going to run a timing function to test the running time later. 我更喜欢使用涉及样板(?)的方法,因为我将运行计时功能以稍后测试运行时间。 If I could only get it to print the result (8). 如果我只能得到它来打印结果(8)。 If I put it inside the merge function(before return C) it returns all the values up to 8. I want it to just print c at the end of the process. 如果我将其放在合并函数中(在返回C之前),它将返回所有值,直到8。我希望它仅在过程结束时打印c。

c=0
def merge(A,B):

    global c
    C=[]
    lenA=len(A)
    lenB=len(B)
    i=0
    j=0
    while i<lenA and j<lenB:
        if A[i]<=B[j]:
            C.append(A[i])
            i=i+1
        else:
            c=c+len(A)-i 
            C.append(B[j])
            j=j+1
    if i==lenA:  #A get to the end
        C.extend(B[j:])
    else:
        C.extend(A[i:])
    return C


def inversions_divide_conquer(Array):
    N=len(Array)
    if N>1:
        S1=inversions_divide_conquer(Array[0:N/2])
        S2=inversions_divide_conquer(Array[N/2:])
        return merge(S1,S2)
    else:
        return Array



if __name__ == '__main__':

    inversions_divide_conquer([4, 1, 3, 2, 9, 1])
M = len(stuff)
def inversions_divide_conquer(Array):
    N=len(Array)
    if N>1:
        S1=inversions_divide_conquer(Array[0:N/2])
        S2=inversions_divide_conquer(Array[N/2:])
        if N == M:
            print c
        return merge(S1,S2)
    else:
        return Array

inversions_divide_conquer(stuff)

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

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