Basic evaluation for trees

This commit is contained in:
Bertrand Benjamin 2018-01-21 18:16:08 +03:00
parent 7d00d3342a
commit 1176b6f608
3 changed files with 85 additions and 7 deletions

View File

@ -0,0 +1,46 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 lafrite <lafrite@Poivre>
#
# Distributed under terms of the MIT license.
"""
Evaluating a binary tree
"""
from .operator import OPERATORS
def compute(node, left_v, right_v):
"""
Computing a node
:example:
>>> compute("+", 1, 2)
3
>>> compute("-", 1, 2)
-1
>>> compute("-", None, 2)
-2
"""
op = OPERATORS[node]
lv = left_v
rv = right_v
if lv is None:
return op["_operate"](rv)()
try:
return op["operate"](lv)(rv)
except NotImplemented:
return op["roperate"](rv)(lv)
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del

View File

@ -6,13 +6,33 @@
# #
# Distributed under terms of the MIT license. # Distributed under terms of the MIT license.
OPERATORS = { OPERATORS = {
"+": {"priority":0}, "+": {'repr': "+",
"-": {"priority":1}, 'precedence': 0,
"*": {"priority":2}, 'operate': lambda x: x.__getattribute__("__add__"),
"/": {"priority":3}, 'roperate': lambda x: x.__getattribute__("__radd__"),
"^": {"priority":4}, },
"-": {'repr': "-",
'precedence': 1,
'_operate': lambda x: x.__getattribute__("__neg__"),
'operate': lambda x: x.__getattribute__("__sub__"),
'roperate': lambda x: x.__getattribute__("__rsub__"),
},
"*": {'repr': "*",
'precedence': 2,
'operate': lambda x: x.__getattribute__("__mul__"),
'roperate': lambda x: x.__getattribute__("__rmul__"),
},
"/": {'repr': "/",
'precedence': 3,
'operate': lambda x: x.__getattribute__("__div__"),
'roperate': lambda x: x.__getattribute__("__rdiv__"),
},
"^": {'repr': "^",
'precedence': 4,
'operate': lambda x: x.__getattribute__("__pow__"),
'roperate': lambda x: x.__getattribute__("__rpow__"),
},
} }

View File

@ -243,7 +243,15 @@ class Tree(object):
+ +
> 3 * 4 > 3 * 4
> 2 > 2
>>> from .evaluate import compute
>>> tt = t.apply_on_last_level(compute)
>>> print(tt)
+
> 12
> 2
>>> ttt = tt.apply_on_last_level(compute)
>>> print(ttt)
14
""" """
left_is_leaf = 0 left_is_leaf = 0
right_is_leaf = 0 right_is_leaf = 0
@ -286,6 +294,10 @@ class Tree(object):
>>> t.apply(to_nested) >>> t.apply(to_nested)
('+', (('*', (3, 4)), 2)) ('+', (('*', (3, 4)), 2))
>>> from .evaluate import compute
>>> t.apply(compute)
14
""" """
try: try:
left_value = self.left_value.apply(function) left_value = self.left_value.apply(function)