{{ message }}

Instantly share code, notes, and snippets.

# turbofart/tsp.py

Created Aug 22, 2012
Applying a genetic algorithm to the travelling salesman problem

### khadijahsaleh commented May 27, 2014

 may i use your code for my research? thank you very much if you allow me

### techniholic commented Dec 13, 2014

 I also feel happy to get a trial by this code, but I got an error with Anaconda (running with Python 2.7.8) at the initialization def init(self, x=None, y=None): I am totally newbie, but need to compare two meta-heuristics, so any help is very very welcome.

### zhirzh commented Dec 15, 2015

 original post can be found here

### evanbrown88 commented Jun 28, 2016 • edited

 I'm attempting to use this substituting geocodes for xy coordinates, and for a modified version of TSP where want the fastest tour but don't need to end up back at the starting node. Could this code be easily modified to achieve that?

### thiagomoretto commented Aug 12, 2016

 @evanbrown88 try adding a dummy node where the distance from/to starting node is 0 and the distance from/to for all other node (except the starting node one, of course) is infinity. Then, remove the dummy node.

### larsblumberg commented Aug 1, 2017

 @turbofart: The comment states `# Evolve population for 50 generations` but in fact, the population is evolving over 100 generations: `````` for i in range(0, 100): pop = ga.evolvePopulation(pop) ``````

### marleyas commented Aug 3, 2018

 Awesome solution! This is a very nice code.

### zurimokato commented Apr 18, 2019

 very nice

### timtreis commented May 3, 2019 • edited

 Probably no longer relevant to @evanbrown88, but for others trying to achieve the same result: Replace the getCity function (line 87,88) with the following: `````` def getCity(self, tourPosition="last"): if tourPosition != "last": return self.tour[tourPosition] else: return self.tour[-1] `````` and then in line 109 call: ``````destinationCity = self.getCity("last") ``````

### denizyigit commented Mar 3, 2020

 hello, what if we wanted to make the maximum distance as a 9000, what should i change? thank you

### pablobarrios1 commented Mar 30, 2020

Hi! Im getting an invalid syntax on line 272

# Initialize population

pop = Population (tourmanager, 50, True);
print "Initial distance: " + str(pop.getFittest().getDistance())

does anybody notice a mistake??

### Tayyab-Ilahi12 commented May 31, 2020

Hi! Im getting an invalid syntax on line 272

# Initialize population

pop = Population (tourmanager, 50, True);
print "Initial distance: " + str(pop.getFittest().getDistance())

does anybody notice a mistake??

Hi, let me correct you that it is because of the python version difference. It is probably written in 2.7 version while you are trying to run it on 3.x .
So the code will be
print ("Initial distance: " + str(pop.getFittest().getDistance()))
The parentheses are mandatory in Python 3.x