计算一个(或多个)值未知/通配符时列表的排列数量

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

计算一个(或多个)值未知/通配符时列表的排列数量

[如果我有一系列选择,例如在这里说3。每个选项可以是1或0。

我可以使用itertools获得可能的组合。

但是,如果其中两个选项是已知的,例如[0, 1, "?"]-如何计算出可能的剩余排列,例如(0, 1, 0), or (0, 1, 1)

我有3种以上的选择,因此需要一种可以扩展(并允许更多未知数的方法)

import itertools
from pprint import pprint

input_data = []
for i in range(0,3):
    input_data.append([0,1])

print(input_data)

#get all possible combinations
result = list(itertools.product(*input_data))
print("possible permutations:", len(result))
pprint(result)

输出:

[[0, 1], [0, 1], [0, 1]]
possible permutations: 8
[(0, 0, 0),
 (0, 0, 1),
 (0, 1, 0),
 (0, 1, 1),
 (1, 0, 0),
 (1, 0, 1),
 (1, 1, 0),
 (1, 1, 1)]

编辑:尝试使用SimonN的建议方法-尝试用列表选项替换? ...

如果我有[0, 1, "?", "?"],如何使用[0, 1]"?"的第一个实例替换为0,将下一个替换为1

def gen_options(current):
    unks = current.count("?")
    input_data = []
    for i in range(0, unks):
        input_data.append([0, 1])

    permutatons = list(itertools.product(*input_data))
    options = []
    for perm in permutatons:

        option = [perm if x == "?" else x for x in current]
        options.append(option)
    return options

test = [0, 1, "?", "?"]
options = gen_options(test)
print (options)

给予

[[0, 1, (0, 0), (0, 0)], [0, 1, (0, 1), (0, 1)], [0, 1, (1, 0), (1, 0)], [0, 1, (1, 1), (1, 1)]]
python itertools
1个回答
1
投票

如果您知道某些选项,则只需要计算未知选项的排列即可。因此,如果您有[0,"?",1,1,0,"?","?"],则只需要生成三个值的所有可能排列并将其替换为?即可。字符。因此,在这种情况下,将有八个选项,其中三个?被替换为您在问题中提供的排列。

编辑:这是一些代码

import itertools
from copy import copy

inp=[1,"?",1,"?",0]
output=[]

for p in itertools.product([0,1], repeat=inp.count("?")):
    working = copy(inp)
    p_list=list(p)
    for i, x in enumerate(working):
        if x == "?":
            working[i] = p_list.pop()
    output.append(working)
print(output)
© www.soinside.com 2019 - 2024. All rights reserved.