I've written a function called size_subsets that returns all subsets of a certain size, when passed a list of cities (numbers). However, restating the function using izip() instead of two for-yield blocks completely breaks the behavior.
The second method below restates the first method using izip(), but for some reason it returns nothing at the top level. Can anyone help me figure out why this is?
Print statements show that SOME (not all) of the correct subsets do get yielded at the bottom-most level of the recursion in size_subsets_broken, but even these aren't making it to the top level for some reason.
def size_subsets(cities, size, sofar):
if not size:
yield sofar
return
elif len(cities) < size:
return
else:
curr_city = cities.pop()
for a in size_subsets(cities[:], size - 1, sofar | {curr_city}):
yield a
for b in size_subsets(cities[:], size, sofar):
yield b
def size_subsets_broken(cities, size, sofar):
if not size:
yield sofar
return
elif len(cities) < size:
return
else:
curr_city = cities.pop()
inclusive = size_subsets_broken(cities[:], size - 1, sofar | {curr_city})
exclusive = size_subsets_broken(cities[:], size, sofar)
for incl_subset, excl_subset in izip(inclusive, exclusive):
yield incl_subset
yield excl_subset
print list(size_subsets([1, 2, 3], 2, set())) # [set([2, 3]), set([1, 3]), set([1, 2])]
print list(size_subsets_broken([1, 2, 3], 2, set())) # []
avalues, followed by all thebvalues. Your second method alternates between them. Do you want that?