【问题标题】:Python - Creating permutations with output array index constraintsPython - 使用输出数组索引约束创建排列
【发布时间】:2021-05-24 13:43:44
【问题描述】:

我想为一个数组创建所有可能的排列,其中每个元素只能出现一次,并限制元素数组索引位置。

ID = ["A","B","C","D","E","F","G","H","I","J"]

我想创建 original_array 的所有可能排列,但是每个元素的位置都限制在以下给出的索引位置:

ID = ["A","B","C","D","E","F","G","H","I","J"]

Index_Options=[]
for i in range(len(ID)):
    List1=[]
    distance=3
    value = i - distance
    for j in range((int(distance)*2)):
        if value < 0 or value > len(ID):
            print("Disregard") #Outside acceptable distance range
        else:
            List1.append(value)
        value=value+1
    Index_Options.append(List1)
    print(Index_Options)

#Index_Options gives the possible index positions for each element. ie "A" can occur in only index positions 0,1,2, "B" can occur in only index positions 0,1,2,3 ect.

我只是在努力研究如何使用这些信息来创建所有输出排列。

任何帮助将不胜感激

【问题讨论】:

    标签: python iteration permutation itertools


    【解决方案1】:

    您可以使用递归生成器函数来构建组合。与其从ID 生成所有可能的排列,然后基于Index_Options 进行过滤,不如通过直接遍历Index_Options 来生成ID 的笛卡尔积更有效:

    ID = ["A","B","C","D","E","F","G","H","I","J"]
    def combos(d, c = [], s = []):
      if not d:
         yield c
      else:
         for i in filter(lambda x:x not in s and x < len(ID), d[0]):
            yield from combos(d[1:], c=c+[ID[i]], s=s+[i])
    
    print(list(combos(Index_Options)))
    

    输出(产生的前十个组合):

    [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'I'], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'H', 'J'], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'J', 'H'], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'J', 'H', 'I'], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'J', 'I', 'H'], ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'G', 'I', 'J'], ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'G', 'J', 'I'], ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'G', 'J'], ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'J', 'G']]
    

    【讨论】:

    • 非常感谢您的帮助,这非常有效,并且比排列方法更有效。
    【解决方案2】:

    您可以使用itertools.permutations 创建所有可能的排列,然后创建新列表并检查所有字母是否都在正确的位置

    permutations = [p for p in itertools.permutations(ID, len(ID)) if all(i in Index_Options[ID.index(x)] for i, x in enumerate(p))]
    

    【讨论】:

    • 感谢您的帮助,效果很好,达到了预期的效果:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多