【问题标题】:Generate all combinations of success sets in Python在 Python 中生成所有成功集的组合
【发布时间】:2017-04-21 01:34:55
【问题描述】:

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

【问题讨论】:

  • 你能在你的例子中包含你想要的输出吗?
  • 将所需的输出添加到我的代码@Allen!

标签: python combinations enumeration combinatorics


【解决方案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返回一个生成器,整个列表将不会按请求存储在内存中。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 嗨,我用一个真实的例子更新了我的问题,所以希望我的问题更清楚。我认为这不能回答我的问题,因为我不需要成功的条件。例如,对于一个固定计划(阿司匹林 1 次测试,布洛芬 2 次测试),我试图输出成功测试的可能组合,即(阿司匹林 0 次成功测试,布洛芬 0 次成功测试),(0阿司匹林测试成功,布洛芬测试成功 1), (0, 2), (1, 0), (1,1), (1, 2)。这有意义吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 2016-08-16
    • 2017-09-15
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多