Stack experiment

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • tom@finland.com

    #1

    Stack experiment

    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.appe nd(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(prod uct)
    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?
  • irstas@gmail.com

    #2
    Re: Stack experiment


    tom@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.appe nd(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(prod uct)
    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?
    Obviously your tokens are wrong since one of the tokens is '56 47' as
    the error message indicates.

    import re
    print re.split(" ([^0-9])", "56 47 + 2 *")

    It looks like you'd just want expr.split().

    Comment

    • kyosohma@gmail.com

      #3
      Re: Stack experiment

      On Apr 3, 10:57 am, t...@finland.co m 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.appe nd(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(prod uct)
      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?
      I don't know why you're using the "re" module. For this, I would skip
      it. Change your code so that it looks like this:

      def evaluatePostfix (expr):
      tokenList = expr.split(" ")
      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(prod uct)
      else:
      stack.push(int( token))
      return stack.pop()

      # this worked for me. There may be something wrong with the "re" code
      in your example, but I don't know enough about that to help in that
      area.

      Mike

      Comment

      • Richard Brodie

        #4
        Re: Stack experiment


        <kyosohma@gmail .comwrote in message
        >There may be something wrong with the "re" code in your example,
        >but I don't know enough about that to help in that area.
        There is a stray leading space in it.


        Comment

        • Steve Holden

          #5
          Re: Stack experiment

          tom@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.appe nd(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)
          If you add a print statement here I think you will find that the
          tokenisation here isn't really what you want:
          >>expr = "56 47 + 2 *"
          >>re.split(" ([^0-9])", expr)
          ['56 47', '+', ' 2', '*', '']
          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(prod uct)
          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?
          I'd try using

          tokenList = split(expr)

          instead - this has the added benefit of removing the spaces, so you can
          simplify your code by removing the case that handles empty tokens and
          sapaces, I suspect.

          regards
          Steve
          --
          Steve Holden +44 150 684 7255 +1 800 494 3119
          Holden Web LLC/Ltd http://www.holdenweb.com
          Skype: holdenweb http://del.icio.us/steve.holden
          Recent Ramblings http://holdenweb.blogspot.com

          Comment

          • irstas@gmail.com

            #6
            Re: Stack experiment

            On Apr 3, 7:14 pm, "Richard Brodie" <R.Bro...@rl.ac .ukwrote:
            <kyoso...@gmail .comwrote in message
            There may be something wrong with the "re" code in your example,
            but I don't know enough about that to help in that area.
            >
            There is a stray leading space in it.
            Nah, I'd say there's a stray ([^0-9]) after the space. With just space
            in it (same as basic split) one would get the tokens 56, 47, +, 2 and
            *. Without the space one would get: ['56', ' ', '47', ' + ', '2', '
            *', '']

            Comment

            • Matimus

              #7
              Re: Stack experiment

              On Apr 3, 8:57 am, t...@finland.co m 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.appe nd(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(prod uct)
              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(prod uct)
              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(prod uct)
              else:
              stack.push(int( token))
              return stack.pop()

              Comment

              • kyosohma@gmail.com

                #8
                Re: Stack experiment

                On Apr 3, 11:17 am, Steve Holden <s...@holdenweb .comwrote:
                t...@finland.co m 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.appe nd(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)
                >
                If you add a print statement here I think you will find that the
                tokenisation here isn't really what you want:
                >
                >>expr = "56 47 + 2 *"
                >>re.split(" ([^0-9])", expr)
                ['56 47', '+', ' 2', '*', '']
                >
                >
                >
                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(prod uct)
                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?
                >
                I'd try using
                >
                tokenList = split(expr)
                >
                instead - this has the added benefit of removing the spaces, so you can
                simplify your code by removing the case that handles empty tokens and
                sapaces, I suspect.
                >
                regards
                Steve
                --
                Steve Holden +44 150 684 7255 +1 800 494 3119
                Holden Web LLC/Ltd http://www.holdenweb.com
                Skype: holdenweb http://del.icio.us/steve.holden
                Recent Ramblings http://holdenweb.blogspot.com
                Steve,

                How do you do "tokenList = split(expr)"? There is no builtin called
                "split".

                Mike

                Comment

                • Richard Brodie

                  #9
                  Re: Stack experiment


                  <irstas@gmail.c omwrote in message
                  news:1175617229 .555905.175790@ w1g2000hsg.goog legroups.com...
                  >There is a stray leading space in it.
                  >
                  Nah, I'd say there's a stray ([^0-9]) after the space.
                  If you regard the spaces as being a required part of the postfix
                  grammar, it would be simpler. But who would design a language
                  where white space was significant ;)


                  Comment

                  • Terry Reedy

                    #10
                    Re: Stack experiment


                    <tom@finland.co mwrote in message news:5QuQh.152$ 9L1.108@read3.i net.fi...
                    | 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.appe nd(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)

                    To see what is wrong, print tokenList.
                    tokenList = expr.split() is probably what you want

                    | 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(prod uct)
                    | 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?
                    | --
                    | http://mail.python.org/mailman/listinfo/python-list
                    |



                    Comment

                    • tom@finland.com

                      #11
                      Re: Stack experiment

                      Ok, I got it running. Thank you!

                      I removed the space and top of that I had foul indentation in return
                      statement.

                      I'll try the approaches you suggest.

                      Comment

                      • Steve Holden

                        #12
                        Re: Stack experiment

                        kyosohma@gmail. com wrote:
                        [...]
                        >
                        Steve,
                        >
                        How do you do "tokenList = split(expr)"? There is no builtin called
                        "split".
                        >
                        Mike
                        >
                        Sorry, that should have been a call to the .split() method of expr, i.e.:

                        tokenList = expr.split()

                        regards
                        Steve
                        --
                        Steve Holden +44 150 684 7255 +1 800 494 3119
                        Holden Web LLC/Ltd http://www.holdenweb.com
                        Skype: holdenweb http://del.icio.us/steve.holden
                        Recent Ramblings http://holdenweb.blogspot.com

                        Comment

                        Working...