''' Created on Dec 30, 2015 @author: Brett Paufler Copyright Brett Paufler CAN KILL Test page for weekly code snippets Sample: Wrapper for a Generator Function Trampoline Function ''' from itertools import count def fibo(): '''Generator yielding next number in Fibonacci sequence.''' f = [0, 1] for _ in count(): f.append(sum(f)) yield f.pop(0) def fibonacci(nth): '''Returns nth number in Fibonacci sequence''' f = fibo() for _ in range(nth - 1): f.next() return f.next() def trampoline(fun, nth): '''Returns nth number in passed func sequence.''' f = fun() for _ in range(nth - 1): f.next() return f.next() def start_at_tenth(fun): '''Wrapper that advances wrapped generator function to the tenth number in sequence.''' def wrapper(): f = fun() for _ in range(9): f.next() return f return wrapper def test_fibo_funcs(nth=10): '''Tests the different fibo constructs. nth must be an int += 10, as that's where the wrapper starts.''' assert nth >= 10 #Set Up Base fibo() generator f = fibo() for _ in range(nth - 1): f.next() f_fibo = f.next() #Set Up Wrapper Generator @start_at_tenth def f10(): return fibo() f_10 = f10() for _ in range(nth - 9): f_start_ten = f_10.next() #All tests should give same value for nth fibonacci number tests = [f_fibo, f_start_ten, fibonacci(nth), trampoline(fibo, nth)] print tests assert all([t == tests[0] for t in tests]) test_fibo_funcs() test_fibo_funcs(45) #print 'Head start' def nth_fibo(n): f = [0, 1] for _ in range(n): f.append(sum(f)) f.pop(0) return f.pop(0) #print 'start loop' #for n in range(10): # print nth_fibo(n) def fact(): f = 1 for i in count(1):# in xrange(100): f *= i yield f def factorial(n): f = fact() for _ in range(n - 1): f.next() return f.next()