Simple Function

Code GenerationDifficulty: EASY11 models comparedTotal cost: $0.022121

Prompt

Write a Python function called `is_palindrome` that checks if a string is a palindrome, ignoring case and non-alphanumeric characters. Include type hints.

Model Responses

Claude Opus 4.6

Unrated
10,868ms786 tokens
```python def is_palindrome(s: str) -> bool: """ Check if a string is a palindrome, ignoring case and non-alphanumeric characters. Args: s: The input string to check. Returns: True if the string is a palindrome, False otherwise. Examples: >>> is_palindrome("A man, a plan, a canal: Panama") True >>> is_palindrome("racecar") True >>> is_palindrome("hello") False >>> is_palindrome("") True >>> is_palindrome("Was it a car or a cat I saw?") True """ # Filter out non-alphanumeric characters and convert to lowercase cleaned: str = "".join(char.lower() for char in s if char.isalnum()) # Compare the cleaned string with its reverse return cleaned == cleaned[::-1] # --- Demo / Testing --- if __name__ == "__main__": test_cases: list[tuple[str, bool]] = [ ("A man, a plan, a canal: Panama", True), ("racecar", True), ("hello", False), ("", True), ("Was it a car or a cat I saw?", True), ("No 'x' in Nixon", True), ("12321", True), ("abc123", False), ("Madam, I'm Adam", True), (" ", True), ] print("Testing is_palindrome function:") print("-" * 55) for text, expected in test_cases: result: bool = is_palindrome(text) status: str = "✅ PASS" if result == expected else "❌ FAIL" print(f'{status} | is_palindrome("{text}") = {result}') ``` ## How It Works 1. **Cleaning the string:** - `char.isalnum()` filters out any character that isn't a letter or digit (spaces, punctuation, etc.) - `char.lower()` converts each remaining character to lowercase for case-insensitive comparison - `"".join(...)` combines the filtered characters back into a single string 2. **Palindrome check:** - `cleaned[::-1]` creates a reversed copy of the cleaned string - A simple equality check (`==`) determines if the string reads the same forwards and backwards ## Key Design Choices | Feature | Detail | |---|---| | **Type hints** | `s: str` for input, `-> bool` for return type | | **Ignores case** | `"Racecar"` → `"racecar"` | | **Ignores non-alphanumeric** | `"A man, a plan..."` → `"amanaplanacanalpanama"` | | **Edge cases** | Empty strings and whitespace-only strings return `True` (vacuously palindromic) | | **Time complexity** | O(n) where n is the length of the string |

GPT-4.1

Unrated
1,755ms178 tokens
Certainly! Here is the `is_palindrome` function with type hints, which ignores case and non-alphanumeric characters: ```python import re def is_palindrome(s: str) -> bool: # Remove non-alphanumeric characters and convert to lowercase cleaned: str = re.sub(r'[^a-zA-Z0-9]', '', s).lower() # Check if cleaned string is equal to its reverse return cleaned == cleaned[::-1] ``` **Usage example:** ```python print(is_palindrome("A man, a plan, a canal: Panama")) # True print(is_palindrome("race a car")) # False ```

GPT-4.1 Mini

Unrated
1,563ms109 tokens
```python import re def is_palindrome(s: str) -> bool: # Remove non-alphanumeric characters and convert to lowercase cleaned = re.sub(r'[^a-zA-Z0-9]', '', s).lower() # Check if cleaned string is equal to its reverse return cleaned == cleaned[::-1] ```

GPT-4.1 Nano

Unrated
1,692ms188 tokens
Certainly! Here's a Python function `is_palindrome` that checks whether a string is a palindrome, ignoring case and non-alphanumeric characters. It includes type hints for clarity. ```python import re def is_palindrome(s: str) -> bool: # Remove non-alphanumeric characters and convert to lowercase cleaned = re.sub(r'[^A-Za-z0-9]', '', s).lower() # Check if the cleaned string is equal to its reverse return cleaned == cleaned[::-1] ``` **Usage example:** ```python print(is_palindrome("A man, a plan, a canal, Panama")) # True print(is_palindrome("Hello, World!")) # False ```

o3

Unrated
2,740ms351 tokens
```python from typing import Final def is_palindrome(text: str) -> bool: """ Determine whether *text* is a palindrome, ignoring case and any non-alphanumeric characters. Parameters ---------- text : str The input string to evaluate. Returns ------- bool True if *text* is a palindrome, otherwise False. """ # Keep only alphanumerics and convert to lowercase cleaned: Final[str] = "".join(ch.lower() for ch in text if ch.isalnum()) # Compare the cleaned string with its reverse return cleaned == cleaned[::-1] ``` Example: ```python >>> is_palindrome("Madam, I'm Adam!") True >>> is_palindrome("OpenAI") False ```

o3 Mini

