13

在 IDLE 中运行代码时会出现以下错误:

Traceback (most recent call last):   File "C:/Python34/inversion3.py",
line 44, in <module>
    nInversions.inversionMergeSort(m)   File "C:/Python34/inversion3.py", line 16, in inversionMergeSort
     left = m[0:half] TypeError: slice indices must be integers or None or have an __index__ method

代码:-

from collections import deque

m = []
f = open("IntegerArray.txt")
for line in f:
    m.append(int(line))

class InversionCount:

    def __init__(self, n):
        self.n = n
    def inversionMergeSort(self, m):
        if len(m) <= 1:
            return m
        half = len(m)/2
        left = m[0:half]
        right = m[half:]
        left = self.inversionMergeSort(left)
        right = self.inversionMergeSort(right)
        return self.inversionSort(left, right)

    def inversionSort(self, left, right):
        leftQueue = deque(i for i in left)
        rightQueue = deque(j for j in right)
        orderedList = []
        while len(leftQueue) > 0 or len(rightQueue) > 0:
            if len(leftQueue) > 0 and len(rightQueue) > 0:
                if leftQueue[0] <= rightQueue[0]:
                    orderedList.append(leftQueue[0])
                    leftQueue.popleft()
                else:
                    orderedList.append(rightQueue[0])
                    self.n += len(leftQueue)
                    rightQueue.popleft()
            elif len(leftQueue) > 0:
                orderedList.append(leftQueue[0])
                leftQueue.popleft()
            elif len(rightQueue) > 0:
                orderedList.append(rightQueue[0])
                rightQueue.popleft()
        return orderedList

nInversions = InversionCount(0)
nInversions.inversionMergeSort(m)
print (nInversions.n)
4

3 回答 3

39

在 3.x 中,int/int 给出一个浮点数。这不是一个整数。

>>> 3/2
1.5

所以你的第 15 行

        half = len(m)/2

使半个浮动。你需要的是一个双斜杠

        half = len(m)//2

根据需要在第 16 行的切片中使用它来制作半个 int。

于 2015-02-02T07:19:12.877 回答
7

在您的情况下,len(m)/2返回 afloat并且第 16 行期待 a int

您应该输入 cast half toint如下:

left = m[0:int(half)]
于 2017-08-22T23:16:40.563 回答
0

仅使用 / 这将为您提供浮点数,您需要使用 // 以将结果转换为整数。

这将解决错误。它对我有用

于 2022-02-28T13:25:37.333 回答