Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of digits in a string

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

like image 707
user1864828 Avatar asked Jan 27 '13 17:01

user1864828


5 Answers

Notice that you can easily solve this problem using built-in functions. This is a more idiomatic and efficient solution:

def sum_digits(digit):
    return sum(int(x) for x in digit if x.isdigit())

print(sum_digits('hihello153john'))
=> 9

In particular, be aware that the is_a_digit() method already exists for string types, it's called isdigit().

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

like image 167
Óscar López Avatar answered Nov 16 '22 17:11

Óscar López


Another way of using built in functions, is using the reduce function:

>>> numeric = lambda x: int(x) if x.isdigit() else 0
>>> reduce(lambda x, y: x + numeric(y), 'hihello153john', 0)
9
like image 32
JCash Avatar answered Nov 16 '22 17:11

JCash


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
like image 35
Alex Reynolds Avatar answered Nov 16 '22 17:11

Alex Reynolds


One liner

sum_digits = lambda x: sum(int(y) for y in x if y.isdigit())
like image 1
shantanoo Avatar answered Nov 16 '22 18:11

shantanoo


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)))
like image 1
Santosh Pillai Avatar answered Nov 16 '22 19:11

Santosh Pillai