【问题标题】:Generator object using recursion使用递归的生成器对象
【发布时间】:2018-06-23 16:14:17
【问题描述】:

Python 2.7

给定alleles的列表和数组numb_alleles的长度,例如:

alleles = [11, 12, 13, 14, 15, 16]
numb_alleles = 8

我一直在尝试检查每个笛卡尔积并选择与我的研究相关且符合以下选择标准的等位基因:

  1. 笛卡尔积中的每个第二个值都必须大于它之前的值。例如,给定上述条件,笛卡尔积[13, 15, 11, 12, 14, 15, 16, 16] 将满足选择标准,而[13, 15, 16, 12, 14, 15, 16, 16] 则不满足,因为索引 2 和 3。
  2. alleles 中的每个值都必须出现在笛卡尔积中。 例如,[13, 15, 11, 12, 14, 15, 16, 16] 将满足选择标准,而 [13, 15, 11, 12, 14, 15, 11, 13] 则不满足,因为16 不在产品中。

我一直在使用itertools.product(alleles, repeat = numb_alleles) 迭代每个可能的笛卡尔积以进一步分析。然而,随着numb_alleles 增加到 10 或 12,整体计算量显着增加。

我试图通过使用下面的递归函数选择相关的笛卡尔积来解决这个问题。

def check_allele(allele_combination, alleles):
    """Check if all the alleles are present in allele_combination"""
    for allele in alleles:
        if allele not in allele_combination:
            return False
    return True

def recursive_product(alleles, numb_alleles, result):
    current_len = len(result[0])
    new_result = []
    final_result = []

    for comb in result:
        for allele in alleles:
            if current_len % 2 == 0:
                new_result.append(comb + [allele])
            elif current_len % 2 == 1:
                if comb[-1] <= allele:
                    new_result.append(comb + [allele])
                    if (check_allele(comb + [allele], alleles)):
                        final_result.append(comb + [allele])

    if current_len + 1 < numb_alleles:
        return recursive_product(alleles, numb_alleles, new_result)
    else:
        return final_result

a = (recursive_product(alleles, numb_alleles, [[]]))

但是,使用这种方法,我仍然无法处理高达numb_alleles = 12 的数组,或者当alleles 的长度增加时,因为我使用的是return 而不是yield。因此,它会导致内存不足错误。

我想知道我是否可以将此函数制作成生成器,或者是否有人可以提出不同的方法,以便我可以进一步计算 numb_alleles = 12 和更长 alleles 数组的输出。

非常感谢!

【问题讨论】:

  • 请检查您为第一个标准写的内容。这对我来说没有意义。两个数组的索引 3 和 4 分别为 12 和 14。另外,“笛卡尔积中的每一秒值必须小于它之前的值”是什么意思。究竟是什么意思?在您给出的示例中,15 不小于 13。
  • 感谢詹姆斯指出我的错误。编辑了原帖。我的意思是“笛卡尔积中的每一秒值都必须大于它之前的值”和索引 2 和 3。
  • 这是一个用归纳法解决的好问题。弄清楚如何从给定的起始数组中获取下一个数组。然后找出你的基本情况。然后在代码中表达相同的想法。
  • 当您再次出现而不是返回时,您也许可以yield from。而不是附加到 final_result 你会产生价值。
  • numb_alleles 总是偶数吗? alleles 总是一个连续整数的列表吗?将您的 recursive_product 变成产品并不难,但正如您所指出的,它效率不高,因为它必须拒绝它所做的许多组合。我有一些改进它的想法,但我需要测试它们。我们可以让check_allele 更高效一点,但我们确实需要更好的主算法。

标签: python arrays recursion generator bioinformatics


【解决方案1】:

您说:“笛卡尔积中的每一秒值都必须大于它之前的值。”但是在您的示例[13, 15, 11, 12, 14, 15, 16, 16] 插槽中的项目,7 (16) 等于前一个插槽中的项目,所以我假设您的意思是奇数索引处的项目必须 >= 到前一个偶数索引处的项目。

下面的生成器比您当前的方法更高效,它避免了在 RAM 中保存大型临时列表。核心思想是使用itertools.product 为偶数槽生成组合,然后再次使用product 填充满足选择标准#1 的奇数槽。我们使用集合操作来确保最终组合包含alleles 中的每一项。

from itertools import product

def combine_alleles(alleles, numb_alleles):
    ''' Make combinations that conform to the selection criteria. First create
        the items for the even slots, then create items for the odd slots such
        that each odd slot item >= the corresponding even slot item. Then test
        that the whole combination contains each item in alleles.
    '''
    # If the number of unique items in the even slots is < min_len, then it's
    # impossible to make a full combination containing all of the alleles.
    min_len = len(alleles) - numb_alleles // 2

    # Create a function to test if a given combination
    # contains all of the alleles.
    alleles_set = set(alleles)
    complete = alleles_set.issubset

    # Make lists of alleles that are >= the current allele number
    higher = {k: [u for u in alleles if u >= k] for k in alleles}

    # Make combinations for the even slots
    for evens in product(alleles, repeat=numb_alleles // 2):
        if len(set(evens)) < min_len:
            continue
        # Make combinations for the odd slots that go with this
        # combination of evens.
        a = [higher[u] for u in evens]
        for odds in product(*a):
            if complete(evens + odds):
                yield [u for pair in zip(evens, odds) for u in pair]

# test

alleles = [11, 12, 13, 14, 15, 16]
numb_alleles = 8

for i, t in enumerate(combine_alleles(alleles, numb_alleles), 1):
    print(i, t)

这段代码找到了 16020 种组合,所以输出太大了,这里就不包含了。


这是一个更接近您的版本的替代生成器,但在我的测试中它比我的第一个版本慢一些。

def combine_alleles(alleles, numb_alleles):
    total_len = len(alleles)

    # Make lists of alleles that are >= the current allele number
    higher = {k: [u for u in alleles if u >= k] for k in alleles}

    def combos(i, base):
        remaining = numb_alleles - i
        if len(set(base)) + remaining < total_len:
            return

        if remaining == 0:
            yield base
            return

        ii = i + 1
        for u in higher[base[-1]] if i % 2 else alleles:
           yield from combos(ii, base + [u])

    yield from combos(0, [])

此版本适用于 Python 3。Python 2 没有yield from,但这很容易修复:

yield from some_iterable

等价于

for t in some_iterable:
    yield t

【讨论】:

  • 非常令人印象深刻 (+1)。
  • 非常感谢。我从来没有想过像你那样分而治之。这太棒了。尤其是higher 字典的使用是一种跟踪比另一个更高的等位基因的优雅方法。再次感谢。
猜你喜欢
  • 2019-10-18
  • 2019-12-24
  • 1970-01-01
  • 2016-07-19
  • 2019-08-25
  • 2021-05-22
  • 2020-08-04
  • 2016-05-03
  • 2020-05-05
相关资源
最近更新 更多