简体   繁体   English

字符串中数字的总和

[英]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.如果我只是在这里阅读我的sum_digits函数,它在我的脑海中是有道理的,但它似乎产生了错误的结果。 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对于函数sum_digits ,如果我输入sum_digits('hihello153john') ,它应该产生9

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() . 特别要注意,对于字符串类型, is_a_digit()方法已经存在,它称为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. 如上所示,使用生成器表达式作为内置函数sum()的参数,可以更简洁地表示sum_digits()函数中的整个循环。

You're resetting the value of b on each iteration, if a is a digit. 如果a是数字,则每次迭代时都要重置b的值。

Perhaps you want: 也许您想要:

b += int(a)

Instead of: 代替:

b = int(a)
b += 1

Another way of using built in functions, is using the reduce function: 使用内置函数的另一种方法是使用reduce函数:

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

一支班轮

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: 我想提出一个使用regx的不同解决方案,该方案涵盖两种情况:

1. 1。
Input = 'abcd45def05' 输入='abcd45def05'
Output = 45 + 05 = 50 输出= 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. 2。
Input = 'abcd45def05' 输入='abcd45def05'
Output = 4 + 5 + 0 + 5 = 14 输出= 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. 它比“ for”版本运行得更快,并节省了大量代码。

Just a variation to @oscar's answer, if we need the sum to be single digit, 只是@oscar答案的一种变体,如果我们需要总和为一位数,

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
#if string =he15ll15oo10
#sum of number =15+15+10=40

def sum_of_all_Number(s):
    num = 0
    sum = 0

    for i in s:
        if i.isdigit():
            num = num * 10 + int(i)
        else:
            sum = sum + num
            num = 0
    return sum+num

#if string =he15ll15oo10
#sum of digit=1+5+1+5+1+0=13

def sum_of_Digit(s):
    sum = 0

    for i in s:
        if i.isdigit():
             sum= sum + int(i)

    return sum

s = input("Enter any String ")

print("Sum of Number =", sum_of_all_Number(s))
print("Sum Of Digit =", sum_of_Digit(s))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM