開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 12.(Tuples)のExercises 12-4.(No. 2897)を取り組んでみる。
Exercises 12-4.(No. 2897)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def get_words(filename):
with open(filename) as f:
words = {line.strip() for line in f}
return words | {'i', 'a', ''}
def children(word):
return {word[:i] + word[i + 1:] for i, _ in enumerate(word)}
reducible_words = {'i', 'a', ''}
def is_reducible(word, words):
if word in reducible_words:
return True
if word == '':
return True
for child in children(word):
if (child in words) and is_reducible(child, words):
reducible_words.add(word)
return True
return False
if __name__ == '__main__':
filename = 'words.txt'
words = get_words(filename)
reducibles = filter(lambda word: is_reducible(word, words), words)
print(sorted(reducibles, key=len, reverse=True)[0])
入出力結果(Terminal, IPython)
$ ./sample4.py complecting $
0 コメント:
コメントを投稿