最短路径优化不起作用

时间:2013-10-29 23:13:12

标签: python algorithm optimization

我试图解决Python中的Ruby Quiz问题60,这里给出: http://rubyquiz.com/quiz60.html

一个人基本上必须通过仅将数字加倍,减半或加2来找到从一个数字到另一个数字的最短路径。

编写一个实际解决问题的程序并不太难:

def maze_solver(a, b):
    paths = [[a]]
    final = []

    for ind, path in enumerate(paths):

        if path[-1] == b:
            return path

        last = path[-1]

        paths.append(path + [last * 2])
        paths.append(path + [last + 2])
        if last % 2 == 0:
            paths.append(path + [last / 2])


print maze_solver(979, 2)


>>> maze_solver(9, 2)
[9, 18, 20, 10, 12, 6, 8, 4, 2]
>>> maze_solver(2, 9)
[2, 4, 8, 16, 18, 9]

但是当我尝试优化它时,失败了。我认为如果两条路径具有相同的终点并且一条路径比另一条路径短,则可以消除较长的路径。

我尝试了这种优化:

def maze_solver(a, b):
    paths = [[a]]
    final = []

    for ind, path in enumerate(paths):

        if path[-1] == b:
            return path

        for other in paths:
            if ind != paths.index(other):
                if path[-1] == other[-1] and len(other) >= len(path):
                    paths.remove(other)

        last = path[-1]

        paths.append(path + [last * 2])
        paths.append(path + [last + 2])
        if last % 2 == 0:
            paths.append(path + [last / 2])

但这甚至没有得出正确的答案:

>>> maze_solver(9, 2)
[9, 11, 22, 24, 48, 24, 12, 6, 8, 4, 2]

我不知道为什么这段代码不起作用,所以如果有人能向我解释我做错了什么,那将非常有帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

在迭代过程中修改列表可能会很危险。

请参阅this answer