Need explanation of Pseudocode and code - Python 3+ -
this question has answer here:
- explain slice notation 24 answers
i have code acts recursive function prints out possible combinations of string:
def permut(head, tail = ''): if len(head) == 0: print(tail) else: in range(len(head)): # need explaning part permut(head[0:i] + head[i+1:], tail + head[i]) # print string permut('xy')
this print out:
xy
yx
i need explaining going on, on part:
permutations(head[0:i] + head[i+1:], tail + head[i])
print statements friend! head being 'xy', 2 characters long, expect function's loop 'loop' through twice (once each character).
in first iteration, find possible combinations of characters, calling (what presume built-in function) permutations on 2 arguments, first being head[0:i] + head[i+1:]. if recall how list slicing works (in case, on strings lists of characters), slice first index not including second. head[0:i] @ point 'x' , not including 'x', meaning empty string. concatenated (+) head[i+1:], index of 'x' (0) plus 1, end of list of characters, meaning index 1 on, meaning 'y'. first argument, therefore 'y'. second argument tail (empty string) + head[i] (which 'x'. first 'loop' calls permutations arguments (y, x).
in second iteration, head[0:i] index 0 not including ('y' @ index 1 @ point), therefore 'x'. since index of y in xy, head[i + 1:] @ point head[2:], there no value head[2:] (it empty string). so, x concatenated empty string means first argument 'x'. tail still empty string , head[i] 'y', second argument 'y'. second 'loop' calls permutations arguments (x, y).
the other possible combination of characters, using permutation of (y, x) (your first loop through) printed first, xy. similarly, other possible combination of characters, using permutation of (x, y) (your second loop through) printed second, yx.
simple answer:
first iteration, argument values (y, x), because index of x, so:
- head[0:i] ""
- head[i+1:] 'y'
- tail ""
- head[i] 'x'
only possible combo (permutation) of argument yx xy.
second iteration, argument values (x, y), because index of y, so:
- head[0:i] 'x'
- head[i+1:] ""
- tail ""
- head[i] 'y'
only possible combo (permutation) of argument xy yx.
Comments
Post a Comment