0

我已经阅读了这个网站上的 Python Yield Keyword Explained,并且在我的一些函数中使用了它,但是对于我的生活,我一直无法解决这个问题。

我有以下生成器函数,当输入示例值时:

import collections
import itertools
import pprint
import copy

partition = []
def partition_prime_factors(partition_structure, prime_factors):
    # partition_structure is a list
    # prime_factors is a collections.Counter object

    global partition    

    for subsection_size in reversed(partition_structure):
        partition_structure.remove(subsection_size)        
        subsections = list(itertools.combinations(prime_factors.elements(), subsection_size))

        for subsection in subsections:
            prime_factors -= collections.Counter(subsection)
            partition.append(list(subsection))

            if len(prime_factors) == 0:
                pprint.pprint(globals()['partition'])

                yield copy.copy(partition)
            else:
                for j in partition_prime_factors(partition_structure, prime_factors):
                    pass

            prime_factors += collections.Counter(subsection)
            partition.remove(list(subsection))

        partition_structure.append(subsection_size)


print [i for i in partition_prime_factors([1, 3], collections.Counter([2, 2, 3, 5]))]


>>> [[2, 2, 3], [5]]
>>> [[2, 2, 5], [3]]
>>> [[2, 3, 5], [2]]
>>> [[2, 3, 5], [2]]
>>> [[2], [2, 3, 5]]
>>> [[2], [2, 3, 5]]
>>> [[3], [2, 2, 5]]
>>> [[5], [2, 2, 3]]
>>> []

所以分区正在被正确评估,但没有产生。如何!?!?!?!哈哈!我什至在屈服之前制作了每个分区的副本,以避免因引用同一个对象而被搞砸。

4

1 回答 1

2

您不会产生从递归调用中获得的值partition_prime_factors。当你递归时:

for j in partition_prime_factors(partition_structure, prime_factors):
    pass

您需要重新生成值:

for j in partition_prime_factors(partition_structure, prime_factors):
    yield j
于 2012-11-30T03:32:41.943 回答