从一组数字到另一组数字的所有可能路径

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

我想找到从[0,0,0,0,0,0]到[1,1,1,1,1,1]的所有可能路径。例如:

path_i = [[0,0,0,0,0,0], 
          [0,1,0,0,0,0],
          [0,1,1,0,0,0], 
          [0,1,1,0,0,1], 
          [0,1,1,1,0,1],
          [0,1,1,1,1,1],
          [1,1,1,1,1,1]]

将是这种可能路径的一个例子。

我可以想象一些非常可怕的方法(对每个列表项随机添加1,它为零并迭代,直到你拥有所有唯一路径)。但是,我相信必须有更好的方法

编辑:要求澄清每条路径中的步骤

如果存在的总和改变1,例如

 [0,0,0,0,0,0] -> [0,0,0,0,1,0] is a step

 [0,0,0,0,0,0] -> [0,0,1,0,1,0] is NOT a step

在每条路径中,应该只有7个步骤

在此先感谢J

python
1个回答
4
投票

所以,你知道我们有7!找到路径的方法,你可以使用itertools.permutations

from itertools import permutations
paths = permutations(range(7), 7)

list_paths = []

for path in paths:
    tmp = [0]*7
    list_path = [tmp[:]]
    for index in path:
        tmp[index] = 1
        list_path.append(tmp[:])
    list_paths.append(list_path)

你所有的路径都在list_paths

© www.soinside.com 2019 - 2024. All rights reserved.