Sum of digits in a string

2019-01-25 13:24发布

if i just read my sum_digits function here, it makes sense in my head but it seems to be producing wrong results. Any tip?

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

For the function sum_digits, if i input sum_digits('hihello153john'), it should produce 9

8条回答
ゆ 、 Hurt°
2楼-- · 2019-01-25 13:44

I would like to propose a different solution using regx that covers two scenarios:

1.
Input = 'abcd45def05'
Output = 45 + 05 = 50

import re
print(sum(int(x) for x in re.findall(r'[0-9]+', my_str)))

Notice the '+' for one or more occurrences

2.
Input = 'abcd45def05'
Output = 4 + 5 + 0 + 5 = 14

import re
print(sum(int(x) for x in re.findall(r'[0-9]', my_str)))
查看更多
\"骚年 ilove
3楼-- · 2019-01-25 13:45

You're resetting the value of b on each iteration, if a is a digit.

Perhaps you want:

b += int(a)

Instead of:

b = int(a)
b += 1
查看更多
登录 后发表回答