2024-04-28 16:42:58 发布
网友
我正在编写一个数学表达式检查器。我有这个字符串:
oper = "((234+3.32)+(cos4-sin65))"
我想通过分离所有“()”和运算符减去数字或三角比来拆分此字符串,以得到以下结果:
oper = ['(', '(', '234', '+', '3.32', ')', '+', '(', 'cos4', '-', 'sin65', ')', ')']
如何分割?你知道吗
有一个更简单的方法,使用它:
oper = "((234+3.32)+(cos4-sin65))" separators=["(",")","+","-"] def my_split(o, l, j="@"): for e in l: o = o.replace(e, j+e+j) return [e for e in o.split(j) if e] print(my_split(oper, separators))
红宝石:
oper = "((234+3.32)+(cos4-sin65))" re = Regexp.union("(" ,")", "+", "-", /[^()\-+]+/) p oper.scan(re) # => ["(", "(", "234", "+", "3.32", ")", "+", "(", "cos4", "-", "sin65", ")", ")"]
下面是我的示例解决方案。你知道吗
oper = "((234+3.32)+(cos4-sin65))" separators = ['(', ')', '+', '-', 'cos', 'sin'] def sep_at_beg(x): for separator in separators: if len(x) >= len(separator) and x.startswith(separator): if separator in ['cos', 'sin']: if len(x) > len(separator)+1 and x[len(separator)+1].isdigit(): return x[:len(separator)+2] return x[:len(separator)+1] return separator return False def separate(x): return_x = [] idx = 0 so_far = '' while idx < len(x): separator = sep_at_beg(x[idx:]) if separator: if so_far: return_x.append(so_far) return_x.append(separator) so_far = '' idx += len(separator) else: so_far += x[idx] idx += 1 if so_far: return_x.append(so_far) return return_x oper = separate(oper) print(oper)
输出:
['(', '(', '234', '+', '3.32', ')', '+', '(', 'cos4', '-', 'sin65', ')', ')']
有一个更简单的方法,使用它:
红宝石:
下面是我的示例解决方案。你知道吗
输出:
相关问题 更多 >
编程相关推荐