简体   繁体   English

计算数组中的反转次数(python代码)

[英]Count number of inversions in an array (python code)

So I'm reading through this code, it's going through a file containing 10,000 integers in some random order(no repetition), and counting the number of inversions.所以我正在阅读这段代码,它正在浏览一个包含 10,000 个随机顺序(无重复)的整数的文件,并计算反转的次数。 I'm not understanding this code fully, I have couple questions: First I suppose this is keep breaking the array into left and right, until the length is 1. When both left array and right array have length 1, what do we do and count here?(I might be completely misunderstanding this code please correct me).我没有完全理解这段代码,我有几个问题:首先我想这是不断地将数组分成左右,直到长度为 1。当左数组和右数组的长度都为 1 时,我们该怎么办?在这里算吗?(我可能完全误解了这段代码,请纠正我)。 And where does the "midsection" element go each time? “中段”元素 go 每次都在哪里? From what I see every time this element does not belong to either the right or the left array.从我每次看到的情况来看,这个元素既不属于右数组也不属于左数组。 Last question is that the line "count += (len(a)-i)" is correct only if both the left and right array are sorted(ordered) already, but I do not see where this sorting process is.最后一个问题是,“count += (len(a)-i)”行只有在左右数组都已经排序(排序)时才是正确的,但我看不到这个排序过程在哪里。 Here is the code:这是代码:

from pathlib import Path
file_path = Path("c:/Users/Lyra/Desktop/Algorithm/")

inFile = open(file_path / "IntegerArray.txt", 'r')

with inFile as f:
    numList = [int(integers.strip()) for integers in f.readlines()]
    
count = 0

def inversionsCount(x):
    global count
    midsection = len(x) // 2
    leftArray = x[:midsection]
    rightArray = x[midsection:]
    if len(x) > 1:
        # Divid and conquer with recursive calls
        # to left and right arrays similar to
        # merge sort algorithm
        inversionsCount(leftArray)
        inversionsCount(rightArray)
        
        # Merge sorted sub-arrays and keep
        # count of split inversions
        i, j = 0, 0
        a = leftArray; b = rightArray
        for k in range(len(a) + len(b) + 1):
            if a[i] <= b[j]:
                x[k] = a[i]
                i += 1
                if i == len(a) and j != len(b):
                    while j != len(b):
                        k +=1
                        x[k] = b[j]
                        j += 1
                    break
            elif a[i] > b[j]:
                x[k] = b[j]
                count += (len(a) - i)
                j += 1
                if j == len(b) and i != len(a):
                    while i != len(a):
                        k+= 1
                        x[k] = a[i]
                        i += 1                    
                    break   
    return x
# call function and output number of inversions
inversionsCount(numList)
print (count)

I know I've asked a lot question but I'm really confused right now, and thanks in advance!我知道我问了很多问题,但我现在真的很困惑,提前谢谢!

There is no "midsection" element.没有“中段”元素。 midsection is just an index in the middle of x leftArray = x[:midsection] and rightArray = x[midsection:] will together copy all elements in x and if length is odd the middle element will end up in rightArray . midsection只是x leftArray = x[:midsection] 和 rightArray = x[midsection:] 中间的索引,将一起复制 x 中的所有元素,如果长度为奇数,则中间元素将在rightArray中结束。

The sorting is made by the function itself by altering the elements in the passed argument x .排序由 function 本身通过更改传递的参数x中的元素进行。 A list is mutable and passed to the function as a reference.列表是可变的,并作为参考传递给 function。 So every x[n] = something is affecting the passed list argument and therefore also affecting corresponding variable in the calling scope.所以每个x[n] = something都会影响传递的列表参数,因此也会影响调用 scope 中的相应变量。 That means after inversionsCount(leftArray) leftArray is sorted.这意味着在inversionsCount(leftArray) leftArray 被排序之后。

If you run a smaller list like inversionsCount([6,0,3,1,2,5,4]) and put in some print(interesting_varable) in the code.如果您运行一个较小的列表,例如inversionsCount([6,0,3,1,2,5,4])并在代码中放入一些print(interesting_varable) Then you may find out what happens.然后你可能会发现发生了什么。

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

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