变量是相同的但不应该是?蟒蛇

问题描述 投票:0回答:1

我有一些麻烦,变量设置为相同,当他们不应该,我无法弄清楚他们为什么这样做。在我的情况下,LCT和MCT被设置为函数中生成的最后一个路由,但是我只在路由分别小于或大于最低成本或最多成本时设置它们。基本上,我正在创建一个从0到13的整数的伪随机列表作为城市标签,并使用i-by-j数组查找找到它们之间的距离,其中值表示从城市i到城市的距离学家这是我的TSP项目的一部分。以下是一些参考代码:

import random

def distance(x1, y1, x2, y2):
     """
     Finds the distance between two points with coordinates (x1, y1) and (x2, y2)
     :param x1: x-coordinate of first point
     :type x1: float or int
     :param y1: y-coordinate of first point
     :type y1: float or int
     :param x2: x-coordinate of second point
     :type x2: float or int
     :param y2: y-coordinate of second point
     :type y2: float or int
     :return: distance between two points
     :rtype: float
     """
     return (((x2-x1)**2) + ((y2-y1)**2)) ** 0.5

def shuffle(idxs):
    """
    Performs random swaps n times with random seeded generator
    :param idxs: Set of items to choose from
    :type idxs: list, tuple, or dict
    :return: modified idxs
    :rtype modified idxs: type(idxs)
    """
    n = 32
    for k in range(n):
        random.seed()
        a, b = random.randint(0, 13), random.randint(0, 13)
        swap(idxs, a, b)
        # print(idxs)
    return idxs


def swap(mylist, a, b):
    """
    Swaps two values
    :param mylist: order of things to choose from
    :type mylist: list, tuple, or dict
    :param a: first index
    :type a: list/tuple: int; dict: key
    :param b: second index
    :type b: list/tuple: int; dict: key
    :return: none; edits items in place
    """
    temp = mylist[a]
    mylist[a] = mylist[b]
    mylist[b] = temp

mat = [[0.430796749, 0.660341257],
      [0.869607109, 0.145710154],
      [0.272249997, 0.281035268],
      [0.310050105, 0.717362826],
      [0.847481151, 0.505130257],
      [0.054921944, 0.597324847],
      [0.565507064, 0.578311901],
      [0.578311901, 0.636552793],
      [0.170565332, 0.160881561],
      [0.800726237, 0.384045138],
      [0.622627218, 0.957622127],
      [0.608021461, 0.736718151],
      [0.628737267, 0.622146623],
      [0.665929436, 0.720342005]]

distances = [[distance(x1=mat[i][0], y1=mat[i][1],
                 x2=mat[j][0], y2=mat[j][1]) for j in range(14)] for i in range(14)]

route = [i for i in range(14)]
bigN = 1000
LC = 100
MC = 0

for j in range(bigN):
    this_dist = 0
    route = shuffle(route)
    # print('Route:', route)

    # Get the distance for the route
    for stop in range(len(route)):
        if stop != len(route) - 1:  # if its not the last node
            this_dist += distances[route[stop]][route[stop + 1]]
        else:  # Add cost from last item to first item
            this_dist += distances[route[stop]][route[0]]
    # print('Distance:', this_dist)

    # Update min/max
    if this_dist < LC:
        LC = this_dist
        LCT = route
        print('New low:', LCT, 'Distance:', LC)
    elif this_dist > MC:
        MC = this_dist
        MCT = route
        print('New high:', MCT, 'Distance:', MC)

print('Last route:', route, 'Last distance:', this_dist)

# Output
print('Least cost:', LC)
print('Least cost trip:', LCT)
print('Most cost:', MC)
print('Most cost trip:', MCT)

如果您只是将其复制并粘贴到IDE中并运行它,您将看到我的意思。 LCT和MCT被设置为生成的最后一条路线(即使它不是最少/最多的成本旅行),当我只在当前路线比当前最小/最多成本更短/更长时更换它们。为什么会发生这种情况,如果将其正确设置为LCT / MCT,我该怎么做?如果这是一个很长的帖子,我很困惑和抱歉,但我无法弄清楚这一点。我正在使用Python 3.7,如果这有帮助的话。编辑:问题澄清。

我希望LCT / MCT至少是不同的,因为它们会有不同的路线和不同的距离。我的问题是变量被设置为生成的最后一条路线,无论它是否实际上比实际的最短/最长路线更短/更长。每当当前路线比实际最短/最长路线更短/更长时,我就会打印出新路线和新的最短路线。 LCT / MCT应设置为打印出的最后一个。

最后编辑:jasonharper在评论中的解决方案有效(对不起,如果我屠杀用户名,你不能在编辑模式下看到它们,我没有足够的代表发表评论)。当我将它们复制到LCT / MCT时,我只需将[:]添加到路径的末尾。谢谢!

python iteration traveling-salesman
1个回答
0
投票

基本上路线是可变的,每次都会改变。当您设置LCT / MCT时,它是指向路线的指针。您可以使用@jasonharper中的建议并更新代码,如下所示:

# Update min/max
if this_dist < LC:
    LC = this_dist
    LCT = route[:]
    print('New low:', LCT, 'Distance:', LC)
elif this_dist > MC:
    MC = this_dist
    MCT = route[:]
    print('New high:', MCT, 'Distance:', MC)
© www.soinside.com 2019 - 2024. All rights reserved.