Python:数学表达式解析

2024-06-25 22:48:39 发布

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

Python: 因此,我正在开发一个程序(这是一个类赋值),它将采用一个表达式,如3/4/5或32432/23423/2354325或3425*343/254235或43252+34254-2435等(对于所有从+,-,/,*开始的运算符)。并将解出表达式。

我不能用EVAL!!

我不能使用更高级别的代码,我最多只能使用下面网站中的字符串操纵器来拆分字符串。

http://docs.python.org/2/library/stdtypes.html#typesseq

我的方法是查看用户输入的表达式,然后使用find函数来查找运算符,然后使用这些运算符和切片函数(例如s[0:x])。下面是我所拥有的,但不幸的是它不起作用:*请注意,打印语句仅用于调试目的。 编辑:为什么在运行程序并输入表达式时没有定义x?

z= (input("expression:")).strip()

def finding(z):
    if "/" in z:
        x=z.find("/")
        print("hi1")
    elif "*" in z:
        x=z.find("*")
        print("hi2")
    elif "+" in z:
        x=z.find("+")
        print("hi3")
    elif "-" in z:
        x=z.find("-")
        print("hi4")
    else:
        print("error, not math expression")
    return x

def Parsing(z,x):

    x= finding(z)
    qw=z.s[0:x]
    print (qw)
# take the x-value from function finding(z) and use it to split 

finding(z)
Parsing(z,x)

Tags: 函数字符串in程序表达式def运算符find
3条回答

我认为,最简单的方法是实现一个Shunting-yard algorithm以后缀表示法转换公式,然后从左到右执行它。

但是由于这是一个课堂作业,你应该自己做实际的实现,我已经给了你比我应该给的更多。

如果您只是在将输入分解成各个部分时遇到问题,这里有一些东西可以帮助您。我尽量让它可读,这样你至少可以理解它的作用。如果你需要我解释的话,我会解释其中的任何部分:

def parse(text):
    chunks = ['']

    for character in text:
        if character.isdigit():
            if chunks[-1].isdigit():   # If the last chunk is already a number
                chunks[-1] += character  # Add onto that number
            else:
                chunks.append(character) # Start a new number chunk
        elif character in '+-/*':
            chunks.append(character)  # This doesn't account for `1 ++ 2`.

    return chunks[1:]

示例用法:

>>> parse('123 + 123')
['123', '+', '123']
>>> parse('123 + 123 / 123 + 123')
['123', '+', '123', '/', '123', '+', '123']

剩下的就交给你了。如果不允许使用.isdigit(),则必须用低级Python代码替换它。

Why is x not defined when I run the program and enter an expression?

x不在作用域中,您只在方法中定义它,并尝试在其他地方访问它。

z= (input("expression:")).strip()

def finding(z):
    # ... removed your code ...
    # in this method, you define x, which is local
    # to the method, nothing outside this method has
    # access to x
    return x

def Parsing(z,x):

    x= finding(z) # this is a different x that is assigned the 
                  # return value from the 'finding' method.
    qw=z.s[0:x] # I'm curious as to what is going on here.
    print (qw)
# take the x-value from function finding(z) and use it to split 

finding(z) # here, z is the value from the top of your code
Parsing(z,x) # here, x is not defined, which is where you get your error.

因为Parsing已经在调用finding来获取x的值,所以不需要将其传递到Parsing,也不需要在Parsing外部调用finding(z),因为您不在任何地方存储该值。

def Parsing(z):

    x= finding(z) # this is a different x that is assigned the 
                  # return value from the 'finding' method.
    qw=z.s[0:x] # I'm curious as to what is going on here.
    print (qw)
# take the x-value from function finding(z) and use it to split 

# finding(z)  -- not needed 
Parsing(z)

相关问题 更多 >