0

My assignment was to come up with a palindrome program in python. Which I did here

def isPalindrome(word):
    for i in range(len(word)//2):
        if word[i] != word[-1-i]:
            return False
    return True

print (isPalindrome("maam")) #returns TRUE
print (isPalindrome("madam")) #returns TRUE
print (isPalindrome("hello")) #returns FALSE
print (isPalindrome("macdam")) #returns FALSE
print (isPalindrome("buffalolaffub")) #returns TRUE
print (isPalindrome("argentina")) #returns FALSE

Now my instructor wants this to be converted using Stacks. Can anybody help with this?

Here's the Stack data structure I have:

class Stack:

    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)
Blckknght
  • 100,903
  • 11
  • 120
  • 169
user2052503
  • 19
  • 1
  • 2

2 Answers2

2

Given:

tests=["maam", "madam","hello","macdam","buffalolaffub","argentina"]

Idiomatic Python check for a string being a palindrome would be something like this:

word==word[::-1]   # True or False

So you can print a list of palindromes like this:

print [word for word in tests if word==word[::-1]]     

To do this with a stack, you need to turn the string into a list and then the Python list / stack operations are available to you. Here is a small demo:

def stack_cmp(s1,s2):
    l1=list(s1)
    l2=list(s2)
    if len(l1)!=len(l2): return False
    while True:
        try:
            if l1.pop()!=l2.pop(): return False
        except IndexError:
            return True  

print [word for word in tests if stack_cmp(word, word[::-1])]

An alternate version of stack_cmp that does not use exceptions:

def stack_cmp(s1,s2):
    l1=list(s1)
    l2=list(s2)
    while l1 and l2:
        if l1.pop()!=l2.pop(): return False
    if l1 or l2: return False
    return True  

Which then works this wway:

>>> stack_cmp('mmmm','mmmm')
True
>>> stack_cmp('mmmm','mmmmm')
False

Your teacher may object to the use of slices to reverse a list; ie, revered_list=orig_list[::-1]. If that is the case, you can use this:

reversed_list=[]
orig_list_copy=orig_list[:]
while orig_list_copy:
    reversed_list.append(orig_list_copy.pop())    # this reverses the list

This works as a Stack class with a palidrome checker:

class Stack(object):
    def __init__(self,items):
        self.items=[]
        for e in items:
            self.push(e)

    def push(self,item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def __repr__(self):
        return str(self.items)  

    def isPalindrome(self):
        tr=Stack([])
        t=Stack(self.items)
        while t.items:
            tr.push(t.pop())
        t=Stack(self.items)    
        while t.items and tr.items:
            c1=t.pop()
            c2=tr.pop()
            print c1,c2
            if c1!=c2: return False
        return True    
the wolf
  • 34,510
  • 13
  • 53
  • 71
  • @the_wolf the line below gives me an invalid syntax error `print [word for word in tests if stack_cmp(word, word[::-1])]` – user2052503 Feb 08 '13 at 12:34
  • @the_wolf If i take that line out, my print results are not correct unless in the tests i write the test word & then the test word backwards. Heres the code... `from stackDS import Stack ` `def isPalindrome(word1, word2): l1=list(word1) l2=list(word2) if len(l1)!=len(l2): return False while True: try: if l1.pop()!=l2.pop(): return False except IndexError: return True ` `print (isPalindrome("maam", "maam")) #Expected Output: TRUE print (isPalindrome("hello", "olleh")) #Expected Output: FALSE` – user2052503 Feb 08 '13 at 12:34
  • This fails to answer the problem. It is not using the stack class to detect palindromes. – cmd Feb 08 '13 at 15:43
0

Well since a stack is First In Last Out they naturally reverse things. You could iterate over the string, pushing for the first half then popping and comparing for the last half.

cmd
  • 5,754
  • 16
  • 30
  • i am just struggling with getting it started.. I am not familiar with python language at all @cmd – user2052503 Feb 07 '13 at 23:44
  • @user2052503 in that case I would run through the tutorial http://docs.python.org/2/tutorial/index.html. Its fairly quick and of great help getting started. – cmd Feb 08 '13 at 16:23