【发布时间】:2013-01-11 01:59:41
【问题描述】:
如果我只是在这里阅读了我的 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
【问题讨论】:
-
你得到什么而不是 9?
-
它产生 4,因为它需要最后一个数字 3 并加上 1,因为您每次运行循环时都设置 b 的值