gpt4 book ai didi

python - 使用Python求数组中奇数之和的函数?

转载 作者:行者123 更新时间:2023-12-01 06:35:39 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,它将接受单个数字或数组作为输入,结果应该是数组中小于或等于输入数字的奇数之和。

示例:如果输入为 9,则结果应为 25,即 1+3+5+7+9。如果输入是数组 ar[4,5],则结果应为 4 和 9 打印在单独的行中。

下面是我的代码,它在采用单个输入时有效,但我不确定如何继续使用数组作为输入。

def oddsum(x): 
sum = 0
for i in range(x+1):
# Loop to find odd Sum
if i % 2 != 0:
sum +=i
return sum

最佳答案

使用函数type检查Python中事物的类型:

def oddsum_int(x): 
sum = 0
for i in range(1,x+1,2):
sum +=i
return sum

def oddsum(x):
'''`x` may be `list` or `int`'''
if type(x) == list:
for i in x:
print(oddsum_int(i))
elif type(x) == int:
print(oddsum_int(x))
else:
raise TypeError("Couldn't handle input of type {}".format(type(x)))

>
oddsum(9)
>25
oddsum([4,5])
>4
>9

关于python - 使用Python求数组中奇数之和的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59683058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com