python-3.x - 类型错误:切片索引必须是整数或无或具有 __index__ 方法

标签 python-3.x typeerror inversion

在 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)

最佳答案

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

>>> 3/2
1.5

所以你的第 15 行
        half = len(m)/2

使半个浮点数。你需要的是双斜线
        half = len(m)//2

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

关于python-3.x - 类型错误:切片索引必须是整数或无或具有 __index__ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28272322/

相关文章:

python-3.x - 类型错误:在运行基本 add.delay(1,2) 测试时无法 pickle 内存 View 对象

coq - 当目标是 Type 时,为什么 Coq 不允许反转、破坏等?

C算法反转1024x1024矩阵?

exists - 在 Coq : inversion of existential quantifier with multiple variables, 中使用一个命令?

python - 斐波那契在 Python 中很奇怪

Python 3.5 字符串格式 : How to add a thousands-separator and also right justify?

python - obj 必须是 type 的实例或子类型

node.js - Mongoose.js - TypeError : Model. deleteOne 不是函数

python-3.x - pkg_resources.resource_filename 未提取文件

javascript - 无法读取 Javascript 文件(非脚本标记)中 null 的属性(读取 'addEventListener' )