Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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