gpt4 book ai didi

Python 前缀/中缀/后缀表达式求值

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:23 25 4
gpt4 key购买 nike

关于代码的简短介绍:我必须创建一个类来计算前缀、后缀或中缀表达式。它必须判断是否是pre/post/infix并将其转换为后缀,例如从'/x7'转换的代码中的prefixTOpostfix()(其他已不需要)方法到 'x7/',表达式在方法 edit() 中从 'x7/' 编辑到 'x 7/'。这两种方法都工作正常,在多个示例上进行了测试(不在这里发布整个代码和分配,但也不需要它们。所提出的问题只是我遇到的错误,别担心我不是在要求我的作业的解决方案)。还有 assign 方法,因为可以有变量,例如 'a = 3',并且它可以位于表达式中的某个位置。问题:当我运行print(v.evaluate('x 7/'))(postfix中已有的内容)时,其中x = 14,它应该返回 2 。但是,当我运行 print(v.evaluate('/x 7')) (前缀中的内容)时,它返回 None两个表达式在运行方法“x 7/”后看起来完全相同(我在代码中测试了prints),两个堆栈是相同的。首先是 '14',然后是 '14 7',最后是 '2'。当我将 return(s.pop()) 更改为 return(s.top()) 时,两个表达式都被很好地计算为 '2'。那么为什么 return(s.pop()) 不适用于第二个呢?如果对代码还有更多疑问或有些内容不够清楚,请告诉我,我会尝试以不同的方式进行解释。

class MyClass:

class Stack:
...

def __init__(self):
self.table = {}

def __repr__(self):
...

def assign(self, variable, exp):

if '+-*/%' in exp: # temporary solution
exp = self.evaluate(exp)

self.table[variable] = exp

def evaluate(self, exp):

if exp[0] in '+-*/%': # Prefix
new_exp = self.prefixTOpostfix(exp)
self.evaluate(new_exp)

elif exp[len(exp)-1] in '+-*/%': # Postfix
s = self.Stack()
exp = self.edit(exp) # from 'x7/' to 'x 7 /'

for item in exp.split():

if item == '+':
s.push(s.pop() + s.pop())

... # other operations

elif prvok == '/':
temp = s.pop()
if temp == 0:
return None
s.push(s.pop() // temp) # it has to be // !

else: # if it is number / variable
if item in self.table:
s.push(int(self.table[item]))
else:
s.push(int(item))

s.printOUT()

return(s.pop())

else: # Infix
...


def prefixTOpostfix(self, exp):

...

def edit(self, exp):

...

最佳答案

    if exp[0] in '+-*/%': # Prefix
new_exp = self.prefixTOpostfix(exp)
self.evaluate(new_exp)

您需要返回递归调用的结果。

    if exp[0] in '+-*/%': # Prefix
new_exp = self.prefixTOpostfix(exp)
return self.evaluate(new_exp)

关于Python 前缀/中缀/后缀表达式求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29438287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com