[Tutor] palindrome using stack and queue

Alan Gauld alan.gauld at btinternet.com
Tue Aug 4 11:04:30 CEST 2015


On 04/08/15 04:55, Quiles, Stephanie wrote:

>   i have to write a palindrome tester using a stack and a queue.

Some teachers seem determined to force students to use basic
data structures rather than use the features of the language
appropriately. I think that's a stupid waste of time but
if you have such a teacher you need to go with it.

> here iw the code i originally had which worked:
> def main():
>      my_str = input("Enter a string: ")
>      my_str2 = [c for c in my_str.lower() if c.isalpha()]
>      rev_str = reversed(my_str2)
>      # check if the string is equal to its reverse
>      if list(my_str2) == list(rev_str):
>          print(my_str,"is a palindrome")
>      else:
>          print(my_str, "is not a palindrome")

And that's pretty much the best way to do it and apart from the
call to reversed() you are pretty much using a queue and
stack approach.

But since you need to use the classes you've been given...

> class Stack:
> def push(self, obj):
> def pop(self):
> def isEmpty(self):

> stack = Stack()
> stack2 = Stack()

I've no idea why they have 2 stack instances you only need one!

> class Queue:
>      def isEmpty(self):
>      def enqueue(self, item):
>      def dequeue(self):
>      def size(self):

A stack will return items in the opposite order to which
you put them in.

So push() the characters of your input string onto the stack
in much the same way you created my_str2.

pop() the characters back off the stack and concatenate
them to form rev_str.

Compare rev_str and the input to determine if its a
palindrome, as you already do.

Where does the Queue come in? - I honestly don't know.
You could put the characters in a queue before pushing
them into a stack I suppose. But that would just be for
the sake of using the queue!

Given that the built in Python list already has both
push/pop and queue semantics available the whole exercise
is rather foolish IMHO. But you gotta do it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list