Palindrome check with deque

EasyCollections Programs · 20 of 20

Write a Python program to check palindromes by removing characters from both ends of a deque.

Advertisement
Output
[('Level', True), ('python', False), ('racecar', True)]

Approach

  1. Compare popleft() with pop() until the middle.

Solution

Python
from collections import deque def is_palindrome(word):    d = deque(word.lower())    while len(d) > 1:        if d.popleft() != d.pop():            return False    return True print([(w, is_palindrome(w)) for w in ["Level", "python", "racecar"]])
Output
[('Level', True), ('python', False), ('racecar', True)]

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

Leave a Comment