当一个(或多个)值为未知/通配符时,计算列表的排列数
如果我有一系列的选项,比如说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)]
编辑:
尝试使用西蒙恩建议的方法-
正在尝试用列表选项替换?
。。。你知道吗
如果我有[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)]]
我想
itertools.product
会做你需要的一切如果你知道一些选项,那么你只需要计算出未知选项的排列。所以如果你有
[0,"?",1,1,0,"?","?"]
,你只需要生成三个值的所有可能的排列,然后插入它们来代替?角色。所以在这种情况下,会有八个选项,其中三个?替换为您在问题中提供的排列。你知道吗编辑:这里有一些代码
相关问题 更多 >
编程相关推荐