Sum of digits in a string

55,355

Solution 1

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.

Solution 2

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

Solution 3

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

Solution 4

One liner

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

Solution 5

Another way of doing it:

def digit_sum(n):
  new_n = str(n)
  sum = 0
  for i in new_n:
    sum += int(i)
  return sum
Share:
55,355
user1864828
Author by

user1864828

Updated on July 17, 2022

Comments

  • user1864828
    user1864828 almost 2 years

    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

    • CharlesB
      CharlesB over 11 years
      and what do you get instead of 9?
    • Thai Tran
      Thai Tran over 11 years
      it produces 4 because it takes the last number 3 and plus 1 to it, since you set back the value of b every time running the loop
  • user1864828
    user1864828 over 11 years
    wow that works! could you explain why mine didnt work though?
  • Alex Reynolds
    Alex Reynolds over 11 years
    The line b = int(a) sets the value of b to be the integer value of the digit character. Then you add one to it. In your example, the last digit is 3, so you set b to 3 and then add 1, getting 4. Instead, you want to increment b by each digit's value.
  • Óscar López
    Óscar López almost 3 years
    @HaseeBMir of course if doesn't work... in ideone you need to explicitly print the result. There is nothing wrong with my implementation, it'll work in any real interpreter, you just forgot to add a print(). Kindly remove your downvote, the problem is with your code, not mine.
  • Óscar López
    Óscar López almost 3 years
    @HaseeBMir you shouldn't test other people's code in ideone, use a real interpreter, otherwise you'll get incorrect results.
  • Haseeb Mir
    Haseeb Mir almost 3 years
    ideone is most accurate coding editor out there
  • Haseeb Mir
    Haseeb Mir almost 3 years
    You should write full code then for all compilers and interpreters.
  • Óscar López
    Óscar López almost 3 years
    @HaseeBMir why don't you take a look at all the other million Python answers that are in this site? if you have free time in your hands you can start adding a print() to literally all of them, because according to you they are "all wrong" and should work "on all compilers and interpreters" and "ideone is the most accurate editor" xD
  • Haseeb Mir
    Haseeb Mir almost 3 years
    Okay no worries i removed downvote now i use main compiled languages not interpreted so I think its fine for python language. Cheers