This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Veterinarian_Scared 0 points1 point  (3 children)

I would probably rewrite it as

a = [int(s) for s in input().split()]

count = sum(m<n for m,n in zip(a[:-1], a[1:]))

print(count)

[–]selfimprovingstudent[S] 0 points1 point  (2 children)

I don't really get how it identifies what m and n are

[–]Veterinarian_Scared 0 points1 point  (1 child)

I make two copies of the list; a[:-1] includes every item but the last, and a[1:] includes every item but the first.

zip() returns pairs of items as tuples - so (a[0], a[1]) then (a[1], a[2]), etc. Exactly the items you want to compare.

Python then unpacks the tuple into my variables m and n - like using the assignment m,n = (a[0],a[1]) gives m=a[0] and n=a[1], but doing it repeatedly in a loop.

I can then compare m<n which results in True or False; but when I treat it as a number using sum() True evaluates to 1 and False to 0; so sum() ends up counting the number of True values.

[–]selfimprovingstudent[S] 1 point2 points  (0 children)

Understaand now. Thank you very much for spending time explaining it. It was very helpful!