Skip to content

Instantly share code, notes, and snippets.

@fnielsen
Created July 24, 2013 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fnielsen/6070697 to your computer and use it in GitHub Desktop.
Save fnielsen/6070697 to your computer and use it in GitHub Desktop.
Generators as pipes
def peak_to_peak(iterable):
"""
From an input iterable find the present maximum range. Only yield when the range gets larger
"""
it = iter(iterable)
first_value = it.next()
the_min = first_value
the_max = first_value
while True:
value = it.next()
if value < the_min:
the_min = value
yield the_max - the_min # Only yield when peak changed
elif value > the_max:
the_max = value
yield the_max - the_min # Only yield when peak changed
import random
def randoms():
while True:
yield random.random() # Just get some random numbers
# Application with finite list
for peak in peak_to_peak([1, 2, 3, 5, -5, 3, 3, 8, 10, 100, 1, 1]):
print(peak)
# Application with infinite "list"
for peak in peak_to_peak(randoms()):
print(peak)
# Another "pipe"
def stop_at(iterable, limit=10):
it = iter(iterable)
while True:
value = it.next()
yield value
if value > limit:
break
def randoms():
"""Gaussian distributed variables"""
while True:
yield random.normalvariate(0, 1)
for peak in stop_at(peak_to_peak(randoms()), 10.5):
print(peak)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment