Alternative Solution for Palindrome Function Exercise

I just thought the following code could be suggested as an alternative solution to exercise no.8 under Functions: Fundamentals Practice Problems.

Original solution:

def is_palindrome(dna):
    n = len(dna)
    for i in range(n // 2):
        if dna[i] != dna[n - i - 1]:
            return False
    return True

Alternative:

def is_palindrome(dna):
    dna_r = dna[::-1]
    if dna == dna_r:
        return(True)
    else:
        return(False)
1 Like

It is a valid alternative (although, I haven’t tested it myself as of now), but it shouldn’t necessarily be suggested as an alternative solution in the exercise as per me.

The aim of such exercises is usually to allow people to think through the problem and come up with a solution without relying on any existing language/library features or built-in methods. That helps develop problem-solving skills and, whether ideal or not, is useful for potential programming interviews as well.

But, yes, still a valid solution I believe.

4 Likes