I am trying to get any mathematical string to split into a list by operators (i.e. "+", "-", "/", "*"), while keeping anything in a matching number of brackets together as one list element.
Examples and desired outputs
Here are some very random examples and the Желаемые результаты того, чего я хочу достичь: < /p>
Код: Выделить всё
import math
equation = "5+5*10"
equation_segmented = ["5", "+", "5", "*", "10"]
equation = "(2*2)-5*(math.sqrt(9)+2)"
equation_segmented = ["(2*2)", "-", "5", "*", "(math.sqrt(9)+2)"]
equation = "(((5-3)/2)*0.5)+((2*2))*(((math.log(5)+2)-2))"
equation_segmented = ["(((5-3)/2)*0.5)", "+", "((2*2))", "*", "(((math.log(5)+2)-2))"]
Найти решение
Моей первой мысли было использование Regex:
.
Код: Выделить всё
import re
equation_segmented = re.split("([\+|\-|\*|\/]|\(.*\))", equation)
< /code>
Проблема здесь, однако, заключается в том, что она не учитывает соответствующие кронштейны.equation_segmented = re.split("([\+|\-|\*|\/])", equation)
Подробнее здесь: https://stackoverflow.com/questions/796 ... n-matching