在Python

时间:2017-04-20 04:02:07

标签: python combinations enumeration combinatorics

在治疗中分配k种治疗和N次总检验,称为计划。对于固定计划,我想在Python中输出所有可能的成功集。

问题:

例如,如果医生正在测试头痛药物,如果k = 2种类型的治疗(即阿司匹林和布洛芬)和N = 3总测试,则可以进行一项计划(1次测试阿司匹林,2次测试布洛芬)。对于该计划,如何输出0-1成功的阿司匹林测试和0-2成功测试布洛芬的所有可能组合?一项成功的测试意味着,当患有头痛的患者服用阿司匹林时,阿司匹林可以治愈他们的头痛。

请使用python代码发布答案 ,而不是数学答案。

所需的输出是一个列表,其列表中有[#成功处理1,#成功处理2]:

[[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,)

2 个答案:

答案 0 :(得分:1)

生成计划是一个分区问题,但为给定计划生成成功集只需要生成一组范围的笛卡尔乘积。

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返回一个生成器,因此整个列表不会按要求存储在内存中。

答案 1 :(得分:0)

我不确定你想要实现的目标。但是可以使用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