Stack experiment

Matimus mccredie at gmail.com
Tue Apr 3 12:21:23 EDT 2007


On Apr 3, 8:57 am, t... at finland.com wrote:
> Hi! Im new to Python and doing exercise found from internet. It is
> supposed to evaluate expression given with postfix operator using
> Stack() class.
>
> class Stack:
>      def __init__(self):
>          self.items = []
>
>      def push(self, item):
>          self.items.append(item)
>
>      def pop(self):
>          return self.items.pop()
>
>      def isEmpty(self):
>          return (self.items == [])
>
> def evaluatePostfix(expr):
>      import re
>      tokenList = re.split(" ([^0-9])", expr)
>      stack = Stack()
>      for token in tokenList:
>          if token == '' or token == ' ':
>              continue
>          if token == '+':
>              sum = stack.pop() + stack.pop()
>              stack.push(sum)
>          elif token == '*':
>              product = stack.pop() * stack.pop()
>              stack.push(product)
>          else:
>              stack.push(int(token))
>          return stack.pop()
>
> print evaluatePostfix("56 47 + 2 *")
>
> Errormsg:
> Traceback (most recent call last):
>    File "C:\*\postfix1.py", line 31, in <module>
>      print evaluatePostfix("56 47 + 2 *")
>    File "C:\*\postfix1.py", line 28, in evaluatePostfix
>      stack.push(int(token))
> ValueError: invalid literal for int() with base 10: '56 47'
>
> How can I avoid the error and get desired result?

Two things:
1. The regular expression contains a space, so it is trying to split
on a space character followed by a non number, when you really want to
split on any nonnumber. Remove the space.

tokenList = re.split(" ([^0-9])", expr) -> tokenList =
re.split("([^0-9])", expr)

2. The return statement in evaluatePostfix is part of the for loop, it
will exit on the first loop.

This:

    for token in tokenList:
        if token == '' or token == ' ':
            continue
        if token == '+':
            sum = stack.pop() + stack.pop()
            stack.push(sum)
        elif token == '*':
            product = stack.pop() * stack.pop()
            stack.push(product)
        else:
            stack.push(int(token))
        return stack.pop()

Should Be:

    for token in tokenList:
        if token == '' or token == ' ':
            continue
        if token == '+':
            sum = stack.pop() + stack.pop()
            stack.push(sum)
        elif token == '*':
            product = stack.pop() * stack.pop()
            stack.push(product)
        else:
            stack.push(int(token))
    return stack.pop()




More information about the Python-list mailing list