A palindrome is a number, phrase, word, or text that reads the same forwards and backwards.
For example: “level”, “radar”, “rotator”.
During interviews, especially in live coding sessions, candidates are often asked to write a simple method to find palindrome words.
Here’s an example of such a method:
def palindrome(*, a: str) -> bool:
return a == a[::-1]
Example usage:
>>> palindrome(a="коза")
>>> False
>>> palindrome(a="дед")
>>> True
In Python, the expression a[::-1] is used to get a reversed copy of a list or string. This is a slicing technique where:
There’s another way to solve this problem:
def palindrome(*, a: str) -> bool:
for i in range(len(a) // 2):
if x[i] != x[-i]:
return False
return True