Search code examples
pythonalgebra

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


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?


Solution

  • 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