1

I have this code that acts as a recursive function which just prints out all the possible combinations of a string:

def permut(head, tail = ''):

    if len(head) == 0:
        print(tail)
    else:
       
        for i in range(len(head)):

            # Need help explaning this part
            permut(head[0:i] + head[i+1:], tail + head[i])


# Print the string
permut('xy')

This will print out:

xy

yx

I just need help explaining what is going on, on this part:

permutations(head[0:i] + head[i+1:], tail + head[i])

Community
  • 1
  • 1
Hydrogen
  • 13
  • 4

1 Answers1

1

Print statements are your friend! With head being 'xy', two characters long, you expect your function's for loop to 'loop' through twice (once for each character).

In the first iteration, to find the possible combinations of characters, you are calling (what I presume is a built-in function) permutations on two arguments, the first being head[0:i] + head[i+1:]. If you recall how list slicing works (in this case, on strings which are lists of characters), you slice from the first index up to but not including the second. head[0:i] at this point is from 'x' up to and not including 'x', meaning an empty string. This is concatenated (+) with head[i+1:], which is index of 'x' (0) plus 1, up to the end of the list of characters, meaning from index 1 on, meaning 'y'. Your first argument, is therefore 'y'. The second argument is tail (empty string) + head[i] (which is 'x'. Your first 'loop' calls permutations with arguments (y, x).

In the second iteration, head[0:i] is from index 0 up to but not including i ('y' at index 1 at this point), therefore 'x'. Since i is now the index of y in xy, head[i + 1:] at this point is head[2:], there is no value head[2:] (it is an empty string). So, x concatenated with empty string means the first argument is simply 'x'. tail is still an empty string and head[i] is 'y', so the second argument is 'y'. Your second 'loop' calls permutations with arguments (x, y).

The only other possible combination of characters, using permutation of (y, x) (your first loop through) is what is printed first, xy. Similarly, the only other possible combination of characters, using permutation of (x, y) (your second loop through) is what is printed second, yx.

Simple answer:

First iteration, argument values are (y, x), because i is the index of x, so:

  • head[0:i] is ""
  • head[i+1:] is 'y'
  • tail is ""
  • head[i] is 'x'

Only possible combo (permutation) of argument yx is xy.

Second iteration, argument values are (x, y), because i is the index of y, so:

  • head[0:i] is 'x'
  • head[i+1:] is ""
  • tail is ""
  • head[i] is 'y'

Only possible combo (permutation) of argument xy is yx.

AnneV
  • 96
  • 5