0

我正在尝试创建一个 python 脚本来计算一组大学的最短行程。我需要添加一个起点,但我将自己迷惑到无法相信的地步。谁能帮我弄清楚从这里去哪里

    from Tkinter import *
import tkMessageBox, tkFileDialog
import json
import re
from urllib import urlopen
import math
class Application(Frame):
    collegelist = []
    collegelist1 = []
    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.pack()
        self.createWidgets()
    def createWidgets(self):
        self.top_frame = Frame(self)
        self.mid_frame = Frame(self)
        self.bot_frame = Frame(self, bg = 'red')
        self.top_frame.pack(side = 'top')
        self.mid_frame.pack(side = 'top')
        self.bot_frame.pack(side = 'top')
        #top frame

        self.label1 = Label(self.top_frame, text = "Your College Choices", bg ='red')
        self.label1.pack(side = 'left', padx='40', pady='0')
        self.label2 = Label(self.top_frame, text = "Your Tour Selections", bg ='green')
        self.label2.pack(side = 'right', padx='40')

        #mid frame
        self.mylist = Listbox(self.mid_frame,
                              bg = 'black',
                              fg = 'gold')
        self.mylist.pack(side='left')
        self.my_button1 = Button(self.mid_frame, text = '>>>', command=self.getlist)
        self.my_button2 = Button(self.mid_frame, text = '<<<', command=self.returnlist)
        self.my_button1.pack(side="left")
        self.my_button2.pack(side="left")
        self.mylist1 = Listbox(self.mid_frame, 
                              selectmode=DISABLED,
                              bg = 'black',
                              fg = 'gold')
        self.mylist1.pack(side='right')
        #bottom frame
        self.openbutton = Button(self.bot_frame, text='Open File', command=self.openfile, fg ='green')
        self.openbutton.pack(side='left')
        self.my_button = Button(self.bot_frame, text = 'Route', fg ='green', command=self.collegeroute)
        self.my_button.pack(side='left')
        self.quit_button = Button(self.bot_frame, text = 'Quit', 
                                  command = self.quit, fg = 'green')
        self.quit_button.pack(side='left')

    def openfile(self):
        filename = tkFileDialog.askopenfilename(title='Choose a file')
        if filename:
            clist = open(filename, "r")
        for line in clist.readlines():
            for i in line.split():
                self.collegelist.append(i)
        for college in self.collegelist:
            self.mylist.insert(1,college)
    def getlist(self):
    # get selected line index
        index = [int(x) for x in self.mylist.curselection()]
        print index
        for i in index:
            seltext = self.mylist.get(i)
            self.mylist.delete(i)
            self.mylist1.insert(1,seltext)
            self.collegelist1.append(seltext)
            print seltext
    def returnlist(self):
    # get selected line index
        index = [int(x) for x in self.mylist1.curselection()]
        for i in index:
            seltext = self.mylist1.get(i)
            self.mylist1.delete(i)
            seltext = seltext.strip()
            seltext = seltext.replace(' ', '')
            self.mylist.insert(0,seltext)
            self.collegelist1.remove(seltext)
    def collegeroute(self):
    # get selected line index
        global tuplist
        self.tuplist =[]
        for college in self.collegelist1:
            f = urlopen('http://graph.facebook.com/%s' % college) #load in the events
            d = json.load(f)
            longitude = d["location"]["longitude"]
            latitude = d["location"]["latitude"]
            name = d['name']
            self.tuplist.append((latitude, longitude))
        cartesian_matrix(self.tuplist)


def cartesian_matrix(coords):
    '''create a distance matrix for the city coords
      that uses straight line distance'''
    matrix={}
    for i,(x1,y1) in enumerate(coords):
        for j,(x2,y2) in enumerate(coords):
            dx,dy=x1-x2,y1-y2
            dist=math.sqrt(dx*dx + dy*dy)
            matrix[i,j]=dist
        tour_length(matrix,collegelist1)
        return matrix
def tour_length(matrix,tour):
    total=0
    num_cities=len(tour)
    print tour
    print num_cities
    for i in range(num_cities):
        j=(i+1)%num_cities
        city_i=tour[i]
        city_j=tour[j]
        total+=matrix[city_i,city_j]
    print total
def getRad(x):
    return float(x) * (math.pi/180.0)
def main():
    app = Application()
    app.master.title("My Application")
    app.mainloop()

if __name__ == "__main__":
    main()

无法让 tour_length 正常工作

4

2 回答 2

0

无法让 tour_length 正常工作

我看到的唯一明显的问题tour_length是你没有返回结果。在末尾添加以下内容:

return total

经过仔细检查,以下内容也很可疑:

    tour_length(matrix,collegelist1)
    return matrix

首先,它是错误的缩进。其次,您忽略了tour_length.

错误缩进可能是导致异常的原因(您在tour_length完全初始化之前调用matrix)。

于 2012-05-03T16:31:10.790 回答
0

您正在调用 tour_length 并在错误的地方从 cartesian_matrix 返回。你只做矩阵的一行,然后调用 tour_length 并返回。

于 2012-05-03T16:42:30.747 回答