aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLubos Kolouch <lubos@kolouch.net>2022-02-26 12:05:49 +0100
committerLubos Kolouch <lubos@kolouch.net>2022-02-26 12:05:49 +0100
commitf50d577c273c460cafc1ebf53d5ab117a44341a4 (patch)
tree84245d178f08f7781222b84ae24ce4b706d216b4
parent3044a2200c0fb28897de7879e3a7dc05dbeec56c (diff)
downloadperlweeklychallenge-club-f50d577c273c460cafc1ebf53d5ab117a44341a4.tar.gz
perlweeklychallenge-club-f50d577c273c460cafc1ebf53d5ab117a44341a4.tar.bz2
perlweeklychallenge-club-f50d577c273c460cafc1ebf53d5ab117a44341a4.zip
feat(challenge-153/lubos-kolouch/python/ch-1.py): Challenge 153 Task 1 Python LK
-rw-r--r--challenge-153/lubos-kolouch/python/ch-1.py68
1 files changed, 68 insertions, 0 deletions
diff --git a/challenge-153/lubos-kolouch/python/ch-1.py b/challenge-153/lubos-kolouch/python/ch-1.py
new file mode 100644
index 0000000000..cdb8b0a586
--- /dev/null
+++ b/challenge-153/lubos-kolouch/python/ch-1.py
@@ -0,0 +1,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()