1

While working within python 3, I have created a calculator that accepts string inputs such as "-28 + 4.0/3 * 5" and other similar mathematical equations. As an exercise I had wanted to support exponentiation through use of the '^' key such that inputs like "5.23 * 2^4/3^2 -1.0" or other equations that contain values to a certain power would be functional. However, implementation with my current code has proven difficult. Not wanting to scrap my work, I realized that I could implement this if I could find a way to take the original string and selectively solve for the '^' operations such that inputs like the aforementioned "5.23 * 2^4/3^2 -1.0" would become "5.23 * 16/9 -1.0" which I could then feed into the code written prior. Only problem is, I am having some trouble isolating these pieces of the equations and was hoping someone might be able to lend a hand.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52

1 Answers1

0

As binary and infix operators, you could split the string into symbols (numbers, operators), assign priority to operators and then rearrange it into (prefix-notation-like) stack.

Or split the input string into the parts separated by exponent mark, each number at the end-begining of neighbooring sub strings could then be cut, evaluated and replaced: "6 * 4^3 +2" -> ["6 * 4", "3 + 2"] -> "6 *" + x + "+ 2"

Zerg Overmind
  • 955
  • 2
  • 14
  • 28