473,474 Members | 1,850 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Stack experiment

tom
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?
Apr 3 '07 #1
11 1758

to*@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?
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().

Apr 3 '07 #2
On Apr 3, 10:57 am, t...@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?
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(product)
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

Apr 3 '07 #3

<ky******@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.
Apr 3 '07 #4
to*@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)
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(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?
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

Apr 3 '07 #5
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', '
*', '']

Apr 3 '07 #6
On Apr 3, 8:57 am, t...@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()

Apr 3 '07 #7
On Apr 3, 11:17 am, Steve Holden <s...@holdenweb.comwrote:
t...@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)

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(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?

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

Apr 3 '07 #8

<ir****@gmail.comwrote in message
news:11**********************@w1g2000hsg.googlegro ups.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 ;)
Apr 3 '07 #9

<to*@finland.comwrote in message news:5Q***************@read3.inet.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.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)

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

Apr 3 '07 #10
tom
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.
Apr 3 '07 #11
ky******@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

Apr 3 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Andrew | last post by:
Last night I was reading about implementing my own stack. The example given pushes items on and off the stack at the start and end of each procedure (ie. in a std module). What's not so clear is...
41
by: Nitin Bhardwaj | last post by:
Hi all, I wanted to know whether the stack in a C program is growing upwards or downwards.So I wrote a little code to see that.Please guide me as to whether this code is correct in telling this...
1
by: CrazyCube | last post by:
does any body got some files about Orthogonal Experiment?? i really need it now ,if anybody got ,please send them to me my mailbox is : yuxh312@hotmail.com
8
by: LedZep | last post by:
What up everyone, I have to write a program that uses a stack to determine whether a string is a palindrome (a string that is spelled identically backward and forward). The program has to...
54
by: CoreyWhite | last post by:
The following experiment is a demonstration of TIME TRAVEL. When writing this program, and testing it out I found that sometimes the program would engage itself in time travel but other times it...
1
by: alfie27 | last post by:
I currently have a working program that is a stack that stores integers. Now i have to convert it to store strings instead of integers. I have been working on this for hours and just keep getting...
7
by: DevNull | last post by:
Hello everyone, I decided to pick c++ back up after not really having used it much in 10 years. Just as a point of refference, there was no standard C++ last time I used regularly. Anyways...
11
by: jimxoch | last post by:
Hi list, Most STL containers are storing their data on the heap. (although some std::string implementations are notable exceptions) Of course, using the heap as storage increases flexibility and...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.