Last active
August 15, 2017 21:35
-
-
Save chiragjn/9ff4f4f0f98d7771a08036f53be90b8d to your computer and use it in GitHub Desktop.
C++ std::next_permutation with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def next_permutation(mi): | |
""" | |
Modifies in place to give lexicographically smallest permutation of mi greater than the given permutation | |
Args: | |
mi (iterable): Mutable iterable, must implement __len__ | |
Returns: | |
bool: True if next permutation was found, False otherwise | |
""" | |
if len(mi) <= 1: | |
return False | |
first_idx = 0 | |
last_idx = len(mi) | |
i = last_idx - 1 | |
while True: | |
ii = i | |
i -= 1 | |
if mi[i] < mi[ii]: | |
j = last_idx - 1 | |
while not mi[i] < mi[j]: | |
j -= 1 | |
mi[i], mi[j] = mi[j], mi[i] | |
mi[ii:last_idx] = mi[ii:last_idx][::-1] | |
return True | |
if i == first_idx: | |
mi[first_idx:last_idx] = mi[first_idx:last_idx][::-1] | |
return False | |
return False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment