[问题] 穷举"将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
这样试试看 https://imgur.com/bbYlZR8[['a','b'],['c']]我用['ab','c']表示 这样过程中不用用到deepcopy 要转换格式做完再一次转如果有重复元素(多个'a')就要再改一下 0.0

Links booklink

Contact Us: admin [ a t ] ucptt.com