如果我只是在这里阅读我的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
注意,您可以使用内置函数轻松解决此问题。这是一个更为惯用和有效的解决方案:
尤其要注意,对于字符串类型,} 。
is_a_digit()
方法已经存在,它被称为^{使用生成器表达式作为内置函数的参数,可以更简洁地表达
sum_digits()
函数中的整个循环,如上图所示。如果
a
是一个数字,则在每次迭代中重置b
的值。也许你想:
而不是:
使用内置函数的另一种方法是使用reduce函数:
相关问题 更多 >
编程相关推荐