简体   繁体   中英

Generators, yield, send python

I got this homework question, after taking a course on udemy I still cannot figure out how to solve it. It is about yield, next and send.

This is what I need to do: Guidance:

  1. Use itertools.permutations to produce all permutations of the list, and store them in a permutations list
  2. Sort the permutations list using list.sort()
  3. Use yield keyword while iterating over the permutations list
  4. Check if the yield statement obtained an input list, if so, empty the permutations list and repeat step 2

Below there is the code i tried, it doesn't support the send function and keeps going with the old LIST.

def permute(items):
    permu_list = [perm for perm in pr(items)]
    permu_list.sort()
    for x in permu_list:
        yield x

this is the exmaple of results:

>>> g = permute(['b', 'a', 'c'])
>>> next(g)
('a', 'b', 'c')
>>> next(g)
('a', 'c', 'b')
>>> g.send(['e', 'q', 'c'])
('c', 'e', 'q')
>>> next(g)
('c', 'q', 'e')

You can get the value which has been sent by assignment in the yield statement. like:

received = yield something

For your usage you need an extra knowledge you can yield from another generator by yield from statement. in your case you need something like this:

def permute(items):
    permu_list = [perm for perm in pr(items)]
    permu_list.sort()
    for x in permu_list:
        l = yield x
        if l:
            yield from permute(l)
            break

In line which have l = yield x I receive whatever has been sent to this generator if you simply call next on a generator you receive None here, so I wrote an if statement to check whether it's a None value or it's something which comes from send method of generator.

After that I create and use another generator from the same generator function which we got. By permute(l) I create a new generator and by yield from I send output of this generator as output and after that I don't want to continue generating permutation from the first list so I break the loop.

For more information you can check this two parted article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM