line.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. from node import Leaf
  2. def generate_line(root):
  3. """
  4. Print an expression tree in a single text line. Where needed, add
  5. parentheses.
  6. >>> from node import Node, Leaf
  7. >>> l0, l1 = Leaf(1), Leaf(2)
  8. >>> plus = Node('+', l0, l1)
  9. >>> print generate_line(plus)
  10. 1 + 2
  11. >>> plus2 = Node('+', l0, l1)
  12. >>> times = Node('*', plus, plus2)
  13. >>> print generate_line(times)
  14. (1 + 2) * (1 + 2)
  15. >>> l2 = Leaf(3)
  16. >>> uminus = Node('-', l2)
  17. >>> times = Node('*', plus, uminus)
  18. >>> print generate_line(times)
  19. (1 + 2) * -3
  20. >>> exp = Leaf('x')
  21. >>> inf = Leaf('oo')
  22. >>> minus_inf = Node('-', inf)
  23. >>> integral = Node('int', exp, minus_inf, inf)
  24. >>> print generate_line(integral)
  25. int(x, -oo, oo)
  26. """
  27. operators = [
  28. ('+', '-'),
  29. ('*', '/', 'mod'),
  30. ('^', )
  31. ]
  32. max_pred = len(operators)
  33. def is_operator(node):
  34. """
  35. Check if a given node is an operator (otherwise, it's a function).
  36. """
  37. label = node.title()
  38. either = lambda a, b: a or b
  39. return reduce(either, map(lambda x: label in x, operators))
  40. def pred(node):
  41. """
  42. Get the precedence of an operator node.
  43. """
  44. # Check binary and n-ary operators
  45. if not isinstance(node, Leaf) and len(node) > 1:
  46. op = node.title()
  47. for i, group in enumerate(operators):
  48. if op in group:
  49. return i
  50. # Unary operator and leaves have highest precedence
  51. return max_pred
  52. def traverse(node):
  53. """
  54. The expression tree is traversed using preorder traversal:
  55. 1. Visit the root
  56. 2. Traverse the subtrees in left-to-right order
  57. """
  58. if not node:
  59. return '<empty expression>'
  60. s = node.title()
  61. if not node.nodes:
  62. return s
  63. arity = len(node)
  64. if is_operator(node):
  65. if arity == 1:
  66. # Unary operator
  67. s += traverse(node[0])
  68. else:
  69. # N-ary operator
  70. node_pred = pred(node)
  71. e = []
  72. for child in node:
  73. exp = traverse(child)
  74. # Check if there is an precedence conflict.
  75. # If so, add parentheses
  76. if pred(child) < node_pred:
  77. exp = '(' + exp + ')'
  78. e.append(exp)
  79. s = (' ' + s + ' ').join(e)
  80. else:
  81. # Function
  82. s += '(' + ', '.join(map(traverse, node)) + ')'
  83. return s
  84. return traverse(root)