I'm trying to write a function to calculate an approximate traveling salesman route through a list of cities using the nearest neighbor algorithm, starting from the first city listed. However, each time I run it I get IndexError: list index out of range
.
In debugging the error, I found that the value of index
stays the same from one loop iteration to the next, rather than changing. When it's time to append, the code checks the if not in
condition; since it's False
, it adds 1
to i
and moves to the next iteration of the loop. Once it reaches a higher number than exists in the array, it gives me the error.
So my problem is, why does execution not enter the first if not in
block? It seems like the code ignores it.
For my actual problem I'm reading in a file of 317 cities, each of which has an index and two coordinates. Here's a shorter sample list of cities for testing:
Nodelist = [
(1, 63, 71),
(2, 94, 71),
(3, 142, 370),
(4, 173, 1276),
(5, 205, 1213),
(6, 213, 69),
(7, 244, 69),
(8, 276, 630),
(9, 283, 732),
(10, 362, 69),
]
Here is the function's code:
def Nearest(Nodelist,Distance,index):
Time_Calculation = time.time()
Newarray=[]
Newarray.append(Nodelist[0])
for i in range(0,len(Nodelist)):
for j in range(1,len(Nodelist)):
if (Nodelist[j] not in Newarray):
DisEquation = math.sqrt(pow(Nodelist[j][1]-Newarray[i][1],2)+pow(Nodelist[j][2]-Newarray[i][2],2))
if Distance==0:
Distance=DisEquation
if Distance > DisEquation:
index=j
Distance=DisEquation
if(Nodelist[index] not in Newarray):
Newarray.append(Nodelist[index])
Distance=0
print (time.time() - Time_Calculation)
return Newarray
Code that calls it:
NearestMethodArr=Nearest(Cities,b,index)
print(NearestMethodArr)
print(len(NearestMethodArr))
The print
statements should produce:
[(1, 63, 71), (2, 94, 71), (6, 213, 69), (7, 244, 69), (10, 362, 69), (3, 142, 370), (8, 276, 630), (9, 283, 732), (5, 205, 1213), (4, 173, 1276)]
10