简体   繁体   中英

For loops and floor division in python

I just had a question about this for loop

total = 0

for x in range(1,15,3):

    total += x

    total //= 2

print(total)

So the answer is 10 when I run it, but when I try to do it by hand I get 17. For example when I add up all the x's it will be 35. Then I floor divide by 2 which will give me 35//2 =17. I honestly don't know why its 10.

Your code is computing sums like this:

(((0 + x1) / 2 + x2) / 2 + x3) / 2 + ...

You can perform the division to see that this is not the same as (0 + x1 + x2 + x3 + ...) / 2 . For example:

((x1/2 + x2)/2 + x3)/2 == x1/8 + x2/4 + x3/2

Just place total //= 2 outside the for loop. your code is finding the floor value of total in every iteration and overwriting total.

total = 0
for x in range(1, 15, 3):
    total += x
total //= 2
print(total)

In Python the tab matters. The following will give you 17

total = 0

for x in range(1,15,3):

    total += x

total //= 2

print(total)

It gets floored in the loop, you're adding up the floored values.

You need to floor the sum, after the loop is done.

total = 0
for x in range(1, 15, 3):
    total += x
total //= 2
print(total)
total = 0

for x in range(1,15,3):
    total += x

    a = total//2



print(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM