问题要求在给定一串数字的情况下求奇数之和。 因此,例如,如果给定“123”,我们应该得到 4 的总和。
这是我的尝试,它返回不正确的“4”
def sumoddnum(s):
total= 0
for i in range(len(s)):
if i % 2 == 1:
total += i
return total
print(sumoddnum('12345'))
我也尝试过将 s 转换为整数,但它一直给我“int is not iterable”错误
def sumoddnum(s):
total= 0
s= int(s)
for i in s:
if i % 2 == 1:
total += i
return total
print(sumoddnum('12345'))
最佳答案
这应该适合你:
def sumoddnum(s):
return sum(0 if int(i) % 2 == 0 else int(i) for i in s)
或者如果你想保持你的第一次尝试,你应该遍历你的 str
然后检查每个 int
字符的条件:
def sumoddnum(s):
total= 0
for i in s:
if int(i) % 2 == 1:
total += int(i)
return total
print(sumoddnum('12345'))
关于python - 从python中的一串数字中找到奇数的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59123325/