Created
June 10, 2019 10:35
-
-
Save louisswarren/2a3427dc92edffc6bedc308552763441 to your computer and use it in GitHub Desktop.
Python co-routine to store a single value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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