Skip to content

Commit

Permalink
improve anagram challenge
Browse files Browse the repository at this point in the history
  • Loading branch information
krother committed Jun 5, 2024
1 parent 25e9989 commit ebf6981
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 13 deletions.
31 changes: 18 additions & 13 deletions challenges/anagrams.rst
Original file line number Diff line number Diff line change
@@ -1,35 +1,40 @@
Anagrams
========

**🎯 Generate all anagrams of a word with 3-6 letters.**
**🎯 Check whether two words are anagrams of each other.**

For example, the string:

::

ROT
players

has the anagrams (permutations of characters):
has the anagram (permutations of characters):

::

TOR
ORT
TRO
RTO
OTR
parsley

Write a function `anagram()` that satisfies the following checks:

.. code:: python3
assert anagram("players", "parsley") is True
assert anagram("hello", "world") is False
Hints
-----

- Look up the function ``itertools.permutations()``.
- You may need an expression like ``''.join(["T", "O", "R"])``
- consider sorting the characters
- consider the `set()` data type
- consider `collections.Counter`
- look up the function `itertools.permutations()`.

Extra challenges
----------------

- Get yourself a word list. Find anagrams that are real words.
- Implement the algorithm to generate the anagrams yourself. Get
informed about **dynamic programming**.
- Look for anagrams in the `SOWPODS word list <https://www.freescrabbledictionary.com/sowpods/download/sowpods.txt>`__ .
- Implement an algorithm to generate all possible anagrams. Inform yourself about **dynamic programming**.
- what is the time complexity of your implementation?

*Translated with* `www.DeepL.com <https://www.DeepL.com/Translator>`__
35 changes: 35 additions & 0 deletions solutions/anagrams.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from collections import Counter
from itertools import permutations


def anagram(s1: str, s2: str) -> bool:
"""clean and neat solution in O(n log n) time"""
return sorted(s1) == sorted(s2)


def anagram(s1: str, s2: str) -> bool:
"""from scratch solution, also O(n log n) because of 'in' """
if len(s1) == len(s2):
for c1 in s1:
if c1 not in s2:
return False
return True
return False

def anagram(s1: str, s2: str) -> bool:
"""faster O(n) but fails for character duplicates"""
return set(s1) == set(s2)

def anagram(s1: str, s2: str) -> bool:
"""using counter dict, covers duplicates and should be O(n)"""
return Counter(s1) == Counter(s2)


def anagram(s1: str, s2: str) -> bool:
"""super slow, probably O(n!)"""
return tuple(s1) in permutations(s2)



assert anagram("players", "parsley") is True
assert anagram("hello", "foo") is False

0 comments on commit ebf6981

Please sign in to comment.