## 2016年7月16日土曜日

### Python - Lists(reverse pairs)

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 10.(Lists)のExercises 10-11.(No. 2386)を取り組んでみる。

Exercises 10-11.(No. 2386)

コード(Emacs)

``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import math import time import random import bisect def words2list(filename): out = [] with open(filename) as f: for word in f: word = word.strip() out.append(word) return out def in_bisect(elems, val): l = len(elems) i = bisect.bisect_left(elems, val) if i != l and elems[i] == val: return i return None if __name__ == '__main__': filename = 'words.txt' words = words2list(filename) words.sort() n = len(words) l = [] for i, word in enumerate(words): reversed_word = word[::-1] j = in_bisect(words, reversed_word) if not j is None: l.append((word, reversed_word)) for pair in l[:10] + l[-10:]: print(pair) ```

```\$ ./sample11.py
('aa', 'aa')
('aba', 'aba')
('abut', 'tuba')
('aga', 'aga')
('agar', 'raga')
('agas', 'saga')
('agenes', 'senega')
('ah', 'ha')
('yak', 'kay')
('yam', 'may')
('yap', 'pay')
('yaps', 'spay')
('yar', 'ray')
('yard', 'dray')
('yaw', 'way')
('yaws', 'sway')
('yay', 'yay')
('yeh', 'hey')
\$
```