Tuesday, April 23, 2024
HomeSoftware EngineeringThe right way to Verify if String is a Palindrome in Python

The right way to Verify if String is a Palindrome in Python


The problem

Write a operate that checks if a given string (case insensitive) is a palindrome.

The answer in Python

Possibility 1:

def is_palindrome(s):
    s = s.decrease()
    for i, merchandise in enumerate(s):
        if i<len(s)/2:
            if s[i]!=s[len(s)-i-1]:
                return False
    return True

Possibility 2:

def is_palindrome(s):
    s = s.decrease()
    return s == s[::-1]

Possibility 3:

def is_palindrome(s):
    return s.decrease()==s[::-1].decrease()

Check circumstances to validate our answer

@take a look at.describe('pattern assessments')
def sample_tests():
    take a look at.assert_equals(is_palindrome('a'), True)
    take a look at.assert_equals(is_palindrome('aba'), True)
    take a look at.assert_equals(is_palindrome('Abba'), True)
    take a look at.assert_equals(is_palindrome('malam'), True)
    take a look at.assert_equals(is_palindrome('walter'), False)
    take a look at.assert_equals(is_palindrome('kodok'), True)
    take a look at.assert_equals(is_palindrome('Kasue'), False)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments