Skip to content

Instantly share code, notes, and snippets.

@ppmx
Created May 6, 2018 15:32
Show Gist options
  • Select an option

  • Save ppmx/8a80d02366d40daa98903afce6d14481 to your computer and use it in GitHub Desktop.

Select an option

Save ppmx/8a80d02366d40daa98903afce6d14481 to your computer and use it in GitHub Desktop.
rough logic bug in python
#!/usr/bin/env python3
class Expression:
OPERATORS = ['+', '-']
@staticmethod
def parse(expression):
# If it is a leaf-expression return even a leaf:
if len(expression) == 1:
return Expression(int(expression[0]), None, None)
# We may implement some validation check if the input is not validated
# enough. We may also check if the input operators are in
# Expression.OPERATORS..
l, r = Expression.parse(expression[0]), Expression.parse(expression[2:])
return Expression(expression[1], l, r)
def __init__(self, value, left, right):
"""
value, left and right may be any object. In this implementation
we use string for operators and integer for values but this may vary
for future purposes. It is important that the given objects implement
all used operators (in evaluate()).
"""
self.value, self.left, self.right = value, left, right
def is_leaf(self):
"""
This function returns true only if the expression does not have
any successor.
"""
return self.left == None and self.right == None
def evaluate(self):
if self.is_leaf():
return self.value
if self.value == '+':
return self.left.evaluate() + self.right.evaluate()
if self.value == '-':
return self.left.evaluate() - self.right.evaluate()
def __str__(self):
if self.is_leaf():
return str(self.value)
return str(self.left) + self.value + str(self.right)
def balance(self):
raise NotImplementedError
def main():
expr = Expression.parse("1+2-3+4")
print(expr)
print(expr.evaluate())
if __name__ == "__main__":
main()
@ppmx

ppmx commented May 6, 2018

Copy link
Copy Markdown
Author

Mind this fuc** logic bug. If you run this code the output is:

mx@ordos ~/work/CODING/algorithms/math (git)-[master] % python3 expression_tree.py
1+2-3+4
-4

@ppmx

ppmx commented May 8, 2018

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment