Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将奇数相加为整数_Python_Function_Loops_Sum - Fatal编程技术网

Python 将奇数相加为整数

Python 将奇数相加为整数,python,function,loops,sum,Python,Function,Loops,Sum,下面是我在添加整数的奇数位数时的尝试: 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 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 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)
或者,您可以使用Python中使用
divmod
的Python方式。请注意,通常div和mode比casting到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)))

输出:

25

def检查单(a):
如果%2==1:
返回真值
其他:
返回错误
def提取最后一位数字(a):
返回%10
def删除最后一位数字(a):
返回a//10
x=输入('键入一个整数:')
n=int(x)
如果n<0:#整数可能是负数(或者在前一行中使用n=abs(int(x)))
n=-1*n
奇数和=0
而n!=0:   
如果检查奇数(n)=真:
求和奇数n+=提取最后一位(n)
n=删除最后一位(n)
print('x',is',str(sum_odd_n))中奇数位数的和)

我正试图准确地理解您的问题是什么?所以您的最大
奇数
仅为
9
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