Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Created June 10, 2019 10:35
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 louisswarren/2a3427dc92edffc6bedc308552763441 to your computer and use it in GitHub Desktop.
Save louisswarren/2a3427dc92edffc6bedc308552763441 to your computer and use it in GitHub Desktop.
Python co-routine to store a single value
from collections import namedtuple
Arrow = namedtuple('Arrow', 'tail head')
# Single input single output
def siso():
def inner():
x = yield
yield
yield x
g = inner()
next(g)
return g
# Single operation of simplifying the state by removing replacing arrows with
# their heads where possible.
def search_step(state, did_simplify):
simplified = False
for element in state:
if isinstance(element, Arrow) and element.tail in state:
yield element.head
simplified = True
else:
yield element
did_simplify.send(simplified)
# Search until state is simplified as much as possible. Detect whether to
# continue searching using the siso.
def search(state):
while True:
did_simplify = siso()
state = set(search_step(state, did_simplify))
if not next(did_simplify):
break
return state
state = {
1, 2, 3, 4,
Arrow(1, 5),
Arrow(2, 6),
Arrow(6, 7),
Arrow(7, Arrow(3, 8)),
}
print(list(search(state)))
"""
[1, 2, 3, 4, 5, 6, 7, 8]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment