Palindrome
  • A palindrome is a string that reads the same forward and backward, for example, radar, toot, and madam
  • # DequeModule.py
    #!/usr/bin/python3
    class Deque(object):
        def __init__(self):
            self.items = []
    
        def isEmpty(self):
            return len(self.items) == 0
    
        def addFront(self, v):
            try:
                self.items.append(v)
                return True
            except Exception as err:
                return False
    
        def addRear(self, v):
            try:
                self.items.insert(0, v)
                return True
            except Exception as err:
                return False
    
        def removeFront(self):
            try:
                return self.items.pop()
            except Exception as err:
                return None
    
        def removeRear(self):
            try:
                return self.items.pop(0)
            except Exception as err:
                return None
    
        def size(self):
            return len(self.items)
    
        def __str__(self):
            s = 'rear ->'
    
            output = []
    
            for item in self.items:
                output.append(str(item))
    
            s += '->'.join(output)
    
            s += '-> front'
    
            return s
                
    #!/usr/bin/python3
    from DequeModule import Deque
    
    def isPalindrome(s):
        d = Deque()
        for c in s:
            d.addFront(c)
    
        if d.size() <= 1:
            return True
    
        while d.size() > 1:
            front = d.removeFront()
            end = d.removeRear()
    
            if front != end:
                return False
    
        return True
    
    if __name__ == '__main__':
        print(isPalindrome("lsdkjfskf")) # False
        print(isPalindrome("radar")) # True
                
    Reference
  • Problem Solving with Algorithms and Data Structures using Python