
How to Write an Anagram Generator in One Line of Code?
Is it possible to write a program that generates anagrams in just one line of code? Absolutely! In Python, all you need is a single call to the standard library:
from itertools import permutations
print([''.join(p) for p in permutations("cat")])
That’s it! Thanks to the built-in permutations
function from the itertools
module, all possible letter combinations are generated instantly.
How Does It Work?
This code creates all possible letter arrangements, meaning it generates the complete set of anagrams for a given word. For the word "cat"
, the result will be:
['cat', 'cta', 'act', 'atc', 'tca', 'tac']
What Is an Anagram?
An anagram is a word or phrase formed by rearranging the letters of another word or phrase. For example:
- Roma → Amor
- Listen → Silent
- Debit Card → Bad Credit
Anagrams are commonly used in word games, cryptography, and language puzzles.
Comparison with JavaScript
You can write similar code in JavaScript, although it requires a few more steps:
function getAnagrams(word) {
if (word.length <= 1) return [word];
let anagrams = [];
for (let i = 0; i < word.length; i++) {
let char = word[i];
let remaining = word.slice(0, i) + word.slice(i + 1);
let subAnagrams = getAnagrams(remaining);
subAnagrams.forEach(sub => anagrams.push(char + sub));
}
return anagrams;
}
console.log(getAnagrams("cat"));
The output will be the same:
['cat', 'cta', 'act', 'atc', 'tca', 'tac']
Minimalism and Efficiency
The Python solution is shorter and more readable because it leverages the built-in permutations
function. In JavaScript, recursion is necessary, which makes the code less concise.
However, keep in mind that the number of anagrams grows exponentially. For a word with n
letters, the number of anagrams is n!
(factorial). For example:
- 3 letters:
3! = 6
- 4 letters:
4! = 24
- 6 letters:
6! = 720
- 10 letters:
10! = 3,628,800
For longer words, generating all anagrams becomes very resource-intensive.
Fun Facts
Anagrams are used in various fields:
- Cryptography – anagrams can be used to encrypt messages.
- Word games – games like Scrabble, Wordfeud, or Wordle often involve letter rearrangements.
- Pseudonyms – some authors use anagrams as pen names (e.g., "Tom Marvolo Riddle" → "I Am Lord Voldemort" in Harry Potter).
Challenge!
Can you write an even shorter code in Python or JavaScript? 🚀
2025-02-02, Category: Tips & Tricks