Sum of odd digits in a string python

the question asks to find the sum of odd numbers when given a string of numbers. so for example, if we are given "123" we should get the sum of 4.

This is my attempt and it returns '4' which is incorrect

def sumoddnum(s):
    total= 0
    for i in range(len(s)):
        if i % 2 == 1:
            total += i
    return total 
print(sumoddnum('12345'))

I've also tried converting s into integers but it keeps giving me the "int is not iterable" error

def sumoddnum(s):
    total= 0
    s= int(s)
    for i in s:
        if i % 2 == 1:
            total += i
    return total 
print(sumoddnum('12345'))

asked Dec 1, 2019 at 7:07

This should work for you:

def sumoddnum(s):
  return sum(0 if int(i) % 2 == 0 else int(i) for i in s)

or if you want to keep your first attempt, you should iterate through your str then check the condition on every int of character:

def sumoddnum(s):
    total= 0
    for i in s:
        if int(i) % 2 == 1:
            total += int(i)
    return total 
print(sumoddnum('12345'))

answered Dec 1, 2019 at 7:17

AyoubAyoub

1,40916 silver badges24 bronze badges

I like using a regex approach here. We can apply the regex pattern [13579] to the input string, then use a list comprehension on the resulting list of odd digits to find the sum:

num = "123"
odds = re.findall(r'[13579]', num)
sum = sum(int(odd) for odd in odds)
print("the sum is: " + str(sum))

This prints:

The sum is: 4

answered Dec 1, 2019 at 7:24

Sum of odd digits in a string python

Tim BiegeleisenTim Biegeleisen

468k24 gold badges253 silver badges330 bronze badges

Your first approach does not work because what you're actually adding to the sum are 'indices' of s not it's elements. What could have work is changing your for loop to run over elements instead of their positions. Then keep in mind that elements of a string are characters so a conversion to the int is required. This can be done with built-in int function whenever the character actually represents a digit.

def sumoddnum(s):
    total= 0
    for i in s:
        if int(i) % 2 == 1:
            total += int(i)
    return total 

Now at this point you may wonder

what a long function for such a simple task!

and you'll be absolutely right. Luckily, Python comes with comprehensions which allow us to shorten some of the for loops and built-in sum function which purpose is kinda self-explanatory but what you need to remember that it takes iterables as its input.

The result you may get will be something like this:

def sumoddnum(s):
    return sum(int(i) for i in s if int(i) % 2 == 1)

With Python 3.8 you can also make use of brand new walrus operator:

def sumoddnum(s):
    return sum(num for i in s if (num := int(i)) % 2 == 1)

The problem with your second approach is already explained by the Python interpreter itself. You've converted your string to the integer, and there's no built-in way too loop over integers. You'll need to find and implement your own way to loop over integer's digits (hint: use remainder modulo 10).

answered Dec 1, 2019 at 7:48

PoneworPonewor

1012 silver badges5 bronze badges

The reason your program is not working is because of the line:

for i in range(len(str)):

here, you are taking all values of i from 0 to the length of the string (exclusive of length).

This means, you are adding up all the odd numbers from 0 to the length of the String.

Instead do this:

for i in str:

this will give you each character in the string as i. Now:

i = int(i)

will convert it to int.

Finally :

if i%2 == 1: 
    total+=i

the final code will be:

def sumoddnum(s):
    total= 0
    for i in s:
        i = int(i)
        if i % 2 == 1:
            total += i
    return total 
print(sumoddnum('12345'))

answered Dec 1, 2019 at 7:54

Sum of odd digits in a string python

def sumoddnum(s):
    total= 0
    for i in s:
        i = int(i)
        if i % 2 == 1:
            total += i
    return total 
print(sumoddnum('12345'))

if you use 'range(len(s))' in for loop instead of 's', it will give you [0,1,2,3,4] which is 0 to length of the '12345.

Therefore, it is required to change the range by just s, then it will give you ['1','2','3','4','5'] which is char elements of string '12345'.

Don't forget to change the type of i to int!

answered Dec 1, 2019 at 7:47

Sum of odd digits in a string python

Here is a better and more readable solution:

def add_up(n: str or int):
   if type(n) == str and str(n).isdigit():
       numbers = [int(n) for n in list(n.strip()) if int(n) % 2 != 0]
       return sum(numbers)
   elif type(n) == int:
       numbers = [int(str(n)) for n in list(str(n)) if n % 2 != 0]
       return sum(numbers)
   else:
       return "No digits found to add up"

answered Dec 1, 2019 at 7:42

Sum of odd digits in a string python

moh80smoh80s

7551 gold badge7 silver badges21 bronze badges

1

How do you find the sum of odd digits in Python?

Working :.
Step 1: Read the integer input..
Step 2: initialize s and set it to zero..
Step 3: using modulo with 10 logic we will get last digit of the number..
Step 4: Do this operation by using while loop..
Step 5: Check whether the number is odd or not , if number is odd add to the result..
Step 6: Print the resultant sum..

How do you find the sum of digits in an odd place?

Approach: First, calculate the reverse of the given number. To the reverse number we apply modulus operator and extract its last digit which is actually the first digit of a number so it is odd positioned digit. The next digit will be even positioned digit, and we can take the sum in alternating turns.

How do you add odd items to a list in Python?

Practical Data Science using Python We have to find sum of all odd elements from the list. So, if the input is like nums = [5,7,6,4,6,9,3,6,2], then the output will be 24 because 5+7+9+3 = 24. return the sum of elements in l by passing l into sum() function.