变量是相同的,但不应该是?Python

2024-10-02 00:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些麻烦,变量被设置为相同的时候,他们不应该是,我不明白为什么他们这样做。在我的例子中,LCT和MCT被设置为函数中生成的最后一个路由,但是我只在路由分别小于或大于最小成本或最大成本时才设置它们。基本上,我正在创建一个0-13之间的整数的伪随机列表作为城市标签,并使用I-by-j数组查找查找它们之间的距离,其中值表示从城市I到城市j的距离。这是我的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?我很困惑,如果这是一个很长的职位,很抱歉,但我不能明白这一点。如果有帮助的话,我使用的是python3.7。编辑:问题澄清。你知道吗

我希望LCT/MCT至少会有所不同,因为它们会有不同的路线和不同的距离。我的问题是,变量被设置为最后生成的路由,不管它是否比实际的最短/最长路由短/长。每次当前路线比实际的最短/最长路线短/长时,我都让它打印出新路线和新的最短距离。LCT/MCT应设置为最后一个打印出来的。你知道吗

最后一次编辑:jasonharper在评论中的解决方案有效(抱歉,如果我破坏了用户名,你在编辑模式下看不到它们,我没有足够的代表发表评论)。当我把它们复制到LCT/MCT时,我只需要在路由的末尾加上[:]。谢谢!你知道吗


Tags: inforparamdisttyperandomthis路线
1条回答
网友
1楼 · 发布于 2024-10-02 00:35:01

基本上路线是可变的,每次都会改变。设置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)

相关问题 更多 >

    热门问题