You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无循环无库实现字符串中数字检测的技术方案求助

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

  1. Base Case: If the input string is empty, we've checked all characters and found no digits—return False.
  2. 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 return True.
  3. 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, returns True
  • Input: "I own one dog" → Traverses the entire string without finding a digit, returns False

This approach strictly adheres to your constraints: no loops, no re/string libraries, and it's easy to follow.

内容的提问来源于stack exchange,提问作者Lidor Cohen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:06:39