【问题标题】:Python: I'm misunderstanding stack logic, but I'm not sure where [closed]Python:我误解了堆栈逻辑,但我不确定在哪里[关闭]
【发布时间】:2013-05-14 17:51:41
【问题描述】:

我有一个函数通过使用堆栈来评估中缀表达式。 (打赌你以前从未见过这个。)它采用列表格式的表达式,其中列表中的每个项目都是单个字符(操作数、运算符或括号。)

s = Stack()
tempvar = None
ops = ['+','-','/','*']

for i in expression:
    if i == '('
        s.push(i)

    elif i.isdigit():
        if tempvar is None:
            tempvar = i
        else:
            tempvar = tempvar + i

    elif i in ops:
        if tempvar is not None:
            s.push(tempvar)
            tempvar = None

        popped = str(s.pop() + str(s.pop())
        last = s.pop()
        if last is not ')':
            popped += str(last)

        for x in popped:
            print 'Popping',x,'from the stack.'

        print 'Popping',last,'from the stack.'

        math = eval(popped)
        s.push(math)
        print 'Pushing',math,'back onto the stack.

我使用“tempvar”字符串的意图是,由于我逐字符地迭代表达式,我会遇到多位数字的问题。所以我用它们制作了一个字符串,然后将字符串推入堆栈。

我有两个问题,我不知道为什么我会遇到其中一个。

输入

((21*2)-(4/2))

我得到输出

Pushing ( onto the stack
Pushing ( onto the stack
Pushing 21 onto the stack
Pushing * onto the stack
Pushing 2 onto the stack
Popping 2 from the stack
**Popping * from the stack
Popping 2 from the stack
Popping 1 from the stack
Popping 21 from the stack**

我用星号标出了问题部分。我对堆栈的理解是,它们的功能是后进先出,它们不在乎顶部是什么,pop 将其取下。 21 是我推入堆栈的第一件事,但它看起来像被单独读取(作为 21,最后一个弹出条目)并分成两半作为 '2' 和 '1' - 但我希望 1会在2之前弹出!我对堆栈或我所写的内容有什么误解?

【问题讨论】:

  • 那么inStack 是什么?你没有定义它。
  • 我在这里输入时的命名不一致,现在我已经修复了。

标签: python stack


【解决方案1】:
for x in popped:
    print 'Popping',x,'from the stack.'

popped 是一个字符串,所以这个循环会一次遍历一个字符。

【讨论】:

  • Duh...谈论在错误的地方寻找问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 2016-02-22
  • 2022-01-17
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
相关资源
最近更新 更多