소스 검색

Fixed parentheses issue in expression that use both plus and minus.

Taddeus Kroes 14 년 전
부모
커밋
b99a1f72b3
2개의 변경된 파일15개의 추가작업 그리고 1개의 파일을 삭제
  1. 4 1
      line.py
  2. 11 0
      tests/test_line.py

+ 4 - 1
line.py

@@ -93,7 +93,10 @@ def generate_line(root):
 
                     # Check if there is an precedence conflict.
                     # If so, add parentheses
-                    if pred(child) < node_pred:
+                    child_pred = pred(child)
+
+                    if child_pred < node_pred or \
+                            (child_pred == node_pred and s != child.title()):
                         exp = '(' + exp + ')'
 
                     e.append(exp)

+ 11 - 0
tests/test_line.py

@@ -23,6 +23,17 @@ class TestLine(unittest.TestCase):
         times = Node('*', plus, plus)
         self.assertEquals(generate_line(times), '(1 + 2) * (1 + 2)')
 
+    def test_parentheses_equal_precedence(self):
+        l0, l1, l2 = Leaf(1), Leaf(2), Leaf(3)
+        plus = Node('+', l1, l2)
+        minus = Node('-', l0, plus)
+        self.assertEquals(generate_line(minus), '1 - (2 + 3)')
+
+    def test_parentheses_nary(self):
+        l0, l1, l2 = Leaf(1), Leaf(2), Leaf(3)
+        plus = Node('+', Node('+', l0, l1), l2)
+        self.assertEquals(generate_line(plus), '1 + 2 + 3')
+
     def test_function(self):
         exp = Leaf('x')
         inf = Leaf('oo')