如何用乘法器拆分任意数学表达式

2024-09-27 00:11:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用乘法器把长的数学方程分开。 表达式以允许空白的字符串形式给出。在

例如:

"((a*b>0) * (e>500)) * (abs(j)>2.0) * (n>1)"

应返回:

^{pr2}$

如果使用除法,事情会变得更复杂,但是假设没有除法。什么是解决这个问题的最具Python式的方法?在


Tags: 方法字符串表达式数学abs事情空白形式
3条回答

您只需使用split()函数:

ans_list = your_string.split(" * ")

注意倍增号周围的空格。这假设您的字符串与您所说的完全相同。在

import re

string = "((a-b>0) * (e + 10>500)) * (abs(j)>2.0) * (n>1)"
signals = {'+','*','/','-'}

###
##

def splitString(string):

    arr_equations = re.split(''([\)]+(\*|\-|\+|\/)+[\(])'',string.replace(" ", ""))

    new_array = []

    for each_equa in arr_equations:

        each_equa = each_equa.strip("()")

        if (not(each_equa in signals)):
            new_array.append(each_equa)

    return new_array

###
##    

print(splitString(string))

您可以使用regex:

s = "((a*b>0) * (e>500)) * (abs(j)>2.0) * (n>1)"
s = ''.join(s.split())
s = re.split(r'([\)]+[\*\+\-/\^]+[\(])', s)
res = []
for x in s:
    x = re.sub(r'(^[\(\)\*\+\-\/]+)', '', x)
    x = re.sub(r'([\(\)]+$)', '', x)
    if len(x) > 0: res.append(x)
print(res)

相关问题 更多 >

    热门问题