Unrated
4,551ms500 tokens
def is_palindrome(s: str) -> bool: """ Check if the given string is a palindrome, ignoring case and non-alphanumeric characters. Parameters: s (str): The string to check. Returns: bool: True if the processed string is a palindrome, False otherwise. """ # Remove non-alphanumeric characters and convert to lowercase cleaned_str = ''.join(char for char in s if char.isalnum()).lower() # Check if the cleaned string is equal to its reverse return cleaned_str == cleaned_str[::-1] # Example usage: if __name__ == "__main__": test_strings = [ "A man, a plan, a canal, Panama", "Racecar", "Hello, World!" ] for text in test_strings: result = is_palindrome(text) print(f'"{text}" is a palindrome: {result}')

o4 Mini

Unrated
4,249ms458 tokens
Here’s a simple implementation with type hints and a quick docstring: ```python def is_palindrome(s: str) -> bool: """ Check if the given string is a palindrome, ignoring case and non-alphanumeric characters. Args: s (str): The string to check. Returns: bool: True if s is a palindrome, False otherwise. """ # Filter out non-alphanumeric characters and convert to lowercase cleaned: str = "".join(char.lower() for char in s if char.isalnum()) # Check if the cleaned string reads the same forwards and backwards return cleaned == cleaned[::-1] # Example usage: if __name__ == "__main__": tests = [ "A man, a plan, a canal: Panama", "racecar", "No 'x' in Nixon", "Hello, World!", ] for t in tests: print(f"{t!r} -> {is_palindrome(t)}") ``` Explanation: 1. We use a generator expression to keep only alphanumeric characters (`char.isalnum()`) and convert them to lowercase. 2. We form a cleaned string and compare it to its reverse (`cleaned[::-1]`). 3. The function returns `True` if they match, `False` otherwise.

GPT-4o Mini

Unrated
6,150ms345 tokens$0.000190
Certainly! Below is a Python function `is_palindrome` that checks if a given string is a palindrome, ignoring case and non-alphanumeric characters. The function includes type hints as requested. ```python import re def is_palindrome(s: str) -> bool: # Normalize the string by removing non-alphanumeric characters and converting to lowercase cleaned_string = re.sub(r'[^a-zA-Z0-9]', '', s).lower() # Check if the cleaned string is equal to its reverse return cleaned_string == cleaned_string[::-1] # Example usage print(is_palindrome("A man, a plan, a canal: Panama")) # Output: True print(is_palindrome("race a car")) # Output: False ``` ### Explanation: 1. **Imports**: We import the `re` module for regular expression operations. 2. **Function Definition**: The function `is_palindrome` takes a single parameter `s`, which is expected to be of type `str`, and returns a boolean (`bool`). 3. **Normalization**: - We use `re.sub` to remove all non-alphanumeric characters from the string. - We convert the entire string to lowercase using `lower()`. 4. **Palindrome Check**: Finally, we compare the cleaned string with its reverse (`cleaned_string[::-1]`) to determine if it is a palindrome. 5. **Examples included**: Demonstrates how the function can be used.

Claude Haiku 4.5

Unrated
4,190ms768 tokens$0.003664
# Palindrome Checker Function Here's a Python function that checks if a string is a palindrome while ignoring case and non-alphanumeric characters: ```python def is_palindrome(s: str) -> bool: """ Check if a string is a palindrome, ignoring case and non-alphanumeric characters. Args: s: The string to check Returns: True if the string is a palindrome, False otherwise Examples: >>> is_palindrome("A man, a plan, a canal: Panama") True >>> is_palindrome("race a car") False >>> is_palindrome("0P") False >>> is_palindrome("") True """ # Filter: keep only alphanumeric characters and convert to lowercase cleaned = ''.join(char.lower() for char in s if char.isalnum()) # Check if cleaned string equals its reverse return cleaned == cleaned[::-1] ``` ## Usage Examples ```python # Test cases print(is_palindrome("A man, a plan, a canal: Panama")) # True print(is_palindrome("race a car")) # False print(is_palindrome("0P")) # False print(is_palindrome("")) # True print(is_palindrome("Madam")) # True print(is_palindrome("12321")) # True print(is_palindrome("12345")) # False print(is_palindrome("a.")) # True print(is_palindrome("ab_a")) # True ``` ## Alternative Implementation (Two-Pointer Approach) If you prefer a more memory-efficient approach for very large strings: ```python def is_palindrome(s: str) -> bool: """ Check if a string is a palindrome using two-pointer technique. More memory-efficient for very large strings. """ left, right = 0, len(s) - 1 while left < right: # Skip non-alphanumeric characters from left while left < right and not s[left].isalnum(): left += 1 # Skip non-alphanumeric characters from right while left < right and not s[right].isalnum(): right -= 1 # Compare characters (case-insensitive) if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True ``` ## Comparison | Approach | Pros | Cons | |----------|------|------| | **String Cleaning** | Simple, readable, Pythonic | Uses extra memory for filtered string | | **Two-Pointer** | Memory-efficient, no new string created | Slightly more complex logic | Both functions are correct; choose based on your priorities (simplicity vs. memory efficiency).

GPT-4o

Unrated
5,467ms402 tokens$0.003735
Here's a Python function called `is_palindrome` that checks if a given string is a palindrome. It ignores case and non-alphanumeric characters, and includes type hints: ```python import re def is_palindrome(s: str) -> bool: # Remove non-alphanumeric characters and convert to lowercase cleaned = re.sub(r'[^A-Za-z0-9]', '', s).lower() # Check if the cleaned string is equal to its reverse return cleaned == cleaned[::-1] # Example usage: # print(is_palindrome("A man, a plan, a canal: Panama")) # should return True # print(is_palindrome("race a car")) # should return False ``` ### Explanation: 1. **Import `re` Module**: We use Python's built-in `re` module for regular expressions to clean the input string. 2. **Clean the String**: We use `re.sub(r'[^A-Za-z0-9]', '', s)` to remove all non-alphanumeric characters from the string `s`. This matches any character that is not a letter or a number and replaces it with an empty string. 3. **Convert to Lowercase**: We convert the cleaned string to lowercase using `.lower()` to ensure the palindrome check is case-insensitive. 4. **Check for Palindrome**: We check if the cleaned string is equal to its reverse using `cleaned == cleaned[::-1]`. The slicing operation `[::-1]` creates a reversed copy of the string. 5. **Return the Result**: The function returns `True` if the string is a palindrome, and `False` otherwise. Example usage is also included to illustrate how this function can be used to check if a given string is a palindrome.

Claude Sonnet 4.6

Unrated
12,311ms1004 tokens$0.014532
## Palindrome Checker Here's a clean, well-documented implementation with type hints: ```python def is_palindrome(s: str) -> bool: """ Check if a string is a palindrome, ignoring case and non-alphanumeric characters. A palindrome reads the same forwards and backwards (e.g., "racecar", "A man a plan a canal Panama"). Args: s: The input string to check. Returns: True if the string is a palindrome, False otherwise. Examples: >>> is_palindrome("racecar") True >>> is_palindrome("A man, a plan, a canal: Panama") True >>> is_palindrome("hello") False >>> is_palindrome("") True """ # Filter out non-alphanumeric characters and convert to lowercase cleaned = [char.lower() for char in s if char.isalnum()] # Compare the cleaned list with its reverse return cleaned == cleaned[::-1] ``` ### How It Works | Step | Example Input | Result | |------|--------------|--------| | Input | `"A man, a plan, a canal: Panama"` | — | | Filter & lowercase | `['a','m','a','n','a','p','l','a','n','a','c','a','n','a','l','p','a','n','a','m','a']` | — | | Reversed | `['a','m','a','n','a','p','l','a','n','a','c','a','n','a','l','p','a','n','a','m','a']` | — | | Equal? | `cleaned == cleaned[::-1]` | `True` | ### Usage Examples ```python # Basic palindromes print(is_palindrome("racecar")) # True print(is_palindrome("madam")) # True # Case-insensitive print(is_palindrome("RaceCar")) # True # Ignores punctuation and spaces print(is_palindrome("A man, a plan, a canal: Panama")) # True print(is_palindrome("Was it a car or a cat I saw?")) # True print(is_palindrome("No 'x' in Nixon")) # True # Not palindromes print(is_palindrome("hello")) # False print(is_palindrome("Python")) # False # Edge cases print(is_palindrome("")) # True (empty string) print(is_palindrome("a")) # True (single character) print(is_palindrome("!!")) # True (only special chars) ``` ### Alternative: Two-Pointer Approach (O(1) Space) If memory efficiency is a priority, you can avoid creating a new list: ```python def is_palindrome_two_pointer(s: str) -> bool: """Same functionality using two pointers for O(1) extra space.""" left, right = 0, len(s) - 1 while left < right: # Move left pointer past non-alphanumeric characters while left < right and not s[left].isalnum(): left += 1 # Move right pointer past non-alphanumeric characters while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True ``` ### Complexity Comparison | Approach | Time | Space | |----------|------|-------| | List + slice reverse | O(n) | O(n) | | Two-pointer | O(n) | O(1) | The **list approach** is more Pythonic and readable, while the **two-pointer approach** is preferred when working with very large strings.

Cost & Performance Comparison

ModelLatencyTokensCostVerdict
Claude Opus 4.610,868ms786
GPT-4.11,755ms178
GPT-4.1 Mini1,563ms109
GPT-4.1 Nano1,692ms188
o32,740ms351
o3 Mini4,551ms500
o4 Mini4,249ms458
GPT-4o Mini6,150ms345$0.000190
Claude Haiku 4.54,190ms768$0.003664
GPT-4o5,467ms402$0.003735
Claude Sonnet 4.612,311ms1,004$0.014532
Simple Function — Model Lab — AISpendGuard