Skip to content

Instantly share code, notes, and snippets.

@ppmx
Created May 6, 2018 18:56
Show Gist options
  • Select an option

  • Save ppmx/0f9fa1cfc736735a94e21ee4e05fa7c9 to your computer and use it in GitHub Desktop.

Select an option

Save ppmx/0f9fa1cfc736735a94e21ee4e05fa7c9 to your computer and use it in GitHub Desktop.
Fix for logic bug in expression code
#!/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[:-2]), Expression.parse(expression[-1])
return Expression(expression[-2], 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

An invalid fix (imho!) would be the left-side-traversal of the constructed tree, because with that concept we would ignore brackets in general and do some flaws in the other direction.

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