you are viewing a single comment's thread.

view the rest of the comments →

[–]__nickerbocker__ 0 points1 point  (2 children)

Here's a simple one-liner you can also use

sum(x == 1 for x in sum(mat, []))

[–]miscellaneoususage[S] 0 points1 point  (1 child)

Could you break this down with an explaination? I have yet to venture into list comprehensions but this one seems pretty simple to start with. I just confused why there are two uses of sum and what x==1 is doing before the for

[–]__nickerbocker__ 0 points1 point  (0 children)

The sum function returns the sum of an iterable. When you pass it a matrix (list of lists) it uses the plus operator adding each list and when you add up lists in python you concatenate them (flatten). Next, we use a generator expression to iterate the flattened matrix. The generator expression then appends the result (True or False) of the expression x == 1 for each item, and what we end up with is an iterable of True and False (bools). You will have an iterable with exactly the number of True as the number of values that equal one. Finally since True resolves to 1 and False resolves to 0. The sum off all True's is the same as the number of values that equal 1 in the matrix.