Generator - Python 3 exercise generating permutation

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I am trying to write a generator function for permutation for practice. But it does not return anything. But if I replace ´´yield new[k]´´ with ´´lis.append(new[k])´´, then I get the correct list of permutations. Am I doing something wrong with yield?

tup=(1,2,3) # tup can be any sequence
new=[[]]*(len(tup)+1) # memory; new[0]=[], new[1] will be length 1 permutation, etc.
lis=[]  # the list of permutations

def repeat(k): # recursion
    for i in tup:
        if i in new[k-1]:
            continue # permutation can t repeat
        else: new[k]=new[k-1]+[i]

        if k==len(tup): 
             yield new[k]
        else:
             repeat(k+1)

gen=repeat(1)
for i in gen:
    print(i)

Answers

This is a recursive function, but you don t pass on the value from the recursion, which is why it doesn t return anything.

You need to change the call to

repeat(k+1)

to

for x in repeat(k+1):
    yield x

The resulting function is then:

tup=(1,2,3) # tup can be any sequence
new=[[]]*(len(tup)+1) # memory; new[0]=[], new[1] will be length 1 permutation, etc.
lis=[]  # the list of permutations

def repeat(k): # recursion
    for i in tup:
        if i in new[k-1]:
            continue # permutation can t repeat
        else: new[k]=new[k-1]+[i]

        if k==len(tup): 
             yield new[k]
        else:
             for x in repeat(k+1):
                 yield x

for i in repeat(1):
    print(i)

Which works.

The next step is then to get rid of the global variables.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/11199707/python-3-exercise-generating-permutation

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils