-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathsolution_1.py
More file actions
91 lines (71 loc) · 1.96 KB
/
solution_1.py
File metadata and controls
91 lines (71 loc) · 1.96 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
# coding=utf-8
# Python Script
#
# Copyleft © Manoel Vilela
#
#
from functools import wraps
def memo(fn):
"""Memorization decorator"""
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
class TruncatePrime(int):
"""
Class to verify if a prime is a truncate:
Truncate prime example: 3797
pop left: 3797 -> 379 -> 37 -> 3
pop right: 3797 -> 797 -> 97 -> 7
"""
def __init__(self, x):
self.num = x
self.string = str(x)
self.len = len(self.string)
def __add__(self, other):
return self.num + other
@property
def left(self):
return all([self.is_prime(x) for x in self.walk('left')])
@property
def right(self):
return all([self.is_prime(x) for x in self.walk('right')])
@property
def self(self):
return self.is_prime(self.num)
def walk(self, orientation):
if orientation is 'right':
return (int(self.string[:x]) for x in range(1, self.len))
elif orientation is 'left':
return (int(self.string[x:]) for x in range(1, self.len))
@memo
def is_prime(self, x):
if x < 2:
return False
for d in range(2, int(x ** 0.5) + 1):
if x % d == 0:
return False
return True
@property
def is_truncate(self):
if len(self.string) < 2:
return False
return self.self and self.left and self.right
def search_truncate(until=11):
n = 0
truncate_primes = []
while len(truncate_primes) < until:
t = TruncatePrime(n)
if t.is_truncate:
truncate_primes.append(t)
n += 1
return sum(truncate_primes)
if __name__ == '__main__':
print(search_truncate())