Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How can I write this C for loop in Python? - what is the best solution?


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

1 Reply

0 votes
by (71.8m points)

The closest equivalent of your C/Java code in Python would be this:

total = 0
i = 0
while number > 0:
    if i % 2 == 0:
        total += number % 10
        number //= 10
    i += 1

This is not very elegant, as you have to rewrite the for (...;...;...) loop with a while and separate lines for initialization and increment. Note that his is close to what you have, but there are two important differences: First, the i += 1 should be at the end of the loop, as the third block of the for is also executed after each iteration. Also note the // for integer division in Python!

This just calculates the sum of all digits. The i % 2 part is irrelevant as the number //= 10 bit is only executed within that block, so it just makes the outer loop run twice as long. If that is indeed what you want, you could simplify it to this, without i:

while number > 0:
    total += number % 10
    number //= 10

Or just this:

total = sum(map(int, str(number)))

If, however, you want to add every other digit (starting from the end), e.g. 6+4+2 for 123456, then you have to move the /= 10 part to the outer loop (in the first version including i), i.e. decrease the indentation in Python. The rest remains the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...