TransWikia.com

Python palindrome checker function

Code Review Asked by dicomp on November 8, 2021

For practice purposes I implemented a function that checks for palindromes:

def palindrom(name):
    name_reversed = ""

    for buchstabe in name[::-1]:
        name_reversed += buchstabe

    return name.lower() == name_reversed.lower()


print(palindrom("Tom"))
print(palindrom("Bob"))

How may I improve this code, especially the for-loop?

4 Answers

It's also possible to work with two pointers. This is not the shortest solution, but it should be very fast and you don't have to store the reversed string.

def palindrome(name):
    name = name.lower()
    left = 0
    right = len(name) - 1
    while left < right:
        if name[left] != name[right]:
            return False
        left += 1
        right -= 1
    return True

Answered by Kevin on November 8, 2021

@Reinderien and @vlovero have already told whatever could be done but maybe you would also like the reversed function. Also you do not need to lower() your strings twice when you can do it only once. Strings(immutable type) are passed by value in python and doesn't modify the original string since a shallow copy of your string is sent to the function.

def palindrome(name):

    name = name.lower()

    return "".join(reversed(name)) == name #or simply name[::-1] == name


print(palindrome("Tom"))
print(palindrome("Bob"))

Answered by Vishesh Mangla on November 8, 2021

For your for-loop, you can use reversed(name) instead of name[::-1]. This will increase performance by preventing unnecessary copying by creating a generator instead of another string. However in your case, because you are only checking if the reversed is the same as the original, your function can be even simpler

def palindrome(name):
    return name.lower() == name[::-1].lower()

Answered by vlovero on November 8, 2021

Localisation

It's fine to localise your user-facing strings (e.g. print('Die Buchstaben in diesem Wort bilden ein Palindrom'), but it is not advisable to write the code itself in a language other than English. For better or worse, English is the de-facto language of programming. Thus, buchstabe would be better as letter.

For-loop

The loop is not necessary:

    name_reversed = name[::-1]

name is a string, which is itself a sequence of one-character strings. Applying a slice, as is done here, reverses the sequence but does not change the type: the output of the expression is still a string.

Answered by Reinderien on November 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP