To brush up my Python knowledge I an algorithm to generate permutations in lexicographic order. I ended up with the following code:
def swap(a, i, j): tmp = a[i] a[i] = a[j] a[j] = tmp def next_permutation(a): n = len(a) if n == 0 or n == 1: return False kFound = False for k in reversed(range(n - 1)): if a[k] < a[k + 1]: kFound = True break if not kFound: return False for l in reversed(range(n)): if a[k] < a[l]: break swap(a, k, l) return a[:k + 1] + [i for i in reversed(a[k + 1:])]
I did a lot of C++ and miss
std::swap(..), what is the proper way to do this in Python? In the last line, because
reversed(..) returns an iterator I cannot write simply:
a[:k + 1] + reversed(a[k + 1:]), is there a simpler way to trigger the unfolding of the iterator into a list?