Skip to content

Instantly share code, notes, and snippets.

@illume
Created June 3, 2020 14:09
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 illume/584b3aed6e9d62121e2e5843f2376562 to your computer and use it in GitHub Desktop.
Save illume/584b3aed6e9d62121e2e5843f2376562 to your computer and use it in GitHub Desktop.
Decision trees in python using recursion and eval.
# 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