python - 当一个(或多个)值未知/通配符时计算出列表的排列数量
问题描述
当一个(或多个)值未知/通配符时计算出列表的排列数量
如果我有一系列选项,例如在这里说 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]
替换 a 的第一个实例"?"
和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)]]
解决方案
如果你知道一些选项,那么你只需要计算出未知选项的排列。因此,如果您有[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)
推荐阅读
- css - Bootstrap 下拉元素,里面有两个项目
- javascript - 电子表格跟踪器
- python - 从 Python 中的 Habenero API 获取错误的 Unicode
- php - 使用 POST 方法从 HTML 表单中检索 SQL 语句不会查询数据库
- antlr - ANTLR4 - 替换操作边界错误|如何使用 TokenStreamRewriter 从原始 AST 中重叠标记上的两个侦听器事件转换文本?
- html - 导航栏折叠按钮不适用于某些视图
- reactjs - componentDidUpdate 和 componentWillReceiveProps 中的 API 调用
- c++ - CURL 静态链接未解析的外部符号
- javascript - Js碰撞检测器 - 撞墙与撞地板(差异)
- mysql - mysql 在加入时忽略 order by 索引