Skip to main content
 首页 » 编程设计

python之我正在从列表错误中获取索引

2024年10月01日7leader

<分区>

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 就像计算的总距离。