无循环无库实现字符串中数字检测的技术方案求助
Solution to Check for Digits in String Without Loops,
re or string Library Got it, let's work through this problem. You need a function that returns True if a string contains any numeric digits, and False otherwise—with strict constraints: no loops, no re module, no string module. Recursion is the perfect fit here since it lets us traverse the string without explicit for/while loops.
The Recursive Approach
Here's a straightforward implementation that checks each character one by one using recursion, leveraging ASCII value comparisons to identify digits (no external libraries needed):
def has_digit(s): # Base case: if the string is empty, no digits exist if not s: return False # Check if the first character is a digit using ASCII values # '0' is ASCII 48, '9' is ASCII 57 if 48 <= ord(s[0]) <= 57: return True # Recursively check the rest of the string return has_digit(s[1:])
How It Works
- Base Case: If the input string is empty, we've checked all characters and found no digits—return
False. - Digit Check: We use
ord()to get the ASCII value of the first character. Digits '0' to '9' fall between 48 and 57, so if the character's value is in this range, we immediately returnTrue. - Recursive Step: If the first character isn't a digit, we call the function again with the substring starting from the second character.
Test Examples
- Input:
"I own 23 dogs"→ The function hits the '2' character, returnsTrue - Input:
"I own one dog"→ Traverses the entire string without finding a digit, returnsFalse
This approach strictly adheres to your constraints: no loops, no re/string libraries, and it's easy to follow.
内容的提问来源于stack exchange,提问作者Lidor Cohen
相关产品推荐
相关产品推荐

