Home
/
Blog
/
Finding Palindromes

Finding Palindromes

Semyon Yevyolkin
Semyon Yevyolkin
Backend Developer
0 1 min
Finding Palindromes

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:

  • a is the list or string to be sliced.

  • : is the slicing syntax (leaving the start and end empty means the entire string or list is taken).

  • -1 is the step (a negative step reverses the order).

  • a[::-1] creates a new string or list containing the same elements as the original, but in reverse order.

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
The idea is to loop up to half the length of the word and compare characters from the beginning with those from the end using slicing: : a[i] != a[-i-1].

Share

Feel free to contact us

Book an appointment

Tell us about your project
Name
Contact
Message
Attach file +
Request to get files
Name
Send files
Message
Thanks!
Your request has been sent
After processing, our manager will contact you