use*_*828 7 python string sum digits
如果我只是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
Run Code Online (Sandbox Code Playgroud)
对于该功能sum_digits,如果我输入sum_digits('hihello153john'),它应该产生9
Ósc*_*pez 18
请注意,您可以使用内置函数轻松解决此问题.这是一个更惯用和有效的解决方案:
def sum_digits(digit):
return sum(int(x) for x in digit if x.isdigit())
sum_digits('hihello153john')
=> 9
Run Code Online (Sandbox Code Playgroud)
特别要注意,该is_a_digit()方法已经存在于字符串类型中,它被调用isdigit().
并且sum_digits()使用生成器表达式作为sum() 内置函数的参数,可以更简洁地表达函数中的整个循环,如上所示.
Ale*_*lds 10
您正在重置b每次迭代的值,如果a是数字.
也许你想要:
b += int(a)
Run Code Online (Sandbox Code Playgroud)
代替:
b = int(a)
b += 1
Run Code Online (Sandbox Code Playgroud)
使用内置函数的另一种方法是使用reduce函数:
>>> numeric = lambda x: int(x) if x.isdigit() else 0
>>> reduce(lambda x, y: x + numeric(y), 'hihello153john', 0)
9
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34816 次 |
| 最近记录: |