This is a generator expression inside a call to the sum
function. sum
just adds things up, so let's look at the generator expression:
(i+j)%k == 0 for x, i in enumerate(a) for j in a[x+1:]
The (i+j)%k == 0
part is a boolean expression. It's either true if i+j
has a remainder of 0
when dived by k
or false otherwise. As a neat little trick, the True
value has a numeric value of 1
in python, and False
has a numeric value of 0
. So this is basically just counting.
for x, i in enumerate(a) for j in a[x+1:]
This is essentially a nested for loop.
for x, i in enumerate(a):
for j in a[x+1:]:
enumerate
is a function that yields items from an iterable paired with their index, so [a, b, c]
becomes [(0, a), (1, b), (2, c)]
Stick it all together, and this code calculates the number of pairs of elements in a list such that their sum is divisible byk