如果我只是看了我的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
请注意,您可以使用内置的功能轻松解决这个问题。 这是一个更地道和有效的解决方案:
def sum_digits(digit):
return sum(int(x) for x in digit if x.isdigit())
sum_digits('hihello153john')
=> 9
尤其要注意的是, is_a_digit()
方法已经存在字符串类型,这就是所谓的isdigit()
并且在整个循环sum_digits()
函数可以使用生成表达式作为一个参数来表示更简明地sum()
内置函数,如上所示。
使用内置函数的另一种方法,是使用减少功能:
>>> numeric = lambda x: int(x) if x.isdigit() else 0
>>> reduce(lambda x, y: x + numeric(y), 'hihello153john', 0)
9
一个衬垫
sum_digits = lambda x: sum(int(y) for y in x if y.isdigit())
我想建议使用至REGx覆盖两种情况不同的解决方案:
1。
输入= 'abcd45def05'
输出= 45 + 05 = 50
import re
print(sum(int(x) for x in re.findall(r'[0-9]+', my_str)))
注意“+”的一个或多个出现
2。
输入= 'abcd45def05'
输出= 4 + 5 + 0 + 5 = 14
import re
print(sum(int(x) for x in re.findall(r'[0-9]', my_str)))
这样做的另一种方式:
def digit_sum(n):
new_n = str(n)
sum = 0
for i in new_n:
sum += int(i)
return sum
为您的代码等效,使用列表理解:
def sum_digits(your_string):
return sum(int(x) for x in your_string if '0' <= x <= '9')
它会跑得更快,然后一个“为”版本,并节省了大量的代码。
到@奥斯卡的答案就在变化,如果我们需要的总和是个位数,
def sum_digits(digit):
s = sum(int(x) for x in str(digit) if x.isdigit())
if len(str(s)) > 1:
return sum_digits(s)
else:
return s