From bfb3640986af5c780b19d4165f36892336cdbcc9 Mon Sep 17 00:00:00 2001 From: Abigail Date: Tue, 11 May 2021 00:32:12 +0200 Subject: Python solutions for week 112 --- challenge-112/abigail/python/ch-2.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 challenge-112/abigail/python/ch-2.py (limited to 'challenge-112/abigail/python/ch-2.py') diff --git a/challenge-112/abigail/python/ch-2.py b/challenge-112/abigail/python/ch-2.py new file mode 100644 index 0000000000..3e2a55750d --- /dev/null +++ b/challenge-112/abigail/python/ch-2.py @@ -0,0 +1,21 @@ +#!/opt/local/bin/python + +# +# See ../README.md +# + +# +# Run as: python ch-1.py < input-file +# + +import fileinput + +cache = {0: 1, 1: 1} + +def fib (n): + if not n in cache: + cache [n] = fib (n - 1) + fib (n - 2) + return (cache [n]) + +for line in fileinput . input (): + print (fib (int (line))) -- cgit From d498fd3ea3e1df8c647b83e5e4922e6af971960b Mon Sep 17 00:00:00 2001 From: Abigail Date: Tue, 11 May 2021 19:29:08 +0200 Subject: Use closed form to calculate Fibonacci numbers for week 112, part 2. --- challenge-112/abigail/python/ch-2.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) (limited to 'challenge-112/abigail/python/ch-2.py') diff --git a/challenge-112/abigail/python/ch-2.py b/challenge-112/abigail/python/ch-2.py index 3e2a55750d..da542b06f2 100644 --- a/challenge-112/abigail/python/ch-2.py +++ b/challenge-112/abigail/python/ch-2.py @@ -5,17 +5,14 @@ # # -# Run as: python ch-1.py < input-file +# Run as: python ch-2.py < input-file # import fileinput +from math import sqrt -cache = {0: 1, 1: 1} - -def fib (n): - if not n in cache: - cache [n] = fib (n - 1) + fib (n - 2) - return (cache [n]) +SQRT5 = sqrt (5) +PHI = (1 + SQRT5) / 2 for line in fileinput . input (): - print (fib (int (line))) + print (round (pow (PHI, int (line) + 1) / SQRT5)) -- cgit