我在这个网站上通过The 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]]
>>> []
因此正在正确评估分区,但不会产生分区。怎么样!?!?!?!大声笑!在我屈服之前,我甚至会制作每个分区的副本,以避免因引用相同的对象而被搞砸。
答案 0 :(得分: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