总结整数中的奇数



以下是我添加整数的奇数时的尝试:

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

有什么提示吗?

怎么样:

代码:

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

测试代码:

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

结果:

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

否则,您可以使用Pythonic在Python中使用divmod的方法。并请注意,通常DIV和模式比投射到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

您也可以尝试以下方法:

数据的预处理:

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

在处理的数据上操作:

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

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

输出:

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>

最新更新