簡體   English   中英

在Python中生成成功集的所有組合

[英]Generate all combinations of success sets in Python

在治療中分配k種治療和N種全面測試,稱為計划。 對於固定計划,我想在Python中輸出所有可能的成功集。

題:

例如,如果醫生正在測試頭痛葯物,如果k = 2種類型的治療(即阿司匹林和布洛芬)和N = 3總測試,一個計划可能是(1次測試阿司匹林,2次測試布洛芬)。 對於該計划,如何輸出0-1成功的阿司匹林測試和0-2成功測試布洛芬的所有可能組合? 一項成功的測試意味着,當患有頭痛的患者服用阿司匹林時,阿司匹林可以治愈他們的頭痛。

請用python代碼發布答案 ,而不是數學答案。

期望輸出是具有[#成功治療1,#成功治療2]的列表w / na列表:

[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]]

如果可以使用yield會很好,因為上面的列表可能很長並且我不想將整個列表存儲在內存中,這會增加計算時間。

下面我有一個代碼,用於枚舉A盒中N球的所有可能組合,這應該類似於創建我想的所有可能的成功組,但我不知道如何。

#Return list of tuples of all possible plans (n1,..,nk), where N = total # of tests = balls, K = # of treatments = boxes
#Code: Glyph, http://stackoverflow.com/questions/996004/enumeration-of-combinations-of-n-balls-in-a-boxes
def ballsAndBoxes(balls, boxes, boxIndex=0, sumThusFar=0):
    if boxIndex < (boxes - 1):
        for counter in range(balls + 1 - sumThusFar):
            for rest in ballsAndBoxes(balls, boxes,
                                      boxIndex + 1,
                                      sumThusFar + counter):
                yield (counter,) + rest
    else:
        yield (balls - sumThusFar,)

生成計划是一個分區問題,但為給定計划生成成功集只需要生成一組范圍的笛卡爾積。

from itertools import product

def success_sets(plan):
    return product(*map(lambda n: range(n + 1), plan))

plan = [1, 2]
for s in success_sets(plan):
    print(s)
# (0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)

由於itertools.product返回一個生成器,因此整個列表不會按要求存儲在內存中。

我不確定你到底要做什么。 但是可以使用itertools生成組合。

from itertools import combinations
    #You can add an extra loop for all treatments
    for j in range(1, N): #N is number of tests
        for i in combinations(tests, r = j):
            indexes = set(i)
            df_cur = tests[indexes] #for tests i am using a pandas df
            if :# condition for success
                #actions
            else:
                #other_actions

暫無
暫無

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

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