## 2019年1月3日木曜日

### Algorithm - Python - アナグラム狂(キー、リスト、tuple、sorted関数、文字列、辞書の基本、ハッシング)

コード

Python 3

```#!/usr/bin/env python3
def anagrams(corpus: list) -> dict:
'''
>>> anagrams(['ate', 'but', 'eat', 'tub', 'tea'])
{('a', 'e', 't'): ['ate', 'eat', 'tea'], ('b', 't', 'u'): ['but', 'tub']}
'''
anagram_dict = {}
for word in corpus:
t = tuple(sorted(word))
anagram_dict.setdefault(t, [])
anagram_dict[tuple(sorted(word))].append(word)
return anagram_dict

if __name__ == '__main__':
import doctest
doctest.testmod()

corpus = ['ate', 'but', 'eat', 'tub',
'abed', 'mace', 'acre', 'abut', 'mean', 'bade', 'abet', 'care',
'tabu', 'bead', 'beat', 'race', 'acme', 'beta', 'came']
for word in anagrams(corpus).values():
print(word)
for words in anagrams(corpus).values():
for word in words:
print(word)
```

```\$ ./sample3.py -v
Trying:
anagrams(['ate', 'but', 'eat', 'tub', 'tea'])
Expecting:
{('a', 'e', 't'): ['ate', 'eat', 'tea'], ('b', 't', 'u'): ['but', 'tub']}
ok
__main__
1 items passed all tests:
1 tests in __main__.anagrams
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
['ate', 'eat']
['but', 'tub']
['mace', 'acme', 'came']
['acre', 'care', 'race']
['abut', 'tabu']
['mean']
['abet', 'beat', 'beta']
ate
eat
but
tub
abed
mace
acme
came
acre
care
race
abut
tabu
mean
abet
beat
beta
\$
```