Skip to content

Instantly share code, notes, and snippets.

@mirekfranc
Created May 11, 2015 21:07
Show Gist options
  • Save mirekfranc/64d50c311853d315cf28 to your computer and use it in GitHub Desktop.
Save mirekfranc/64d50c311853d315cf28 to your computer and use it in GitHub Desktop.
python's generator methods...
from random import shuffle
class Generators(object):
def __init__(self, n):
self.a = range(n)
def __iter__(self):
for e in self.a:
yield e
def backward(self):
for e in reversed(self.a):
yield e
def inorder(self, key=lambda x: x):
for e in sorted(self.a, key=key):
yield e
def randomly(self):
tmp = self.a[:]
shuffle(tmp)
for e in tmp:
yield e
a = Generators(4)
print 'forward'
for i in a:
print "%02d" % i
print 'backward'
for i in a.backward():
print "%02d" % i
print 'inorder'
for i in a.inorder(lambda x: -x):
print "%02d" % i
print 'forward'
for i in a:
print "%02d" % i
print 'randomly'
for i in a.randomly():
print "%02d" % i
print 'backward'
for i in a.backward():
print "%02d" % i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment