Here is my solution for the first exercise/Project in:
Learn Advanced Algorithms and Data Structures with Python
I had to modify it somewhat
A deque class is provided - deque = Deque()
but when I attempted to utilize it I seem to be stuck in an infinite loop so I initialized my own instance of the Deque() class and called it pal_ch (for palindrome_checker)
I also did some error handling in case a string of 1 character or an empty string was passed as the parameter.
Instructions
Deque Palindrome Project
Deques can be helpful when trying to determine if a given string is a palindrome. A palindrome is a string with the same characters when read forwards and backwards. The words level and kayak are examples of palindromes.
In our Implementing Deque in Python lesson, we covered the implementation of the deque data structure with our Deque
class. In this project, we will use the Deque
class to create a palindrome reader that will determine if any given string is a palindrome.
class Deque:
def __init__(self):
self.elements = []
def add_first(self, item):
self.elements.append(item)
def add_last(self, item):
self.elements.insert(0, item)
def remove_first(self):
item = self.elements.pop()
return item
def remove_last(self):
item = self.elements.pop(0)
return item
def is_empty(self):
if len(self.elements) > 0:
return False
return True
def size(self):
return len(self.elements)
def peek_first(self):
return self.elements[-1]
def peek_last(self):
return self.elements[0]
def display_deque(self):
print('\t | \t'.join(str(item) for item in self.elements))
def is_palindrome(word):
pal_ch = Deque()
for char in word:
# Add the character to the front of the deque (remove pass)
pal_ch.add_first(char)
#if I used deque = Deque() the code would not execute
#pal_ch.display_deque()
while pal_ch.size() > 1:
# Pop from the rear of the deque. Replace None with code
first = pal_ch.remove_last()
# Pop from the front of the deque. Replace None with code
last = pal_ch.remove_first()
# If statement goes below to check for equality
if first == last:
match = True
return True
else:
return False
if pal_ch.size() <= 1:
return "Too small"
deque = Deque()
print(is_palindrome('alskjfwi'))
print(is_palindrome('level'))
print(is_palindrome('kayak'))
print(is_palindrome('koala'))
print(is_palindrome('o'))
print(is_palindrome(''))