Skip to content

Instantly share code, notes, and snippets.

@chuanconggao
Forked from jmuzsik/anagrams.py
Last active May 14, 2020 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chuanconggao/2b3020d08834f9d1173a53229082a71d to your computer and use it in GitHub Desktop.
Save chuanconggao/2b3020d08834f9d1173a53229082a71d to your computer and use it in GitHub Desktop.
Code for computing anagrams that works on both string and list.
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