2019年1月3日木曜日

開発環境

問題解決のPythonプログラミング ―数学パズルで鍛えるアルゴリズム的思考 (Srini Devadas (著)、黒川 利明 (翻訳)、オライリージャパン)の17章(アナグラム狂)、練習問題(問題3)の解答を求めてみる。

コード

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)

入出力結果(Terminal, cmd(コマンドプロンプト), Jupyter(IPython))

$ ./sample3.py -v
Trying:
    anagrams(['ate', 'but', 'eat', 'tub', 'tea'])
Expecting:
    {('a', 'e', 't'): ['ate', 'eat', 'tea'], ('b', 't', 'u'): ['but', 'tub']}
ok
1 items had no tests:
    __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']
['abed', 'bade', 'bead']
['mace', 'acme', 'came']
['acre', 'care', 'race']
['abut', 'tabu']
['mean']
['abet', 'beat', 'beta']
ate
eat
but
tub
abed
bade
bead
mace
acme
came
acre
care
race
abut
tabu
mean
abet
beat
beta
$

0 コメント:

コメントを投稿