problem42

アルファベットを数字に対応させた際の単語の和が三角数になるものの数を数える問題。
まだ、どのように書けば十分なのかというのが把握できていない。これはクラスにした方が良かったかもしれない。

def _str_to_val(offset):
    def _calc(s):
        n = 0
        for c in s:
            n += ord(c) - offset
        return n
    return _calc

def _tri_num(n):
    d = {}
    tmp = 0
    for i in xrange(1, n):
        tmp += i
        d[tmp] = True
    return lambda n : d.get(n)

def consume(file):
    with open(file) as f:
        for word in f.read().split(","):
            yield(word[1:-1].lower())
    
str_to_val =  _str_to_val(ord("a")-1)
is_tri_num = _tri_num(1000)

# print str_to_val("sky")
# print is_tri_num(str_to_val("sky"))

cnt = 0
for word in consume("words.txt"):
    if is_tri_num(str_to_val(word)):
        cnt += 1
print cnt