0

I've read through The Python Yield Keyword Explained here on this website, and have been playing around a bit with it in some of my functions, but for the life of me I haven't been able to work out this problem.

I have the following generator function, which when fed in example values:

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]]
>>> []

So the partitions are being correctly evaluated, but not yielded. HOW!?!?!?! LOL! I even make a copy of each partition before I yield in order to avoid being screwed by referencing the same object.

Community
  • 1
  • 1
nebffa
  • 1,529
  • 1
  • 16
  • 26

1 Answers1

2

You're not yielding the values that you get from your recursive call to partition_prime_factors. When you recurse:

for j in partition_prime_factors(partition_structure, prime_factors):
    pass

you need to re-yield the values:

for j in partition_prime_factors(partition_structure, prime_factors):
    yield j
Xymostech
  • 9,710
  • 3
  • 34
  • 44
  • Lol silly me.... it didn't work before when I was debugging the rest of the function so I didn't expect it was the problem. This solves my problem perfectly. – nebffa Nov 30 '12 at 03:35