Friday, May 22, 2015

Project Euler #42 - Coded triangle numbers

프로젝트 오일러 42번
알파벳을 숫자로 변환했을 때, 단어의 알파벳 숫자합이 삼각수가 되는 경우는 몇 번인가?
A => 1, B => 2, ... S => 19.. 
이렇게 할당하면 알파벳 합은 ABC => 6, SKY => 55가 된다. 첨부한 파일의 대문자 단어들 중 알파벳 합이 삼각수(1,2,3,6,10,...)이 되는 경우는 몇 번?

ord('A') = 65, ord('S') = 83, ... 을 이용하면 쉽다.

words = open('Euler/p042_words.txt').read().strip('"').split('","')
#print max([len(w) for w in words])

tri, n = {1}, 3
for i in range(3,30):
    n += i; tri.add(n)

cnt = 0
for word in words:
    nm = 0
    for s in word:
        nm += ord(s)-64
    if nm in tri: cnt += 1

print cnt




No comments: