Last active
October 22, 2021 10:10
-
-
Save rblaine95/67db48b050b95a2ae51beedc6bd3d111 to your computer and use it in GitHub Desktop.
Permutation Sort - Given a list, generate every possible permutation of the list, then find the one that's sorted
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
#!/usr/bin/env python3 | |
import itertools | |
from random import shuffle | |
def is_sorted(l): | |
for i in range(len(l)-1): | |
if l[i] > l[i+1]: | |
return False | |
return True | |
def permutation_sort(l): | |
if not is_sorted(l): | |
p = list(itertools.permutations(l)) | |
print("there are", len(p), "permutations") | |
for x in range(len(p)-1): | |
if is_sorted(p[x]): | |
print(x, "is the one that's sorted") | |
return(p[x]) | |
print("list is already sorted") | |
return l | |
def main(): | |
max = 10 | |
lst = [i for i in range(max)] | |
shuffle(lst) | |
print(permutation_sort(lst)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment