0

When discovering solutions for the permutations of the list I have stumbled upon this hardcoded answer. I will list the code here:

def permutations(head, tail=''):
    if len(head) == 0: print tail
    else:
        for i in range(len(head)):
            permutations(head[0:i] + head[i+1:], tail+head[i])

permutations('abc')

Now, I totally do not understand, what happens when we call function from its body. Could you please explain to me, why it works, why it is needed here, and where I can read about this in more detail.

Thank you!

ma3oun
  • 3,681
  • 1
  • 21
  • 33
gregoruar
  • 345
  • 3
  • 14
  • 5
    It's a recursive call: https://www.geeksforgeeks.org/recursive-functions/ – ma3oun Aug 22 '19 at 12:45
  • I would step through the function by hand for a small list (e.g. 3-4 values). The computer term to search for is recursion – mmmmmm Aug 22 '19 at 12:46
  • Try posting a letter through your front door with an instruction inside it to post it through your front door, it'll achieve the same thing – Sayse Aug 22 '19 at 12:47

1 Answers1

0

This is a recursive call. Basically recursion is based off of a base case, which if fulfilled, will stop. Otherwise the function will call itself.

You can read more here:

https://realpython.com/python-thinking-recursively/

It's also worth noting, that while recursion can make code more readable, in Python recursion should be used with caution, as the default recursion limit is relatively conservative.

DariusFontaine
  • 682
  • 1
  • 4
  • 20