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 sequence1, 2, 3].
Implementgen_perms, a generator function that takes in a sequenceseqand returns a generator that yields all permutations ofseq. For this question, assume thatseqwill 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 isprint(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!