Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

A problem about generator built by iteration

$
0
0

I came across a problem in CS61A:

Given a sequence of unique elements, a permutation of the sequence is a list containing the elements of the sequence in some arbitrary order. For example, [2, 1, 3], [1, 3, 2], and [3, 2, 1] are some of the permutations of the sequence 1, 2, 3].
Implement gen_perms, a generator function that takes in a sequence seq and returns a generator that yields all permutations of seq. For this question, assume that seq will not be empty. Permutations may be yielded in any order.

My solution to this is:

def gen_perms(seq):    def generator(seq_):        list_seq=list(seq_)        if len(list_seq)==1:            yield list_seq        else:            for item in generator(list_seq[1:]):                for i in range(len(list_seq)):                    yield item[:i]+[list_seq[0]]+item[i:]    return generator(seq)

An instance is
print(list(gene_perms([10,20,30])))
And the output works out fine:
[[10, 20, 30], [20, 10, 30], [20, 30, 10], [10, 30, 20], [30, 10, 20], [30, 20, 10]]

My doubt is that it looks like it should not have had the correct output, since in my code generator is built recursively and the yield line of generator(list_seq[1:]) is occured ahead of that of generator(list_seq) and it should yield the permutation of its subsequence first and then the permutation of the sequence itself. But the former didn't even appear in the output.
Could someone explain this to me? Maybe I have a wrong comprehension about how generator works. Thanks!


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>