简体   繁体   中英

Sum the odd digits in an integer

Below is my attempt when adding the odd digits of an integer:

def sumOdd(n):
    for i in range(n):
        if n % 2 == 0:  # if n is odd
            n -= 1
    print(sum(range(1, n, 2)) + n)  # The range(1,n,2) starts at 1 and counts by twos until it reaches n


sumOdd(123)  # 4

Any tips?

How about something like:

Code:

def sum_odd_digits(number):
    return sum(int(d) for d in str(number) if d in '13579')

Test Code:

print(sum_odd_digits(123))
print(sum_odd_digits(133))

Results:

4
7

two solutions, one is cast it to string, another is directly handle it as integer.

def sumOdd(n):
    n = str(n)
    sumn = 0
    for i in n:
        i = int(i)
        if i % 2 == 1:  # if n is odd
            sumn+=i
    return sumn

print(sumOdd(132495)) # 4388797504


def sumOdd_(n):
    n = abs(n)
    sumn = 0
    while n>0:
        digit = n%10
        n = n//10
        if digit %2 ==1:
            sumn+=digit
    return sumn

myn = 132495
assert sumOdd_(myn)==sumOdd(myn)

Or else, you could use pythonic way of using divmod in Python. And do note that generally div and mode runs faster than casting to str.

def sumOdd_2(n):
    sumn=0
    while n:
        # "pop" the rightmost digit
        n, digit = divmod(n, 10)
        if digit %2 ==1:
            sumn+=digit
    return sumn

You can also try this:

Preprocessing of data:

data=123456789

real_data=list(map(int,str(data)))

operation on processed data:

print(sum(filter(lambda x:x%2,real_data)))

or

print(functools.reduce(lambda x,y:x+y,(filter(lambda x:x%2,real_data))))

output:

25

 <pre> def check_odd(a): if a % 2 == 1: return True else: return False def extract_last_digit(a): return a % 10 def remove_last_digit(a): return a // 10 x = input('Type an integer: ') n = int(x) if n < 0: # the integer may be negative (alternatively use n = abs(int(x)) in previous line) n = -1*n sum_odd_n = 0 while n:= 0: if check_odd(n) == True, sum_odd_n += extract_last_digit(n) n = remove_last_digit(n) print('The sum of the odd digits in number ', x, ' is ', str(sum_odd_n)) </pre>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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