python codekatas solutions | | Cell 1 | Search

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.

Cell 0

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!')

What the code could have been:

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!')

Function Breakdown: palindrome(string)

Purpose

Checks if the input string (with all lower-case characters) is a palindrome.

Parameters

Return Values

Algorithm

  1. Loops through the first half of the string indices using range(len(string)//2).
  2. For each index i, checks if the character at index i is different from the character at the corresponding index from the end (len(string)-i-1).
  3. If any mismatch is found, immediately returns False.
  4. If the loop completes without finding any mismatches, returns True, indicating the string is a palindrome.

Edge Cases