Python中缀到后缀求值AttributeError:“list”对象没有属性“split”

2024-09-28 23:26:37 发布

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

这是我的密码:

from StackClass import Stack


def postfixEval(postfix):
    os = Stack()


tokenList = postfix.split()

for token in tokenList:
    if token in "0123456789":
        os.push(int(token))
    else:
        op2 = os.pop()
        op1 = os.pop()
        result = doMath(token,op1,op2)
        os.push(result)
return os.pop()

def doMath(op, op1, op2):
    if op == "*":
        return op1 * op2
    elif op == "/":
    return op1 / op2
elif op == "+":
    return op1 + op2
else:
    return op1 - op2



def pres(p):
    if p is '(':
        return 0
    elif p is '+' or '-':
        return 1
    elif p is '*' or '/':
        return 2
    else:
        return 99

def read(p):
    if p is '(':
        return left
    elif p is ')':
        return right
    elif p is '+' or p is '-' or p is '*' or p is '%' or p is '/':
        return operator
    elif p is ' ':
        return empty    
    else :
        return operand                          




def infixtopostfix(infixexp):

    for i in infixexp :
        type = read(i)
        if type is left :
            outlst.append(i)
        elif type is right :
            next = outlst.pop()
            while next is not '(':
                postfix.append(next)
                next = outlst.pop()
        elif type is operand:
            postfix.append(i)
    elif type is operator:
        p = pres(i)
        while len(outlst) is not 0 and p <= pres(outlst[-1]) :
            postfix.append(outlst.pop())
        outlst.append(i)
    elif type is empty:
        continue

while len(outlst) > 0 :
    postfix.append(outlst.pop())


print "It's postfix notation is ",''.join(postfix)

主程序

如果为真:

postfix = []
outlst = []
operator = -10
operand = -20
left = -30
right = -40
empty = -50


infixexp = raw_input("\nEnter the infix notation : ")
infixtopostfix(infixexp)
print(postfixEval(postfix))   



choice = raw_input("\nDo you want to continue?<1-Yes/0-No>: ")

if choice == '0':
    break

我得到这个错误:AttributeError:'list'对象没有属性'split'。我不知道它是从哪里来的,我试着用join把列表串起来,但是没有效果。我觉得我应该张贴这个,我需要帮助,也为那些谁是有这个错误的问题,以及在堆栈实现和评估。你知道吗

顺便问一下,在infixtopostfix(infixexp)部分,你知道我如何在彼此之间加空格得到结果吗?例如:将其改为13+5*,改为13+5*。我该怎么做?我正在想办法。我在这里回答我自己的问题。如果我能解决问题。但是为了节省时间,有人可能会碰到这个问题,并在过去解决了这个问题。请帮忙:)谢谢!你知道吗

回溯

回溯(最近一次调用上次):文件“练习.py,第112行,在打印(postfix)文件中练习.py,第8行,在后缀标记列表中=后缀.split()AttributeError:“list”对象没有“split”属性


Tags: orreturnifisosdeftypepop
2条回答

在代码中,postfix = []postfix.append(outlst.pop()) 显示postfix是一个列表。列表没有像split()那样的方法,而是可以应用于str对象。你知道吗

间距问题的答案。只需在原始输入后拆分中缀表达式。这样它就可以确认例如100是一个字符串。结果就是我在帖子里写的东西。以防你不知道。你知道吗

相关问题 更多 >