The palindrome(string)
function checks if the input string, with all lower-case characters, is the same when reversed. It does this by comparing characters from the start and end of the string, working its way towards the center, and returns True
if no mismatches are found.
def palindrome(string):
"""Check if input string (all lower-case characters) is a palindrome."""
for i in range(len(string)//2):
if string[i] != string[len(string)-i-1]:
return False
return True
assert palindrome('') == True
assert palindrome('a') == True
assert palindrome('ab') == False
assert palindrome('abba') == True
assert palindrome('redivider') == True
print('All passed!')
def is_palindrome(s: str) -> bool:
"""
Check if input string is a palindrome, ignoring case and spaces.
Args:
s (str): The input string to check.
Returns:
bool: True if the string is a palindrome, False otherwise.
"""
# Remove spaces and convert to lower case
s = ''.join(c for c in s if c.isalnum()).lower()
# Handle empty strings as edge case
if len(s) < 2:
return True
# Compare characters from the start and end, moving towards the center
left = 0
right = len(s) - 1
while left < right:
if s[left]!= s[right]:
return False
left += 1
right -= 1
return True
assert is_palindrome('')
assert is_palindrome('a')
assert not is_palindrome('ab')
assert is_palindrome('abba')
assert is_palindrome('redivider')
print('All passed!')
palindrome(string)
Checks if the input string (with all lower-case characters) is a palindrome.
string
: The input string to be checked.True
if the input string is a palindrome.False
if the input string is not a palindrome.range(len(string)//2)
.i
, checks if the character at index i
is different from the character at the corresponding index from the end (len(string)-i-1
).False
.True
, indicating the string is a palindrome.palindrome('') == True
).palindrome('a') == True
).