Home > Blockchain >  Sum: what is the difference between these two pieces of code?
Sum: what is the difference between these two pieces of code?

Time:09-04

The problem in question asks to calculate sums using while loops where end is a variable that represents the last integer in a sum. For example, in 1 2 3 4 = 10, end = 4

The two solutions below, to me, seem to be the exact same thing in different order within the loop. Both incrementally assign a new value and track the sum.

My question

What is the difference? Solution 2 was graded as incorrect.

Solution 1

total = 0
current_total = 1
while current_total <= end:
    total  = current_total
    current_total  = 1
    
print(total)

Solution 2

total = 0
current_total = 0
while current_total <= end:
    current_total  = 1
    total  = current_total

    
print(total)

Thank you.

CodePudding user response:

Solution 2 increments "current_total" after checking the end condition so will always go one step too far. After checking N, you then add N 1 to the total. Place both solutions into functions and then pass in some values and you'll see.

def t1(end):
    total = 0
    current_total = 1
    while current_total <= end:
        total  = current_total
        current_total  = 1

    print(total)

def t2(end):
    total = 0
    current_total = 0
    while current_total <= end:
        current_total  = 1
        total  = current_total

    print(total)

t1(1)
t2(1)
print('----')
t1(4)
t2(4)

output

1
3
----
10
15

Even if you tried changing the while condition, you'd have to check the boundary case end = 1 to be sure you got the math right.

CodePudding user response:

It's more of a math case than programming, but the the second solution increment current_total slower, giving the loop excess steps what makes a different output.

You can see it for yourself, if your IDE has step-by-step execution or using an online execution visualizer, like this one.

  • Related