[問題] 窮舉"將List中元素分群"的所有可能方法

作者: sharkbay (Shark Bay)   2021-01-22 06:27:43
目前已知這個方法能滿足這個題目, 但是空間或運算量太大, 想請問有沒有別的做法?
import itertools
powerset = lambda iterable: itertools.chain.from_iterable(
itertools.combinations(list(iterable), r)
for r in range(len(list(iterable)) + 1))
flatten = lambda list2d: [item for sublist in list2d for item in sublist]
x = list("abcd")
xx = [list(val) for val in list(powerset(x)) if 0 != len(val)]
xxx = [list(val) for val in list(powerset(xx)) if 0 != len(val)]
xxxx = [list(val) for val in xxx if x == list(sorted(flatten(val)))]
xxxx =
[[['a', 'b', 'c', 'd']],
[['a'], ['b', 'c', 'd']],
[['b'], ['a', 'c', 'd']],
[['c'], ['a', 'b', 'd']],
[['d'], ['a', 'b', 'c']],
[['a', 'b'], ['c', 'd']],
[['a', 'c'], ['b', 'd']],
[['a', 'd'], ['b', 'c']],
[['a'], ['b'], ['c', 'd']],
[['a'], ['c'], ['b', 'd']],
[['a'], ['d'], ['b', 'c']],
[['b'], ['c'], ['a', 'd']],
[['b'], ['d'], ['a', 'c']],
[['c'], ['d'], ['a', 'b']],
[['a'], ['b'], ['c'], ['d']]]
作者: LP9527 (ㄊㄇ抽菸都去)   2021-01-22 13:28:00
tuple+ set幾行就搞定了資料少的話就這樣吧 https://i.imgur.com/0CbjrkT.jpg喔看錯了
作者: sherees (ShaunTheSheep)   2021-01-22 14:55:00
itertools.combinations
作者: ro9956882 (幽靈)   2021-01-23 00:13:00
這樣試試看 " target="_blank" rel="nofollow">
[['a','b'],['c']]我用['ab','c']表示 這樣過程中不用用到deepcopy 要轉換格式做完再一次轉如果有重複元素(多個'a')就要再改一下 0.0

Links booklink

Contact Us: admin [ a t ] ucptt.com