【问题标题】:How can I stop the loop exatly when I get the result I want in Python? [duplicate]当我在 Python 中得到我想要的结果时,如何准确地停止循环? [复制]
【发布时间】:2022-01-17 19:38:42
【问题描述】:

我正在尝试使用贪心算法解决具有限制的 TSP。我现在可以在跑步过程中得到正确的路线,但我不知道当我得到答案时如何准确地停止循环。这是我的主要代码。

while repeat_number < nodes_number :
    best_path = 999999999         
    for i in range(nodes_number): 
        if total_distance + distance[city_visited[-1]][i] <= 20000:
            if i not in city_visited and distance[city_visited[-1]][i] != 0 and distance[city_visited[-1]][i] <= best_path:
                best_path = distance[city_visited[-1]][i]
                next_city = i

    city_visited.append(next_city)
    total_distance = total_distance + best_path
     
    repeat_number = repeat_number + 1

通过这段代码,我可以找到重复次数为19时的最佳解决方案 enter image description here

但是,循环会继续,导致最终结果错误。因此,我想知道一旦我得到答案,如何停止这个循环。希望得到您的帮助;非常感谢你们!

【问题讨论】:

    标签: python python-2.7 loops


    【解决方案1】:

    您可以使用break 命令停止任何循环。只需写一个if 语句,测试该语句中的灵魂是否良好,并在此语句中调用break 命令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 2013-01-01
      相关资源
      最近更新 更多