Sunday, September 10, 2017

Python stack and queue

Finding if palindrome with stacks and queues in python


import sys
class stackandqueue:
    def __init__(self):
        self.stack = [ ]
        self.queue = [ ]
   
    def pushChar(self, s):
        self.stack.append(s)
       
    def popChar(self):
        return self.stack.pop()
   
    def enqueueChar(self, s):
        self.queue.insert(0,s)
   
    def dequeueChar(self):
        return self.queue.pop()

s=raw_input()
obj=stackandqueue()  

l=len(s)

for i in range(l):
    obj.pushChar(s[i])
    obj.enqueueChar(s[i])
   
isPalindrome=True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
'''
for i in range(l / 2):
    if obj.popChar()!=obj.dequeueChar():
        isPalindrome=False
        break
#finally print whether string s is palindrome or not.
if isPalindrome:
    sys.stdout.write ("The word, "+s+", is a palindrome.")
else:
    sys.stdout.write ("The word, "+s+", is not a palindrome.")