Last active
July 7, 2016 18:05
-
-
Save ohenrik/45d9023f3aff44345d514e850e3be9f6 to your computer and use it in GitHub Desktop.
Chaos course - Iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# ## Defining the iterator generator function | |
# In[63]: | |
def iteration_generator(seed, equation=None): | |
# First check that an equation is provided | |
if equation == None: | |
raise ValueError("Missing equation, please provide a function.") | |
# Initiate result | |
result = seed | |
# Deliver the result when requested | |
while True: | |
yield result | |
# create the next result. | |
result = equation(result) | |
# ----- | |
# In[64]: | |
# This is the funciton provided to the iterator_generator | |
def double_it(x): | |
return x*2 | |
# In[65]: | |
# First create the generator object, passing in the seed (1) and the function (double_it) | |
g = iteration_generator(1, double_it) | |
# Then create an array of the first 5 results | |
print([next(g) for _ in range(5)]) | |
print("") | |
print("Running the last line again would return the next 5 results") | |
print([next(g) for _ in range(5)]) | |
# In[66]: | |
g = iteration_generator(0, double_it) | |
print([next(g) for _ in range(5)]) | |
# In[67]: | |
g = iteration_generator(2, double_it) | |
print([next(g) for _ in range(5)]) | |
# ------ | |
# In[68]: | |
def square_it(x): | |
return x**2 | |
# In[69]: | |
g = iteration_generator(0, square_it) | |
print([next(g) for _ in range(5)]) | |
# In[70]: | |
g = iteration_generator(0.5, square_it) | |
print([next(g) for _ in range(5)]) | |
# In[71]: | |
g = iteration_generator(1, square_it) | |
print([next(g) for _ in range(5)]) | |
# In[72]: | |
g = iteration_generator(2, square_it) | |
print([next(g) for _ in range(5)]) | |
# ------ | |
# In[73]: | |
def func_1(x): | |
return 4*x - 12 | |
# In[74]: | |
g = iteration_generator(0, func_1) | |
print([next(g) for _ in range(5)]) | |
# In[75]: | |
g = iteration_generator(5, func_1) | |
print([next(g) for _ in range(5)]) | |
# ---- | |
# In[76]: | |
def func_2(x): | |
return x/2 + 10 | |
# In[77]: | |
g = iteration_generator(4, func_2) | |
series = [next(g) for _ in range(20)] | |
series | |
# In[78]: | |
from bokeh.charts import TimeSeries, show, output_notebook | |
output_notebook() | |
# In[45]: | |
plt = TimeSeries(series) | |
# In[46]: | |
plt.show() | |
# In[ ]: | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment