我得到索引列表错误

时间:2017-03-02 04:02:14

标签: python

def calcDistance(x1, y1, x2, y2):
    distance = sqrt((x1-x2)**2 + (y1-y2)**2)

    return distance

def make_dict():
    return defaultdict(make_dict)

# Capture 1 input from the command line.
#    NOTE: sys.argv[0] is the name of the python file
#    Try "print sys.argv" (without the quotes) to see the sys.argv list
#    1 input --> the sys.argv list should have 2 elements.
if (len(sys.argv) == 2):
    print "\tOK.  1 command line argument was passed."

    # Now, we'll store the command line inputs to variables
    myFile = str(sys.argv[1])
else:
    print 'ERROR: You passed', len(sys.argv)-1, 'input parameters.'
    quit()  


# Create an empty list:
cities = []

# Create an empty dictionary to hold our (x,y) coordinate info:
myCoordinates = {}

# Open our file:
myFile = '%s.csv' % (myFile)
with open(myFile, 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in spamreader:
        # Only read rows that do NOT start with the "%" character.
        if (row[0][0] != '%'):
            # print row
            id = int(row[0])
            isHome = int(row[1])
            x = float(row[2])
            y = float(row[3])

            myCoordinates[id] = {'x': x, 'y': y}
            # print myCoordinates[id]['x']
            # print myCoordinates[id]['y']


            if (isHome == 1):
                # Store this id as the home city
                homeCity = id

            cities.append(id)           

print homeCity
print cities

# Create a TSP tour.
# VERSION 1 -- Using range() and for() loops:

myTour = []
for i in range(homeCity, len(cities)+1):
    myTour.append(i)
for i in range(1, homeCity+1):
    myTour.append(i)    
print myTour

# VERSION 2 -- Using only range()
'''
firstPart = range(homeCity, len(cities)+1)
secondPart = range(1, homeCity+1)
myTour = firstPart + secondPart
print myTour
'''

tau = defaultdict(make_dict)

for i in cities:
    # print "distance[%d][%d] = 0" % (i, i)
    tau[i][i] = 0
    for j in range(i+1, len(cities)+1):         
        # print "distance[%d][%d] > 0" % (i, j)
        tau[i][j] = calcDistance(myCoordinates[i]['x'], myCoordinates[i]['y'], myCoordinates[j]['x'], myCoordinates[j]['y'])
        # print "distance[%d][%d] = distance[%d][%d]" % (j, i, i, j)
        tau[j][i] = tau[i][j]


# FIXME -- Edit the code below...
# Calculate the total distance of our TSP solution:
i = myTour[i]
for myIndex in range(1, len(myTour)+1):
    j = myTour[myIndex]
    print j

根据距离计算成本的功能。需要修改。

def cost(rate,j):
    cost = rate * j
cost = cost(1000,j)
print cost

另外,我需要根据行进距离计算成本。 myIndex我收到错误list index out of range。我不知道到底发生了什么。 j就像计算的总距离一样。

1 个答案:

答案 0 :(得分:2)

python中的列表有0个索引。如果向列表中添加n个元素,则索引从0n-1。但是您正在运行从1n的循环。因此,它会出现list index out of range错误。

你应该这样做 -

for myIndex in range(0, len(myTour)):
    j = myTour[myIndex]
    print(j)

如果您收到list index out of range错误,请更改出现错误的循环,并使用从listrange(1,len(some_list)+1)的基于1的索引访问range(0,len(some_list))。或者你可以简单地写range(len(some_list))。当范围函数中没有传递起始值时,它默认从0开始。

要计算cost,请尝试此操作 -

for myIndex in range(0, len(myTour)):
    j = myTour[myIndex]
    cost = rate * j
    print(cost)

在开始循环之前设置rate的值。