Skip to content Skip to sidebar Skip to footer

Too Many Values To Unpack In A Yield

this is an exercise where Item is a class, and when I run testAll I have a valueError. The yield is suppose to return just 2 values, the content of 2 bags: > Traceback (most rec

Solution 1:

You yield two items at a time in your loop, so you have to catch two at a time:

for pset1, pset2 in yieldAllCombos(items):
    ...

Solution 2:

If you don't understand generators and the yield statement at all, see the Python Wiki page for a general overview.

The problem is that you're trying to assign the entire generator yieldAllCombos(items) to two variables. This only works if yieldAllCombos generates exactly two values, by calling yield exactly twice.

But that's not what yieldAllCombos generates. If you want to see what it does, just try this:

print(list(yieldAllCombos(items)))

You'll see that you got back a large list of 2-tuples, one for each time it calls yield in the loop. And this shouldn't be too surprising, since a function called yieldAllCombos ought to be giving you a lot of combos, right? If you wanted to unpack the whole thing, you'd have to unpack it into one variable for each 2-tuple in the list, not just two variables. But that's probably not what you want.

What you probably want to do is iterator over all of the 2-tuples, unpacking each one. So:

for pset1, pset2 in yieldAllCombos(items):

Solution 3:

Below is suggestion

def testAll():
    items = buildItems()
    gen=yieldAllCombos(items)
    for l in range(3**len(items)+0):
        pset = next(gen)
        pset1 = pset[0]
        pset2 = pset[1]
        print(str(len(pset1)) + '   ' + str(len(pset2)))
        for j in range(len(pset1)):
            print(str(pset1[j]))
        for k in range(len(pset2)):
            print(str(pset2[k]))

The above code will generate an output similar to the following

Pset 1 length : 4 Pset 2 length : 2
******** pset 1 ********
<painting, 90.0, 9.0>
<vase, 50.0, 2.0>
<book, 10.0, 1.0>
<computer, 200.0, 20.0>
******** pset 2 ********
<clock, 175.0, 10.0>
<radio, 20.0, 4.0>

Reference


Post a Comment for "Too Many Values To Unpack In A Yield"