import os import sys LETTERS = {} for idx,letter in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ"): LETTERS[letter] = idx+1 def get_word_value(word): total_value = 0 for letter in word: val = LETTERS[letter] total_value += val return total_value all_triangle_numbers = [] def update_triangles(val): top_idx = len(all_triangle_numbers) if top_idx == 0: top_idx = 1 all_triangle_numbers.append(1.0) while all_triangle_numbers[-1] < val: all_triangle_numbers.append(0.5*top_idx*float(top_idx+1)) top_idx += 1 def is_triangle(val): if val > len(all_triangle_numbers): update_triangles(val) if val in all_triangle_numbers: return True else: return False def main(): w_file = open("p42_words.txt", "r") words = w_file.read().split(",") num_triangles = 0 for word in [ x[1:-1].upper() for x in words ]: w_value = get_word_value(word) if is_triangle(w_value): num_triangles += 1 print num_triangles if __name__ == "__main__": sys.exit(main())