-3

If I have a integer

number = 468471365418971

how am I able to get every even and odd digit and add them together in Python?

So I want to get 4, 6, 8, 6, etc for even and add these together and 7, 1 , 3, 5, etc. and add these together

Natch
  • 41
  • 1
  • 5
  • 5
    What have you tried this far. SO guidelines says that you should provide us a code example and community can help you solve a problem in your code. Not code for you. – ex4 Sep 22 '21 at 04:33
  • Convert to string -> iterate over each char -> parse to int -> test if `i % 2 == 0` to finally test if is an even or odd number – philipp Sep 22 '21 at 04:36

4 Answers4

3

You can try in this way:

even = []
odd = []
number = 468471365418971
for i in str(number):
    if int(i)%2:
        odd.append(int(i))
    else:
        even.append(int(i))
print("sum of even integers",sum(even))
print("sum of odd integers",sum(odd))

This will give the output of both odd and even integers sum.

There is a simple way of doing this too:

number = 468471365418971
print("sum of odd integers",sum([int(i) for i in str(number) if i%2]))
print("sum of even integers",sum([int(i) for i in str(number) if i%2==0]))
SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
1

To demonstrate an approach without string conversion.

number = 468471365418971

def getdigits(n):
    while n:
        n, digit = divmod(n, 10)
        yield digit

# see https://stackoverflow.com/a/8793925/1540468
def splitter(data, pred):
    yes, no = [], []
    for d in data:
        (yes if pred(d) else no).append(d)
    return [yes, no]

print([sum(x) for x in splitter(getdigits(number), lambda n: n & 1)])

Output:

[34, 40]

We can break a number down to its constituent decimal digits by progressively taking the modulus (remainder) of it and 10, then dividing (integer division) by 10. We can perform this process again and again until the remaining number is 0. After that if can partition the resulting list into odd and even numbers we can use sum on those two lists to arrive at the totals.

The string way is probably clearer, but this another way to do it that would no doubt perform better in some languages.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
0

Or you could do this:

>>> sum(map(int, filter('02468'.__contains__, str(number))))
40
>>> sum(map(int, filter('13579'.__contains__, str(number))))
34
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

by checking each one place and appending them in odd and even no

def func(n):
    even = []
    odd = []
    while n:
        if n%2==1:
            odd.append(n%10)
        else:
             even.append(n%10)
        n//=10
    return odd, even
number = 468471365418971
print(func(number))

output

([1, 7, 9, 1, 5, 3, 1, 7], [8, 4, 6, 4, 8, 6, 4])
sahasrara62
  • 10,069
  • 3
  • 29
  • 44