Created
May 5, 2012 19:37
-
-
Save beala/2604992 to your computer and use it in GitHub Desktop.
Permutations interview question.
This file contains 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
# Print each permutation. | |
def perm(l, n, str_a): | |
if len(str_a) == n: | |
print str_a | |
else: | |
for c in l: | |
perm(l, n, str_a+c) | |
# Return a list of permutations. | |
def perm2(l, n, str_a, perm_a): | |
if len(str_a) == n: | |
return [str_a] + perm_a | |
else: | |
new_perm_a = perm_a | |
for c in l: | |
new_perm_a = perm2(l, n, str_a+c, new_perm_a) | |
return new_perm_a | |
perm(['a','b','c'], 3, "") | |
print perm2(['a','b','c'], 3, "", []) |
Good Job, keep making tutorials you explain everything so well.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good! Nice solution :)