[英]TypeError: slice indices must be integers or None or have an __index__ method
When running the code in IDLE gives the following error:在 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
CODE:-代码:-
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)
In 3.x, int/int gives a float. 在3.x中,int / int给出一个浮点数。 which is not an int.
这不是一个int。
>>> 3/2
1.5
so your line 15 所以你的第15行
half = len(m)/2
makes half a float. 让一半浮动。 What you need is a double slash
你需要的是双斜线
half = len(m)//2
to make half an int, as needed for its use in the slice in line 16. 根据需要在第16行的切片中使用半个int。
In your case, len(m)/2
returns a float
and line 16 is expecting an int
. 在你的情况下,
len(m)/2
返回一个float
,第16行期望一个int
。
You should type cast half to int
as the following: 您应该将cast half键入
int
,如下所示:
left = m[0:int(half)]
By only using / this will give you result in float you need to use // in order to give the result into integer.仅使用 / 这会给您带来浮点数,您需要使用 // 才能将结果提供给 integer。
This will resolve the error.这将解决错误。 It worked for me
它对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.