Ad

How Does Append() Work In This Code Snippet? Confused With A Particular Variable

- 1 answer

Can someone explain this code to me? More specifically, the part about lead.append([sum1 - sum2 , 1]) and print(ans[1],ans[0]).

I do not understand the "1" in "lead.append([sum1 - sum2 , 1])"

I, also, do not understand the "1" and "0" in print(ans[1],ans[0]).

lead = []
sum1 , sum2 = 0 , 0
for i in range(int(input())):
    a1 , a2 = map(int, input().split())
    sum1 += a1
    sum2 += a2
    if sum1>sum2:
        lead.append([sum1 - sum2 , 1])
    else:
        lead.append([sum2 - sum1 , 2])

ans = max(lead)
print(ans[1],ans[0])

Thanks.

Ad

Answer

lead.append([sum2 - sum1 , 2])

This is appending to the list 'lead' the value inside the brackets.

[sum2 - sum1, 2] <- inside the brackets

The 2 or 1 you are referring to is inside a list itself. So you would be appending these entries to the list. The code seems to check which of sum1/sum2 is greater and then subtracts the lesser one, adding the corresponding value to the list 'lead'.

The last line, assuming that all items in the list are lists themselves, should print the 2nd value of the sublist, then the 1st value of the sublist.

In [18]: lead = [[100, 2], [200, 1], [400, 3]]

In [19]: max(lead)
Out[19]: [400, 3]

In [20]: ans = max(lead)

In [21]: print(ans[1], ans[0])
3 400
Ad
source: stackoverflow.com
Ad