# Completed implementation of a deque ADT
class Deque:
def __init__(self):
self.data = []
def is_empty(self):
return self.data == []
def add_front(self, item):
self.data.append(item)
def add_rear(self, item):
self.data.insert(0, item)
def remove_front(self):
return self.data.pop()
def remove_rear(self):
return self.data.pop(0)
def size(self):
return len(self.data)
if __name__ == '__main__':
dq = Deque()
dq.add_front('hello')
dq.add_front(123)
dq.add_rear(True)
dq.add_rear(3.14)
while not dq.is_empty():
print(dq.remove_front())
print(dq.remove_rear())
A simple case to use Deque:
from deque import Deque
def pal_checker(str):
'''Palindrome checker.
eg. abcba is a palindrome
'''
ch_deque = Deque()
for ch in str:
ch_deque.add_front(ch)
if ch_deque.size() < 2: # Assume '' or only one character is palindrome
return True
while ch_deque.size() > 1:
if ch_deque.remove_front() == ch_deque.remove_rear():
continue
else:
break
else:
return True
return False
if __name__ == '__main__':
print(pal_checker('abcdedcba'))
print(pal_checker('asdfghfdsa'))
print(pal_checker('aabbcc'))
print(pal_checker('asdfghjklkjhgfdsa'))