fibonacci.html


001| ####################################################################################################
002| from sys import argv
003| from os import path
004| from time import perf_counter_ns
005| ####################################################################################################
006| BasePath = r'C:\CJS\prj\Python\app\maths'
007| 
008| 
009| ##================================================================================================##
010| def fib1 (n):
011|     '''Fibonacci #1: naive multiple recursion.'''
012| 
013|     return n if n < 2 else (fib1(n-1) + fib1(n-2))
014| 
015| ##================================================================================================##
016| def fib2 (n, lst=None):
017|     '''Fibonacci #2: single recursion.'''
018| 
019|     if lst is None:
020|         return fib2(n, [0, 1])
021| 
022|     if len(lst) < 2:
023|         lst.append(lst[0]+1)
024| 
025|     ix = len(lst) - 1
026|     lst.append(lst[ix] + lst[ix-1])
027| 
028|     return lst if n <= len(lst) else fib2(n, lst)
029| 
030| ##================================================================================================##
031| def fib3 (n, lst=[]):
032|     '''Fibonacci #3: single recursion.'''
033| 
034|     if len(lst) < 1:
035|         lst.append(0)
036| 
037|     if len(lst) < 2:
038|         lst.append(lst[0]+1)
039| 
040|     ix = len(lst)
041|     lst.append(lst[ix-1] + lst[ix-2])
042| 
043|     return lst if n <= len(lst) else fib3(n, lst)
044| 
045| 
046| ##================================================================================================##
047| def fib_seq_print (seq):
048|     '''Print a Fibonacci sequence.'''
049|     for ix,fn in enumerate(seq):
050|         print(f'{ix:4d} = {fn}')
051|     print()
052| 
053| 
054| ##================================================================================================##
055| def fib_seq_no_cache (seq_len):
056|     '''Basic Fibonacci sequence generator.'''
057| 
058|     def fib (n):
059|         '''Canonical Recursive Fibonacci function.'''
060|         if n < 2: return 1
061|         return (fib(n-2) + fib(n-1))
062| 
063|     return [fib(n) for n in range(seq_len)]
064| 
065| 
066| ##================================================================================================##
067| def cache (obj):
068|     '''Cache Decorator for fib function.'''
069|     cache.previous = {}
070| 
071|     def wrapper (n):
072|         if n in cache.previous:
073|             return cache.previous[n]
074|         r = obj(n)
075|         cache.previous[n] = r
076|         return r
077| 
078|     return wrapper
079| 
080| ##================================================================================================##
081| def fib_seq_cache (seq_len):
082|     '''Cached Fibonacci sequence generator.'''
083| 
084|     @cache
085|     def fib (n):
086|         '''Canonical Recursive Fibonacci function.'''
087|         if n < 2: return 1
088|         return (fib(n-2) + fib(n-1))
089| 
090|     return [fib(n) for n in range(seq_len)]
091| 
092| 
093| ##================================================================================================##
094| def fib_seq_array (seq_len):
095|     '''Array cache Fibonacci sequence generator.'''
096| 
097|     # Create empty sequence array...
098|     seq = [0]*seq_len
099|     seq[0] = 1
100|     seq[1] = 1
101|     seq[2] = 2
102| 
103|     def fib (n):
104|         if seq[n]: return seq[n]
105|         seq[n] = (fib(n-2) + fib(n-1))
106|         return
107| 
108|     for n in range(seq_len):
109|         fib(n)
110| 
111|     return seq
112| 
113| 
114| ##================================================================================================##
115| def fib_seq_iterative (seq_len):
116|     '''Iterative Fibonacci sequence generator.'''
117| 
118|     # Create empty sequence array...
119|     seq = [0]*seq_len
120|     seq[0] = 1
121|     seq[1] = 1
122|     seq[2] = 2
123| 
124|     def fib (n):
125|         if seq[n]: return seq[n]
126|         seq[n] = (fib(n-2) + fib(n-1))
127|         return
128| 
129|     for n in range(seq_len):
130|         fib(n)
131| 
132|     return seq
133| 
134| 
135| ##================================================================================================##
136| def fib_seq_mechanical (seq_len, left_hand=1, right_hand=1):
137|     '''Mechanical Iterative Fibonacci sequence generator.'''
138|     # Start with something(s) in left and right hands...
139|     left = left_hand
140|     right = right_hand
141|     # These are the first two Fibonacci numbers...
142|     seq = [left, right]
143| 
144|     # Generate sequence with simple process...
145|     for ix in range(seq_len-2):
146|         # Copy left and right hands to pile...
147|         pile = left + right
148|         # The pile is the next Fibonacci number...
149|         seq.append(pile)
150|         # Move right hand stuff to left hand...
151|         # (Left hand stuff is discarded.)
152|         left = right
153|         # Move the pile to the right hand...
154|         right = pile
155|         # Rinse and repeat...
156| 
157|     # Return the Fibonacci sequence...
158|     return seq
159| 
160| fib_best = fib_seq_mechanical
161| 
162| ##================================================================================================##
163| def print_timing (name, seq_len, ns):
164|     s1 = f'{name}[{seq_len}]'
165|     print(f'{s1:<18s}: {ns/pow(10,6):10.3f} ms')
166| 
167| ##================================================================================================##
168| def demo_fib_seq_no_cache (seq_len=10, print_list=True):
169|     '''Exercise the fib_seq_no_cache function.'''
170|     t0 = perf_counter_ns()
171| 
172|     fs = fib_seq_no_cache(seq_len)
173|     if print_list:
174|         fib_seq_print(fs)
175| 
176|     t1 = perf_counter_ns()
177|     print_timing('basic', seq_len, t1-t0)
178|     return fs
179| 
180| ##================================================================================================##
181| def demo_fib_seq_cache (seq_len=100, print_list=True):
182|     '''Exercise the fib_seq_cache function.'''
183|     t0 = perf_counter_ns()
184| 
185|     fs = fib_seq_cache(seq_len)
186|     if print_list:
187|         fib_seq_print(fs)
188| 
189|     t1 = perf_counter_ns()
190|     print_timing('cache', seq_len, t1-t0)
191|     return fs
192| 
193| ##================================================================================================##
194| def demo_fib_seq_array (seq_len=100, print_list=True):
195|     '''Exercise the fib_seq_array function.'''
196|     t0 = perf_counter_ns()
197| 
198|     fs = fib_seq_array(seq_len)
199|     if print_list:
200|         fib_seq_print(fs)
201| 
202|     t1 = perf_counter_ns()
203|     print_timing('array', seq_len, t1-t0)
204|     return fs
205| 
206| ##================================================================================================##
207| def demo_fib_seq_iterative (seq_len=100, print_list=True):
208|     '''Exercise the fib_seq_iterative function.'''
209|     t0 = perf_counter_ns()
210| 
211|     fs = fib_seq_iterative(seq_len)
212|     if print_list:
213|         fib_seq_print(fs)
214| 
215|     t1 = perf_counter_ns()
216|     print_timing('iterative', seq_len, t1-t0)
217|     return fs
218| 
219| ##================================================================================================##
220| def demo_fib_seq_mechanical (seq_len=100, print_list=True):
221|     '''Exercise the fib_seq_mechanical function.'''
222|     t0 = perf_counter_ns()
223| 
224|     fs = fib_seq_mechanical(seq_len)
225|     if print_list:
226|         fib_seq_print(fs)
227| 
228|     t1 = perf_counter_ns()
229|     print_timing('mechanical', seq_len, t1-t0)
230|     return fs
231| 
232| ##================================================================================================##
233| def speed_demo ():
234|     n = int(argv[1]) if 1 < len(argv) else 1000
235| 
236|     fs1 = demo_fib_seq_no_cache(33, print_list=False)
237|     fs2 = demo_fib_seq_cache(n, print_list=False)
238|     fs3 = demo_fib_seq_array(n, print_list=False)
239|     fs4 = demo_fib_seq_iterative(n, print_list=False)
240|     fs5 = demo_fib_seq_mechanical(n, print_list=False)
241| 
242| ##================================================================================================##
243| def main ():
244|     #speed_demo()
245|     return fib_best(100)
246| 
247| ####################################################################################################
248| if __name__ == '__main__':
249|     print(argv[0])
250|     print()
251|     r = main()
252|     print()
253| ####################################################################################################
254| '''eof'''
255|