Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: slice indices must be integers or None or have an __index__ method

When running the code in IDLE gives the following error:

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)
like image 478
jarvis Avatar asked Feb 02 '15 06:02

jarvis


1 Answers

In 3.x, int/int gives a float. which is not an int.

>>> 3/2
1.5

so your line 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.

like image 181
Terry Jan Reedy Avatar answered Oct 21 '22 16:10

Terry Jan Reedy