2016年7月17日日曜日

開発環境

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

Exercises 10-12.(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


def interlock(words, word):
    word0 = word[::2]
    word1 = word[1::2]
    return (
        (not in_bisect(words, word0) is None) and
        (not in_bisect(words, word1) is None)
    )


def interlock_three(words, word):
    for i in range(3):
        word0 = word[i::3]
        if in_bisect(words, word) is None:
            return False
    return True

if __name__ == '__main__':
    filename = 'words.txt'
    words = words2list(filename)
    words.sort()
    n = len(words)
    l = []
    interlocks = [word for word in words if interlock(words, word)]
    interlocks_three = [word for word in words
                        if interlock_three(words, word)]
    print(len(interlocks))
    for word in interlocks[:10] + interlocks[-10:]:
        print('{0}: {1}, {2}'.format(word, word[::2], word[1::2]))
    print(len(interlocks_three))
    for word in interlocks_three[:10] + interlocks_three[-10:]:
        print('{0}: {1}, {2}, {3}'.format(
            word, word[::3], word[1::3], word[2::3]))

入出力結果(Terminal, IPython)

$ ./sample12.py
1254
aahs: ah, as
abbey: aby, be
abied: aid, be
abies: ais, be
abri: ar, bi
abris: ars, bi
abye: ay, be
abyes: ays, be
across: ars, cos
added: add, de
wreaths: wets, rah
wries: wis, re
wriest: wis, ret
yaird: yid, ar
yairds: yid, ars
yeah: ya, eh
yean: ya, en
year: ya, er
yeas: ya, es
yuan: ya, un
113809
aa: a, a, 
aah: a, a, h
aahed: ae, ad, h
aahing: ai, an, hg
aahs: as, a, h
aal: a, a, l
aalii: ai, ai, l
aaliis: ai, ai, ls
aals: as, a, l
aardvark: adr, avk, ra
zymogene: zon, yge, me
zymogenes: zon, yge, mes
zymogens: zon, ygs, me
zymologies: zogs, yli, moe
zymology: zog, yly, mo
zymoses: zos, ys, me
zymosis: zos, ys, mi
zymotic: zoc, yt, mi
zymurgies: zui, yre, mgs
zymurgy: zuy, yr, mg
$

0 コメント:

コメントを投稿

Comments on Google+: