因此,下面的代码获取一个输入信息字符串(一个数学表达式),并使用find函数来查找“*/+-”中的一个运算符,并相应地分隔字符串。你知道吗
def splitting1(z):
for operators in "*/+-":
if operators in z:
position1= z.find(operators)
position2= z.rfind(operators)
text_before_operators= (z[:position1]).strip()
text_after_operators= (z[(position1+1):(position2)]).strip()
return text_before_operators,text_after_operators
我的问题是,如果我有一个输入表达式,比如3/5*7
,那么position1
将首先找到*
,然后再找到/
。我希望代码将“position1”与最左边的运算符相关联。在使用for/in函数时,有没有办法省略运算符的优先级?如果没有,是否有更好的字符串操纵器可以省略优先顺序。你知道吗
注z是输入。输入仅限于两个运算符,以防产生歧义。你知道吗
您正在迭代
*/+-
,因此找到的第一个字符就是返回的第一个字符。你知道吗您基本上需要找到所有这些操作符的索引,然后找到最大或最小的。尝试重新编写此函数以适用于字符串的另一端:
一个稍微更具脓性的解决方案是这样的:
看起来您正在尝试lex,因此我建议您研究专门为此目的设计的模块,例如^{} 。你知道吗
是的。你知道吗
尽管如此,我认为您在本例中的思路是正确的,但是您缺少了一些递归(为了使这些更通用的lexer):
找到最左边的运算符而不考虑其优先级(即省略运算符优先级)的一种方法是重新排列您迭代的内容:
注意,这些函数返回与原始函数不同的结果。
相关问题 更多 >
编程相关推荐