Iterators, Generators, and Decorators in Python

I worked through Iterators, Generators and Decorators sections of the Computational Statistics in Python tutorial, and although this code is similar to the tutorial, it is modified in ways to make it retainable to myself:


 # Iterators can be created from sequences with the built-in function iter()  
 """http://people.duke.edu/~ccc14/sta-663/FunctionsSolutions.html#iterators"""  
   
 xs = [n for n in range(10)]  
 x_iter = iter(xs)  
   
 [x for x in x_iter]  
   
 for x in x_iter:  
   print(x)  
   
   
 # Generators  
 """http://people.duke.edu/~ccc14/sta-663/FunctionsSolutions.html#generators"""  
   
 # Functions containing the 'yield' keyword return iterators  
 # After yielding, the function retains its previous state  
 def limit_seats(n):  
   """Limits number and counts down"""  
   for i in range(n, 0, -1):  
     yield i  
   
 counter = limit_seats(10)  
   
 for count in counter:  
   print(count)  
   
   
 # Iterators can also be created with 'generator expressions'  
 # which can be coded similar to list generators but with parenthesis  
 # in place of square brackets  
 maxUsers = [x for x in range(10)]  
 for x in maxUsers:  
   print(x)  
   
 # Many built-in Python functions return iterators including file handlers  
 for line in open('requirements.txt'):  
   print(line)  
   
 # Decorators  
 # Here is a simple decorator to time an arbitrary function  
 def func_timer(func):  
   """Times how long the function took."""  
   def f(*args, **kwargs):  
     import time  
     start = time.time()  
     results = func(*args, **kwargs)  
     print("Elapsed: %.2fs" % (time.time() - start))  
     return   
   
 @func_timer  
 def fibonacciWithCacheWithTimer(n, cache={0:1, 1:1}):  
   try:  
     return cache[n]  
   except:  
     cache[n] = fibonacci(n-1) + fibonacci (n-2)  
     return cache[n]  
   
 [fibonacciWithCacheWithTimer(n) for n in range(10)]  
   

Popular posts from this blog

Decision Tree in R, with Graphs: Predicting State Politics from Big Five Traits

Chi-Square in R on by State Politics (Red/Blue) and Income (Higher/Lower)

Logistic Regression in R on State Voting in National Elections and Income