4

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Gideon
  • 43
  • 2
  • 2
    Looks like [SymPy](https://www.sympy.org/en/index.html) could work for this. – 0x5453 May 08 '20 at 20:02
  • You mean you want to build monoids and monads in Python? Functional programming? – Catalina Chircu May 08 '20 at 20:04
  • 1
    @CatalinaChircu no, I don't think the OP is referring to anything like that, it sounds like they want a computer algebra system. – juanpa.arrivillaga May 08 '20 at 20:08
  • No, there are no built-in functions for this. An no, a class structure is *never really necessary to accomplish anything*. However, often, it is a useful way to organize your code. In any case, what you are describing isn't strings. It *sounds* like you want a computer algebra system, something that manipulates symbols using mathematics. `sympy` is a popular library for this sort of thing in Python. – juanpa.arrivillaga May 08 '20 at 20:09

1 Answers1

5

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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218