Basic Data Structure - 3. Deque

A deque, also known as a double-ended queue, is an ordered collection of items similar to the queue. It has two ends and new items can be added and removed at either front or the rear, which does not require FIFO or LIFO orderings.

# Listing 3.14
class Deque:
    def __init__(self):
        self.items = []
        
    def isEmpty(self):
        return self.items == []
    
    def addFront(self, item):
        self.items.append(item)
        
    def addRear(self, item):
        self.items.insert(0, item)
        
    def removeFront(self):
        return self.items.pop()
    
    def removeRear(self):
        return self.items.pop()
    
    def size(self):
        return len(self.items)

A palindrome is a string that reads the same forward and backward, for ex, radar, tool, and madam.
The solutino to this problem will use a deque to store the characters of the string. We will process the string from left to right and add each character to the rear of the deque.

Simulation : Palindrome Checker

# Listing 3.15 : Palindrome Checker

def parcheck(aString):
    chardeque = Deque()
    
    for ch in aString:
        chardeque.addRear(ch)
        
    stillEqual = True
    
    while chardeque.size() > 1 and stillEqual:
        first = chardeque.removeFront()
        last = chardeque.removeRear()
        if first != last:
            stillEqual = False
            
    return stillEqual
# Testing code
parcheck("toot")
False
parcheck("aksdjflk")
False

Leave a comment