mercredi 16 mai 2018

Why removing else causes recursive function to repeat the result in python

When I execute the following code on Python console using the below statement,

for L in permute([12, 32, 3]):
    print(L)

for the code below,

def permute(L):
    if len(L) <= 1:
        yield L
    else:
        for i in range(0, len(L)):
            L[0], L[i] = L[i], L[0]
            for L1 in permute(L[1:]):
                yield [L[0]] + L1

each result appears just once. But if I remove the else part and remove the associated indentation of the code below it, I receive each result twice. Why does it happen? Any help will be appreciated.

Aucun commentaire:

Enregistrer un commentaire