line.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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_assoc = 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 assoc(node):
  41. """
  42. Get the associativity of an operator node.
  43. """
  44. if not isinstance(node, Leaf) and len(node) > 1:
  45. op = node.title()
  46. for i, group in enumerate(operators):
  47. if op in group:
  48. return i
  49. return max_assoc
  50. def traverse(node):
  51. """
  52. The expression tree is traversed using preorder traversal:
  53. 1. Visit the root
  54. 2. Traverse the subtrees in left-to-right order
  55. """
  56. s = node.title()
  57. if isinstance(node, Leaf):
  58. return s
  59. arity = len(node)
  60. if is_operator(node):
  61. if arity == 1:
  62. # Unary operator
  63. s += traverse(node[0])
  64. else:
  65. # N-ary operator
  66. node_assoc = assoc(node)
  67. e = []
  68. for child in node:
  69. exp = traverse(child)
  70. # Check if there is an assiociativity conflict.
  71. # If so, add parentheses
  72. if assoc(child) < node_assoc:
  73. exp = '(' + exp + ')'
  74. e.append(exp)
  75. s = (' ' + s + ' ').join(e)
  76. else:
  77. # Function
  78. s += '(' + ', '.join(map(traverse, node)) + ')'
  79. return s
  80. return traverse(root)