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
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
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]))
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.
Or you could do this:
>>> sum(map(int, filter('02468'.__contains__, str(number))))
40
>>> sum(map(int, filter('13579'.__contains__, str(number))))
34
>>>
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])