1

So I'm toying with the traveling salesman problem, and I have the following code to create random instances of the TSP. (tangent, does TSP stand for Traveling Salesman Problem, or Traveling Sales Person? in otherwords, is TSP problem redundant? But back to the main problem...)

import numpy as np
import random
import copy
def generate_TSP(num_nodes, symmetric=False, triangleInequality=False, rangeStart=0.0, rangeEnd=100.0, dropEdges=0.0):
    tsp = [ [0]*num_nodes ] *num_nodes
    for i in range(num_nodes):
        for j in range(num_nodes):
            if i == j:
                tsp[i][j] = np.inf
                continue
            else:
                tsp[i][j] = round(random.uniform(rangeStart, rangeEnd), 2)
            if symmetric:
                tsp[j][i] = copy.deepcopy(tsp[i][j])
            if np.random.rand() < dropEdges:
                tsp[i][j] = np.inf
    return tsp

The Problem is that when I call generate_TSP(4, symmetric=True) it doesn't return a symmetric matrix. Instead, every row in the matrix is the same as the last row. I figured this has something to do with python assigning by reference instead of value or something like that, so I've tried it with the deep copy and without. Forgive my C++ ways, but I don't quite understand python's reference vs value system.

Here's an example of the output

josephfs@DESKTOP-IH0RR0A:~/cs312/TSP$ python3
Python 3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0] on linux 
Type "help", "copyright", "credits" or "license" for more information.
>>> import TSP
>>> print(TSP.generate_TSP(4, symmetric=True))
[[91.87, 15.11, 52.67, inf], [91.87, 15.11, 52.67, inf], [91.87, 15.11, 52.67, inf], [91.87, 15.11, 52.67, inf]]

0 Answers0