Sum of digits per line

If I just read my sum_digits function here, it makes sense in my head, but it seems to be sum_digits wrong results. Any advice?

 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 sum_digits function, if I input sum_digits('hihello153john') , it should produce 9

+6
source share
7 answers

Please note that you can easily solve this problem using the built-in functions. This is a more idiomatic and effective solution:

 def sum_digits(digit): return sum(int(x) for x in digit if x.isdigit()) sum_digits('hihello153john') => 9 

In particular, keep in mind that the is_a_digit() method already exists for string types; it is called isdigit() .

And the whole cycle in the sum_digits() function can be expressed more briefly using the generator expression as a parameter of the built-in sum() function, as shown above.

+17
source

You return b at each iteration if a is a digit.

Perhaps you want to:

 b += int(a) 

Instead:

 b = int(a) b += 1 
+10
source

Another way to use inline functions is to reduce :

 >>> numeric = lambda x: int(x) if x.isdigit() else 0 >>> reduce(lambda x, y: x + numeric(y), 'hihello153john', 0) 9 
+3
source

Single liner

 sum_digits = lambda x: sum(int(y) for y in x if y.isdigit()) 
+1
source

I would like to suggest another solution using regx that spans 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))) 

Note 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))) 
+1
source

Equivalent to your code using lists:

 def sum_digits(your_string): return sum(int(x) for x in your_string if '0' <= x <= '9') 

It will run faster than the for version and save a lot of code.

0
source

Just a @oscar answer option, if we need a sum to be a single digit,

 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 
0
source

All Articles