fork download
  1. from functools import partial
  2.  
  3. class Tree:
  4. def __init__(self, op, left, right):
  5. self.op = op
  6. self.left = left
  7. self.right = right
  8.  
  9. @classmethod
  10. def reducer(cls, left, right, ops):
  11. return cls(
  12. op = ops.pop(0), #shift
  13. left = left,
  14. right = right
  15. )
  16.  
  17. def __str__(self):
  18. return '({self.left} {self.op} {self.right})'.format(self=self)
  19.  
  20.  
  21. ops = ['+', '-', '*']
  22. x = [1, 2, 3, 4]
  23.  
  24. reducer = partial(Tree.reducer, ops = ops)
  25.  
  26. ret = reduce(reducer, x)
  27.  
  28. print(ret)
Success #stdin #stdout 0.01s 7896KB
stdin
Standard input is empty
stdout
(((1 + 2) - 3) * 4)