我已经阅读了这个网站上的 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]]
>>> []
所以分区正在被正确评估,但没有产生。如何!?!?!?!哈哈!我什至在屈服之前制作了每个分区的副本,以避免因引用同一个对象而被搞砸。