Created
June 3, 2020 14:09
-
-
Save illume/584b3aed6e9d62121e2e5843f2376562 to your computer and use it in GitHub Desktop.
Decision trees in python using recursion and eval.
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
# Decision trees in python using recursion and eval. | |
TREE_SIMPLE = { | |
"expression": 'state["x"] > 1', | |
True: {"result": "b"}, | |
False: {"result": "a"}, | |
} | |
def decide(state, node): | |
return ( | |
node["result"] | |
if "result" in node | |
else decide(state, node[eval(node["expression"])]) | |
) | |
print(decide(state={"x": 1}, node=TREE_SIMPLE)) # a | |
print(decide(state={"x": 2}, node=TREE_SIMPLE)) # b | |
TREE = { | |
"expression": 'state["x"] > 0', | |
True: { | |
"expression": 'state["x"] > 1', | |
True: {"result": "c"}, | |
False: {"result": "b"}, | |
}, | |
False: {"result": "a"}, | |
} | |
print(decide(state={"x": 0}, node=TREE)) # a | |
print(decide(state={"x": 1}, node=TREE)) # b | |
print(decide(state={"x": 2}, node=TREE)) # c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment