-
-
Save chuanconggao/2b3020d08834f9d1173a53229082a71d to your computer and use it in GitHub Desktop.
Code for computing anagrams that works on both string and list.
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 anagrams(s): | |
return [s] if len(s) == 0 else [ | |
w[:pos] + s[:1] + w[pos:] | |
for w in anagrams(s[1:]) | |
for pos in range(len(w) + 1) | |
] | |
anagrams("abc") | |
# returns ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'] | |
anagrams([1, 2, 3]) | |
# [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment