Skip to content

Instantly share code, notes, and snippets.

@dburles
Forked from keyo/Counter.py
Created December 22, 2011 01:26
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 dburles/1508491 to your computer and use it in GitHub Desktop.
Save dburles/1508491 to your computer and use it in GitHub Desktop.
Python useless counter class
"""
░░░█░░░░░░▄██▀▄▄░░░░░▄▄▄░░​░█
░▄▀▒▄▄▄▒░█▀▀▀▀▄▄█░░░██▄▄█░​░░█
█░▒█▒▄░▀▄▄▄▀░░░░░░░░█░░░▒▒​▒▒▒█
█░▒█░█▀▄▄░░░░░█▀░░░░▀▄░░▄▀​▀▀▄▒█
░█░▀▄░█▄░█▀▄▄░▀░▀▀░▄▄▀░░░░​█░░█
░░█░░░▀▄▀█▄▄░█▀▀▀▄▄▄▄▀▀█▀█​█░█
░░█░░░░██░░▀█▄▄▄█▄▄█▄████░​█
░░░█░░░░▀▀▄░█░░░█░█▀██████​░█
░░░░▀▄░░░░░▀▀▄▄▄█▄█▄█▄█▄▀░​░█
░░░░░░▀▄▄░▒▒▒▒░░░░░░░░░░▒░​░░█
░░░░░░░░░▀▀▀▄▄▄▄▄▄▄▄▄▄▄▄▄▄​▄▀
"""
class Counter(object):
""" This class counts stuff... """
def __init__(self, start = 0, end = 10, increment = 1):
self.start = start
self.end = end
self.increment = increment
def __iter__(self):
# this method is called when a Counter object is used as an iterator (e.g. in a for loop).
i = self.start
while i < self.end:
yield i
i += self.increment
def __reversed__(self):
i = self.end
while i > self.start:
i -= self.increment
yield i
def __str__(self):
return str(map(str,self))
#instantiate a new Counter object, counting even numbers only
c = Counter(start = 0, end = 20, increment = 2)
print("As string")
print c
print("Forward iterator, comma separated")
#map each value from c into the str function to get a list of printable strings.
print ",".join(map(str,c))
print("Backward")
#reversed(c) gets an iterator from Counter.__reversed__ instead of Counter.__iter__
print map(str,reversed(c))
print("Loop")
for x in c:
print x
print("List comprehension of numbers divisible by 3")
print([x for x in c if x % 3 == 0 ])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment