Skip to content
TheChatArchiveThe Chat Archive
o3-mini· OpenAIHugging Face LMArena Human Preference 140K

Check if a string contains only digits, without using standard library functions.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-17b-128e-instruct’s answer.
  1. User

    Check if a string contains only digits, without using standard library functions.

  2. Assistant

    Below is a Python implementation to check if a string contains only digits. This implementation does not use any standard library functions such as isdigit:

    def contains_only_digits(s):
        # Iterate through each character in the string
        for char in s:
            # Check if the character is outside the range '0' to '9'
            if char < '0' or char > '9':
                return False
        return True
    
    # Example usage:
    test_strings = ["12345", "abc123", "00123", "", "45678a"]
    
    for s in test_strings:
        print(f"'{s}' contains only digits: {contains_only_digits(s)}")
    

    Explanation:

    • Loop Through Characters: The function loops through each character in the input string.
    • Character Comparison: It checks whether each character falls within the range '0' to '9'. In Python, characters can be compared using relational operators based on their ASCII (or Unicode) values.
    • Return Result: If a character is found that is not a digit, the function immediately returns False. Otherwise, if the loop finishes successfully, the function returns True.

    This solution meets the requirement of not using standard library functions for digit checking.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.