如何获得与Python表达式表达的所有可能的括号组合?
给定几个元素的列表,找到所有可能的括号组合。例如,使用[1、2、3、4]
,它不会
[
[1,2,3,4],
[[1,2],3,4],
[[1,2],[3,4]],
[1,[2,3],4],
[1,2,[3,4]],
[[1,2,3],4],
[[[1,2],3],4],
[[1,[2,3]],4],
[1,[2,3,4]],
[1,[[2,3],4]],
[1,[2,[3,4]]]
]
以任何层次顺序返回。
请阅读:在将其标记为如何为表达式打印所有可能的平衡括号?,尽管相似,但这与此相似。在这个问题中,它只要求括号表达每个值都被包围。但是,无论每个元素是否在括号内,这个问题都要求每个组合。
Given a list of several elements, find all the possible parentheses combinations. For example with [1, 2, 3, 4]
, it would return
[
[1,2,3,4],
[[1,2],3,4],
[[1,2],[3,4]],
[1,[2,3],4],
[1,2,[3,4]],
[[1,2,3],4],
[[[1,2],3],4],
[[1,[2,3]],4],
[1,[2,3,4]],
[1,[[2,3],4]],
[1,[2,[3,4]]]
]
in no paticular order.
PLEASE READ: Before you mark this as a duplicate of How to print all possible balanced parentheses for an expression?, although similar, it is a slightly different question than that. In that question, it only asks for parentheses expressions where every value is surrounded. This question however asks for every single combination regardless of whether every element is within parentheses.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从列表中列出所有可能的树:
itertools.product
组合孩子的所有可能子树。测试:
To list all the possible trees from the list:
itertools.product
.Testing: