Python Practice › Collections Programs › Program 20
Palindrome check with deque
Write a Python program to check palindromes by removing characters from both ends of a deque.
Output
[('Level', True), ('python', False), ('racecar', True)]Approach
- Compare
popleft()withpop()until the middle.
Solution
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.