File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11Anagrams
22========
33
4- **🎯 Generate all anagrams of a word with 3-6 letters . **
4+ **🎯 Check whether two words are anagrams of each other . **
55
66For example, the string:
77
88::
99
10- ROT
10+ players
1111
12- has the anagrams (permutations of characters):
12+ has the anagram (permutations of characters):
1313
1414::
1515
16- TOR
17- ORT
18- TRO
19- RTO
20- OTR
16+ parsley
17+
18+ Write a function `anagram() ` that satisfies the following checks:
19+
20+ .. code :: python3
21+
22+ assert anagram("players", "parsley") is True
23+ assert anagram("hello", "world") is False
2124
2225 Hints
2326-----
2427
25- - Look up the function ``itertools.permutations() ``.
26- - You may need an expression like ``''.join(["T", "O", "R"]) ``
28+ - consider sorting the characters
29+ - consider the `set() ` data type
30+ - consider `collections.Counter `
31+ - look up the function `itertools.permutations() `.
2732
2833Extra challenges
2934----------------
3035
31- - Get yourself a word list. Find anagrams that are real words .
32- - Implement the algorithm to generate the anagrams yourself. Get
33- informed about ** dynamic programming **.
36+ - Look for anagrams in the ` SOWPODS word list < https://www.freescrabbledictionary.com/sowpods/download/sowpods.txt >`__ .
37+ - Implement an algorithm to generate all possible anagrams. Inform yourself about ** dynamic programming **.
38+ - what is the time complexity of your implementation?
3439
3540*Translated with * `www.DeepL.com <https://www.DeepL.com/Translator >`__
Original file line number Diff line number Diff line change 1+ from collections import Counter
2+ from itertools import permutations
3+
4+
5+ def anagram (s1 : str , s2 : str ) -> bool :
6+ """clean and neat solution in O(n log n) time"""
7+ return sorted (s1 ) == sorted (s2 )
8+
9+
10+ def anagram (s1 : str , s2 : str ) -> bool :
11+ """from scratch solution, also O(n log n) because of 'in' """
12+ if len (s1 ) == len (s2 ):
13+ for c1 in s1 :
14+ if c1 not in s2 :
15+ return False
16+ return True
17+ return False
18+
19+ def anagram (s1 : str , s2 : str ) -> bool :
20+ """faster O(n) but fails for character duplicates"""
21+ return set (s1 ) == set (s2 )
22+
23+ def anagram (s1 : str , s2 : str ) -> bool :
24+ """using counter dict, covers duplicates and should be O(n)"""
25+ return Counter (s1 ) == Counter (s2 )
26+
27+
28+ def anagram (s1 : str , s2 : str ) -> bool :
29+ """super slow, probably O(n!)"""
30+ return tuple (s1 ) in permutations (s2 )
31+
32+
33+
34+ assert anagram ("players" , "parsley" ) is True
35+ assert anagram ("hello" , "foo" ) is False
You can’t perform that action at this time.
0 commit comments