[Tutor] creating pop method for stack class
Alan Gauld
alan.gauld at btinternet.com
Fri Jul 18 08:25:58 CEST 2008
"Christopher Spears" <cspears2002 at yahoo.com> wrote
>I am almost done with a stack class that I wrote:
Some comments...
> class Stack(list):
> def isempty(self):
> length = len(self)
> if length == 0:
> return True
> else:
> return False
This can just be
return bool(len(self))
> def peek(self):
> length = len(self)
> if length == 0:
> return 0
How do you know whether zero was the last item or an error?
Better to raise an IndexError or a ValueError or define your
own StackEmptyError.
> else:
> last_index = length - 1
> return self[last_index]
You don't need the last_index thing, just use -1
-1 is always the last item.
> def stackpop(self):
> length = len(self)
> if length == 0:
> print "Empty list!"
And this is inconsistent with the previous method.
Keep your error jhandling style the same or confuse your users.
In general putting print statements inside class methods is a
bad idea. Raise an exception instead.
> else:
> last_index = length - 1
> stackpop_val = self[last_index]
> self = self[:last_index]
> return stackpop_val
I don't think reassigning self is a good idea.
I'd go with deleting the last member using del(self[-1])
> My main problem seems to be getting this part to work:
>
> def stackpop(self):
...
> self = self[:last_index]
> return stackpop_val
see comment above.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list