user1864828
user1864828

Reputation: 359

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

Upvotes: 13

Views: 70938

Answers (10)

Not Bedo
Not Bedo

Reputation: 21

simply turn the input to integer by int(a) ---> using a.isdigit to make sure the input not None ('') , if the input none make it 0 and return sum of the inputs in a string simply

def sum_str(a, b):
    a = int(a) if a.isdigit() else 0
    b = int(b) if b.isdigit() else 0
    return f'{a+b}'

Upvotes: 0

Sanjay Rai
Sanjay Rai

Reputation: 27

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

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236034

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.

Upvotes: 31

Leonardo Lima
Leonardo Lima

Reputation: 11

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

Upvotes: 1

Santosh Pillai
Santosh Pillai

Reputation: 8653

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

Upvotes: 1

Babu
Babu

Reputation: 2598

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

Upvotes: 0

JCash
JCash

Reputation: 322

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

Upvotes: 5

shantanoo
shantanoo

Reputation: 3704

One liner

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

Upvotes: 1

kaspersky
kaspersky

Reputation: 4097

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.

Upvotes: 0

Alex Reynolds
Alex Reynolds

Reputation: 96967

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

Upvotes: 10

Related Questions