-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathsolution_1.py
More file actions
58 lines (42 loc) · 1.1 KB
/
solution_1.py
File metadata and controls
58 lines (42 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python
# coding=utf-8
# Python Script
#
# Copyleft © Manoel Vilela
#
#
from functools import wraps
from os.path import dirname, join
def memo(fn):
cache = {}
miss = object()
@wraps(fn)
def wrapper(*args, **kwargs):
result = cache.get(args, miss)
if result is miss:
result = fn(*args)
cache[args] = result
return result
return wrapper
def load_words():
with open("../p042_words.txt") as f:
words = f.read().strip("\n").split(",")
return [x.lower().strip("\"") for x in words]
def string_to_num(string):
from string import ascii_lowercase as alpha
return sum([alpha.index(x) + 1 for x in string])
def triangles():
from itertools import count
for n in count(start=1, step=1):
yield ((n + 1) * n) // 2
@memo
def is_triangle(num):
for t in triangles():
if num == t:
return True
if t > num:
return False
def solution():
return sum(1 for x in load_words() if is_triangle(string_to_num(x)))
if __name__ == '__main__':
print(solution())