def advance_permutation(a, increasing=True, forward=True):
if not forward:<EOL><INDENT>a.reverse()<EOL><DEDENT>cmp = operator.lt if increasing else operator.gt<EOL>try:<EOL><INDENT>i = next(i for i in reversed(range(len(a) - <NUM_LIT:1>)) if cmp(a[i], a[i + <NUM_LIT:1>]))<EOL>j = next(j for j in reversed(range(i + <NUM_LIT:1>, len(a))) if cmp(a[i], a[j]))<EOL><DEDENT>except StopIteration:<EOL><INDENT>if forward:<EOL><INDENT>a.reverse()<EOL><DEDENT>return False<EOL><DEDENT>a[i], a[j] = a[j], a[i]<EOL>a[i + <NUM_LIT:1>:] = reversed(a[i + <NUM_LIT:1>:])<EOL>if not forward:<EOL><INDENT>a.reverse()<EOL><DEDENT>return True<EOL>
Advance a list of unique, ordered elements in-place, lexicographically
increasing or backward, by rightmost or leftmost digit.

Returns False if the permutation wrapped around - i.e. went from
lexicographically greatest to least, and True in all other cases.

If the length of the list is N, then this function will repeat values after
N! steps, and will return False exactly once.

See also https://stackoverflow.com/a/34325140/43839