字符串中数字的和

12 投票
10 回答
68001 浏览
提问于 2025-04-17 13:50

如果我只看我的 sum_digits 函数,脑子里觉得没问题,但它似乎输出的结果不对。有什么建议吗?

def is_a_digit(s):
''' (str) -> bool

Precondition: len(s) == 1

Return True iff s is a string containing a single digit character (between
'0' and '9' inclusive).

>>> is_a_digit('7')
True
>>> is_a_digit('b')
False
'''

return '0' <= s and s <= '9'

def sum_digits(digit):
    b = 0
    for a in digit:
        if is_a_digit(a) == True:
            b = int(a)
            b += 1

    return b

对于这个 sum_digits 函数,如果我输入 sum_digits('hihello153john'),它应该返回 9

10 个回答

5

另一种使用内置函数的方法是使用 reduce 函数:

>>> numeric = lambda x: int(x) if x.isdigit() else 0
>>> reduce(lambda x, y: x + numeric(y), 'hihello153john', 0)
9
9

你在每次循环的时候,如果a是一个数字,就会把b的值重置。

也许你想要的是:

b += int(a)

而不是:

b = int(a)
b += 1
29

注意,你可以很简单地用内置函数来解决这个问题。这是一种更符合习惯且高效的解决方案:

def sum_digits(digit):
    return sum(int(x) for x in digit if x.isdigit())

print(sum_digits('hihello153john'))
=> 9

特别要知道,字符串类型已经有一个叫 is_a_digit() 的方法,它的真正名字是 isdigit()

而在 sum_digits() 函数中的整个循环,可以用生成器表达式更简洁地作为 sum() 内置函数的参数来表示,就像上面展示的那样。

撰写回答