2016年6月13日月曜日

Python - Case Study Word Play(Forbidden letters)

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 9.(Case Study Word Play)のExercises 9-3(No. 1961)を取り組んでみる。

Exercises 9-3(No. 1961)

コード(Emacs)

``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- def avoids(word, forbidden_letters): for letter in forbidden_letters: if letter in word: return False return True if __name__ == '__main__': letters = [chr(letter) for letter in range(ord('a'), ord('z') + 1)] # 5だと時間がかかったから 2 に変更 # (それでも時間がかかったからアルゴリズムの変更が必要かも。。) forbidden_letters = [a + b for a in letters for b in letters if a < b] # for d in letters # for e in letters # if a < b < c < d < e] print(len(forbidden_letters)) n = 0 combinations = set() with open('words.txt') as f: words = f.read().split() print(len(words)) for letters in forbidden_letters: count = 0 for word in words: if avoids(word, letters): count += 1 if count > n: combinations = {letters} n = count elif count == n: combinations.add(letters) print(combinations, n) ```

```\$ ./sample3.py
325
113809
{'jq'} 110435
\$
```