Question

I have got 2 dev environment.

First I load the data into an array:

def loadData(filename):
    ins = open(filename, "r")
    array = []
    for line in ins:
        array.append(int(line))
   ins.close()
   return array 

In the first one this works without problem

tempLeftArray = array[:(length / 2)]
tempRightArray = array[(length / 2):]

But in the second environment I have to change the code to the following because I was getting the 'slice indices must be integers or none or have __index__ method':

tempLeftArray = array[:int(length / 2)]
tempRightArray = array[int(length / 2):]

Dev env I : windows 8.1, visual studio 2013, python 3.4.0

Dev env II(error one): windows 7, visual studio 2013, python 3.4.0

Any idea of the problem with the first? Why do I need to change the code adding the cast?

Was it helpful?

Solution

By default, division in Python 3, gives you floating number. And you cannot use a floating point number as a list's index.

You might want to use integer division in this case, like this

tempLeftArray  = array[:length // 2]
tempRightArray = array[length // 2:]

In Python 2.x,

print(4 / 2)
# 2
print(4.0 / 2)
# 2.0
print(4.0 // 2)
# 2.0
print(4 // 2)
# 2

In Python 3.4,

print(4 / 2)
# 2.0
print(4.0 / 2)
# 2.0
print(4.0 // 2)
# 2.0
print(4 // 2)
# 2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top