簡體   English   中英

生成給定步驟數的所有可能的字典組合?

[英]Generate all possible dictionary combinations given number of steps?

假設:

僅使用4個字母(a,b,c,d)

假設我有一個字典,由4個字母的出現次數(> = 0)組成

d = {"a":1, "b":2, "c":1, "d":3}

然后給我一個“步驟”編號。

我想找到給定出現次數“逐步”的所有字典。

例如

# given the above dictionary and a steps of 2
moo = {"a":1, "b":1, "c":1, "d":2}
# moo is a possibility because I simply took away 1 b and 1 d
# how do I find all the possibilities? (note: occurrences cannot be negative)

編輯:步驟正好是2個步驟

注意:我想找到所有的“ moo”或給定參考字典和許多步驟的所有字典。 我不在乎測試兩個字典是否滿足步驟要求。

我想我想出了一些遞歸代碼來解決這個問題:

def genDict(d, steps):
    if steps == 0:
        return [d]
    dList = []
    for key, value in d.items():
        if value > 0:
            temp = dict(d)
            temp[key] = value -1
            dList += genDict(temp, steps-1)
    return dList

任何人都可以獲得不會占用內存的非遞歸解決方案嗎?

它不占用太多內存,因為它會更改遞歸中的相同列表,但是,如果您要收集結果而不是僅打印它,則需要在結果列表中附加d的深拷貝。

d = map(list, {"a":1, "b":2, "c":1, "d":3}.items())
step = 2
def choose(d, pos, step):
    if step == 0:
        print d
        return
    if d[pos][1] > 0:
        d[pos][1] -= 1
        choose(d, pos, step-1)
        d[pos][1] += 1
    if pos < len(d)-1:
        choose(d, pos+1, step)
choose(d, 0, 2)

此輸出:

[['a', 0], ['c', 0], ['b', 2], ['d', 3]]
[['a', 0], ['c', 1], ['b', 1], ['d', 3]]
[['a', 0], ['c', 1], ['b', 2], ['d', 2]]
[['a', 1], ['c', 0], ['b', 1], ['d', 3]]
[['a', 1], ['c', 0], ['b', 2], ['d', 2]]
[['a', 1], ['c', 1], ['b', 0], ['d', 3]]
[['a', 1], ['c', 1], ['b', 1], ['d', 2]]
[['a', 1], ['c', 1], ['b', 2], ['d', 1]]

如果我正確理解您的問題...

  1. 從字典中獲取完整的字符串。

     d = {"a":1, "b":2, "c":1, "d":3} my_string = "" for key, value in d.iteritems(): my_string += key * value # my_string now contains 1 a, 2 b's, 1 c, and 3 d's. 
  2. 使用itertools.permutations獲取字符串的所有可能排列。

     from itertools import permutations for i in permutations(my_string): print i # Do something meaningful with the output 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM