How is the program using recursion and for loop what is the need for tail as a function argument in the below program?

Viewed 28

Consider the following code: How is the program using recursion and for loop what is the need for tail as a function argument in the below program?

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('abcd')
1 Answers

This function is used to get all the possible permutations of the characters of a str.

The recursion part is responsible for taking characters from head and puting them in tail, and when head == '' its prints the tail.

The role of for loop is to consider all the possibilities. Indeed, it start by taking the first character from head, then the second, then the third, and so on.

By combining these two parts, we get all the permutations.

Hope this help you.

Related