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

看板Python作者 (Shark Bay)時間4年前 (2021/01/22 06:27), 4年前編輯推噓2(206)
留言8則, 3人參與, 4年前最新討論串1/1
目前已知這個方法能滿足這個題目, 但是空間或運算量太大, 想請問有沒有別的做法? 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']]] -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.1.116.121 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1611268065.A.18F.html

01/22 13:28, 4年前 , 1F
tuple+ set幾行就搞定了
01/22 13:28, 1F

01/22 13:46, 4年前 , 2F
資料少的話就這樣吧 https://i.imgur.com/0CbjrkT.jpg
01/22 13:46, 2F

01/22 13:47, 4年前 , 3F
喔看錯了
01/22 13:47, 3F

01/22 14:55, 4年前 , 4F
itertools.combinations
01/22 14:55, 4F

01/23 00:13, 4年前 , 5F
01/23 00:13, 5F

01/23 00:15, 4年前 , 6F
[['a','b'],['c']]我用['ab','c']表示 這樣過程中不用
01/23 00:15, 6F

01/23 00:15, 4年前 , 7F
用到deepcopy 要轉換格式做完再一次轉
01/23 00:15, 7F

01/23 00:21, 4年前 , 8F
如果有重複元素(多個'a')就要再改一下 0.0
01/23 00:21, 8F
elements = list("abcdefghijl") combinations = [[]] for element in elements : for i in range(len(combinations)): for j in range(len(combinations[i])): new = combinations[i][:] new[j] += element combinations.append(new) combinations[i].append(element) combinations = [list(sorted([list(c) for c in combination])) for combination in combinations] combinations = list(sorted(combinations)) 我重抄一份在此 ※ 編輯: sharkbay (106.1.116.121 臺灣), 01/23/2021 00:50:44 def partition(collection): global counter if len(collection) == 1: yield [collection] return first = collection[0] for smaller in partition(collection[1:]): for n, subset in enumerate(smaller): yield smaller[:n] + [[first] + subset] + smaller[n + 1:] yield [[first]] + smaller google到一份新的code ※ 編輯: sharkbay (106.1.116.121 臺灣), 01/23/2021 06:20:52
文章代碼(AID): #1W2V_X6F (Python)
文章代碼(AID): #1W2V_X6F (Python)