Python - 使用输出数组索引约束创建排列

Python - Creating permutations with output array index constraints

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

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.

我只是在苦苦思索如何使用这些信息来创建所有输出排列。

如有任何帮助,我们将不胜感激

您可以使用 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))]

您可以使用递归生成器函数来构建组合。与其从 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']]