Sum of digits in a string

好久不见. 提交于 2019-11-29 07:07:37

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())

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.

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
JCash

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
shantanoo

One liner

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

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)))

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

An equivalent for your code, using list comprehensions:

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

It will run faster then a "for" version, and saves a lot of code.

Just a variation to @oscar's answer, if we need the sum to be 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!