Last active
May 30, 2016 06:49
-
-
Save phamtm/ac22fbbb1e4b79f591a540132a08bbb7 to your computer and use it in GitHub Desktop.
Permutation generation methods
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 swap(ar, i, j): | |
tmp = ar[i] | |
ar[i] = ar[j] | |
ar[j] = tmp | |
def genheapperm(ar, n): | |
if n == 1: | |
print ar | |
return | |
for i in range(n): | |
genperm(ar, n - 1) | |
if n & 2 == 1: | |
swap(ar, 0, n - 1) | |
else: | |
swap(ar, i, n - 1) | |
genheapperm(ar, n - 1) | |
if __name__ == '__main__': | |
ar = [1, 2, 3] | |
genperm(ar, len(ar)) |
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 swap(ar, i, j): | |
tmp = ar[i] | |
ar[i] = ar[j] | |
ar[j] = tmp | |
def genperm(ar, n): | |
if n == 1: | |
print ar | |
return | |
for i in range(n): | |
swap(ar, i, n - 1) | |
genperm(ar, n - 1) | |
swap(ar, i, n - 1) | |
if __name__ == '__main__': | |
ar = [1, 2, 3] | |
genperm(ar, len(ar)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment