o3-mini· OpenAI
LMArena Human Preference 140K
Check if a string contains only digits, without using standard library functions.
- User
Check if a string contains only digits, without using standard library functions.
- 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 returnsTrue.
This solution meets the requirement of not using standard library functions for digit checking.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.