給定幾個元素的串列,找出所有可能的括號組合。例如[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]]]
]
沒有特別的順序。
請閱讀:在將其標記為如何列印運算式的所有可能的平衡括號的副本之前?,雖然相似,但這是一個與此略有不同的問題。在那個問題中,它只要求每個值都被包圍的括號運算式。然而,無論每個元素是否在括號內,這個問題都要求每個組合。
uj5u.com熱心網友回復:
從串列中列出所有可能的樹:
- 從根開始迭代所有可能數量的孩子;
- 對于選定數量的子串列,迭代所有可能的方法將串列拆分為該數量的子串列;
- 遞回查找子串列的所有可能子樹;
- 使用 . 組合子節點的所有可能子樹
itertools.product
。
from itertools import product, combinations, pairwise, chain
def all_trees(seq):
if len(seq) <= 1:
yield from seq
else:
for n_children in range(2, len(seq) 1):
for breakpoints in combinations(range(1, len(seq)), n_children-1):
children = [seq[i:j] for i,j in pairwise(chain((0,), breakpoints, (len(seq) 1,)))]
yield from product(*(all_trees(child) for child in children))
測驗:
for seq in ([], [1], [1,2], [1,2,3], [1,2,3,4]):
print(seq)
print(list(all_trees(seq)))
print()
[]
[]
[1]
[1]
[1, 2]
[(1, 2)]
[1, 2, 3]
[(1, (2, 3)), ((1, 2), 3), (1, 2, 3)]
[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)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/470056.html
上一篇:從父子關系創建選單路徑