Skip to content

Instantly share code, notes, and snippets.

@KyleJamesWalker
Last active January 7, 2017 01:20
Show Gist options
  • Save KyleJamesWalker/40f42777e4c2b8b89c68a210f7c08bbc to your computer and use it in GitHub Desktop.
Save KyleJamesWalker/40f42777e4c2b8b89c68a210f7c08bbc to your computer and use it in GitHub Desktop.
Generator that can tell the future based on a iterable object
'''Generator that can tell the future based on a iterable object
Update: Created a helper class to simplify the core generator code, left original to verify against.
'''
from collections import deque
class Bucket(object):
def __init__(self, size=0):
self.size = size
self.contents = deque([], self.size)
def filled(self):
return True if len(self.contents) is self.size else False
def insert(self, item):
self.contents.append(item)
return self.filled()
def view(self):
return list(self.contents)
def fill(self, item):
while len(self.contents) < self.size:
self.insert(item)
def flush(self):
steps = len(self.contents)
if steps and not self.filled():
self.fill(None)
yield self.view()
for _ in range(steps - 1):
self.insert(None)
yield self.view()
self.contents.clear()
def simple_fortune(tell, future_dist=0):
window = Bucket(future_dist + 1)
for x in tell:
if window.insert(x):
yield tuple(window.view())
for x in window.flush():
yield tuple(x)
def fortune_teller(tell, future=0):
'''Generator that tells the future.
Example:
fortune_teller([1, 2, 3], 1) >> (1, 2), (2, 3), (3, None)
'''
window = []
tell_iter = iter(tell)
iter_process = True
over_inspect = 0
# Fill window with future
while len(window) <= future:
try:
window.append(tell_iter.next())
except StopIteration:
over_inspect += 1
window.append(None)
# Walk through the remainder of the iter
while iter_process and over_inspect <= future:
yield tuple(window)
try:
item = tell_iter.next()
except StopIteration:
iter_process = False
item = None
window = window[1:] + [item]
# Finished remainder of values
while future > over_inspect:
yield tuple(window)
future -= 1
window = window[1:] + [None]
def main():
''' A few quick tests
'''
# No Future
print[x for x in fortune_teller([1, 2, 3])]
print[x for x in simple_fortune([1, 2, 3])]
# Yes Future
print[x for x in fortune_teller([1, 2, 3], 1)]
print[x for x in simple_fortune([1, 2, 3], 1)]
# Over Future
print[x for x in fortune_teller([1], 1)]
print[x for x in simple_fortune([1], 1)]
# No item
print[x for x in fortune_teller([], 1)]
print[x for x in simple_fortune([], 1)]
# Big Future
print[x for x in fortune_teller([1, 2, 3], 5)]
print[x for x in simple_fortune([1, 2, 3], 5)]
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment