Python: 数学表达式解析

4

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])来处理。但是以下代码很不幸地无法运行:*请注意, print 语句仅用于调试目的。

编辑:当我运行程序并输入表达式后,为什么 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)

1
你没有问过类似的问题吗?我知道昨天我已经回答了这个问题。两天前也有其他人回答了这个问题。没有人会替你完成作业。 - Blender
你能解释一下这个答案有什么问题吗? - Blender
@Blender 基于以上原因,请撤销您给我负面的评价。 - SeesSound
你尝试过修改那段代码以适应你的需求吗? - Blender
@blender 是的,我试过了,但是我无法操作它,因为我不是那么高级,也没有完全理解那篇帖子中的代码,所以我只能放弃。在新的帖子中争论旧的帖子是荒谬的...我编辑了我的帖子。如果你认为这个问题是我的作业作弊,那么很遗憾,我学不会计算机科学了。 - SeesSound
显示剩余4条评论
3个回答

3

如果您只是在将输入拆分为其各个部分方面遇到问题,这里有一些帮助您的内容。我尽可能地使它易读,以便您至少可以理解它的作用。如果您需要,我可以解释其中的任何部分:

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代码替换它。


可能只是我自己的问题,但这段代码与你要做的事情的普通英语解释并没有太大的区别。isdigit()返回True,如果字符串仅由数字组成'1'.isdigit() == True - Blender
你介意和我一起聊天吗? - SeesSound
@user1716168:你不小心编辑掉了链接。 - Blender
我从未放置过链接...我从未在这个网站上使用过聊天,但是一个提示出现在上面,要求我将对话转移到聊天中。您介意提供一个我可以加入的链接吗? - SeesSound
让我们在聊天中继续这个讨论。点击此处进入聊天室 - Blender
显示剩余8条评论

2
最简单的做法,我认为是使用逆波兰表达式实现Shunting-yard算法,然后从左到右执行方程。但由于这是一项课堂作业,你应该自己完成实际的实现,我已经给了你比应该给的更多信息了。

很抱歉,这完全没有帮助。一个用户给了我一个与您上述方法相关的具体示例,我意识到我无法使用该方法。 - SeesSound
那么,为什么你不就那个方法提出问题并说明你遇到的问题,而是要重复整个问题呢? - Burhan Khalid
实际上它确实符合您的需求,它尊重操作的优先级,并且不需要任何外部库。我知道这一点,因为我之前在业余时间用Python实现过这个功能。 - willtrnr
我的原帖并没有说我可以使用任何内置函数。它说我可以使用任何字符串内置函数...因此它不适合我的需求。该死,我现在受到了很多压力... - SeesSound
我使用了数组、字符串和字符串内置函数来完成它。除非你不能使用数组,否则我看不出有任何问题。另外,请别误解,我只是想向你展示我的解决方案并不难,而且我认为值得一试。如果你真的想要,明天我可以贴上我的代码。不过别期望太高,我是匆忙完成的。 - willtrnr
显示剩余3条评论

0
当我运行程序并输入表达式时,为什么x没有被定义?
因为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)

我该如何将第一个函数中的 X 传递到第二个函数中? - SeesSound
由于您正在第二个函数中调用第一个函数,并且存储结果“x = finding(z)”,因此您已经在第二个函数中拥有它。 - Burhan Khalid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接