Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

python - 在python中从一串数字中找到奇数和(Find the sum of odd numbers from a string of numbers in python)

the question asks to find the sum of odd numbers when given a string of numbers.

(该问题要求在给定一串数字时查找奇数之和。)

so for example, if we are given "123" we should get the sum of 4.

(因此,例如,如果给定的值为“ 123”,则总和为4。)

This is my attempt and it returns '4' which is incorrect

(这是我的尝试,返回“ 4”,这是不正确的)

def sumoddnum(s):
    total= 0
    for i in range(len(s)):
        if i % 2 == 1:
            total += i
    return total 
print(sumoddnum('12345'))

I've also tried converting s into integers but it keeps giving me the "int is not iterable" error

(我也尝试过将s转换为整数,但它一直给我“ int不可迭代”错误)

def sumoddnum(s):
    total= 0
    s= int(s)
    for i in s:
        if i % 2 == 1:
            total += i
    return total 
print(sumoddnum('12345'))
  ask by jennyislong translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should work for you:

(这应该为您工作:)

def sumoddnum(s):
  return sum(0 if int(i) % 2 == 0 else int(i) for i in s)

or if you want to keep your first attempt, you should iterate through your str then check the condition on every int of character:

(或者如果您想继续尝试,则应遍历str然后检查每个字符int的条件:)

def sumoddnum(s):
    total= 0
    for i in s:
        if int(i) % 2 == 1:
            total += int(i)
    return total 
print(sumoddnum('12345'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...