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
|
""" Challenge 153 Task 1"""
class LeftFactCalculator:
"""Challenge 153 Task 1"""
def __init__(self):
# keep seen factorials in a cache to speed things up
self.fact_cache = {0: 1}
self.left_fact_cache = {0: 0}
def calculate_factorial(self, what: int):
"""Calculate factorial on one number"""
try:
return self.fact_cache[what]
except KeyError:
pass
# let's utilize the fact that we are processing the numbers in sequence
self.fact_cache[what] = what * self.fact_cache[what - 1]
return self.fact_cache[what]
def calculate_left_fact(self, what: int):
"""Calculate the left factorial of one number"""
try:
return self.left_fact_cache[what]
except KeyError:
pass
# let's utilize the fact that we are processing the numbers in sequence
self.left_fact_cache[what] = (
self.calculate_factorial(what - 1) + self.left_fact_cache[what - 1]
)
return self.left_fact_cache[what]
def get_left_factorial(self, what: int):
"""Get the solution for the task"""
output = []
for i in range(1, what + 1):
output.append(self.calculate_left_fact(i))
return output
def main():
calculator = LeftFactCalculator()
assert calculator.get_left_factorial(10) == [
1,
2,
4,
10,
34,
154,
874,
5914,
46234,
409114,
]
if __name__ == "__main__":
main()
|