. Advertisement .
..3..
. Advertisement .
..4..
As title, I am getting typeerror: slice indices must be integers or none or have an __index__ method error. How can I fix it so the error goes away? Here is my program:
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)
When I operate it and I received the error text:
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
I appreciate any help from you.
The cause: The error is detected because your slice index is malformed, it must be in one of the following categories: integers/ none/ have an __index__ method
Solution:
You should change to an
int
as this way:In 3.x, int/int provides a floating. This is not an int.
so your line 15
Makes half a floating. You will need a double slash
To make half of an int, as necessary for its use in line 16