How can I perform algebra such as apple + apple = 2 apple?

Viewed 56

Is its possible to define an algebra for string objects? For example:

  • apple + apple = 2 apple
  • apple + orange = orange + apple
  • apple + 3.5 apple = 4.5 apple

Are there built-in functions that could do that? Is the creation of a class structure necessary?

1 Answers

You could use SymPy to define symbolic variables for this type of algebra.

>>> from sympy import *
>>> apple = symbols('apple')
>>> orange = symbols('orange')
>>> apple + apple
2*apple
>>> apple + orange
apple + orange
>>> apple + 3.5 * apple
4.5*apple
Related