4 ms·
The only thing this does for me is ask why its not named count instead of sum.
by hobs 3y ago
The only thing this does for me is ask why its not named count instead of sum.
- scherlock 3y agoBecause what is happening I the list of ages is being transformed into a list of booleans where it's true if the age is greater than 17. This list of booleans is then turned into a list of integers where it's 1 if true, 0 if false. This list of integers is then being summed.
- ok_dad 3y agoIn Python a Boolean true and false are often used in mathematical formulas, so they will often implicitly be coerced into the integers 1 and 0. Sum is the sum function, you can sum a sequence of numbers, but in this case it’s summing a bunch of Boolean values which are coerced to 1 and 0.
- kragen 3y agobecause sum([1, 2]) is 3 and not 2
- Jtsummers 3y agoIt is summing but being used for counting (in imitation of the same style from APL) via punning on True/False as 1/0. Not what actually happens but conceptually: ages = [17, 13, 18, 30, 12] sum(age > 17 for age in ages) => sum([False, False, True, True, False]) => sum([0, 0, 1, 1, 0]) => 2 # via conventional summing Since True and False are 1 and 0 for arithmetic in Python, this is just a regular sum which also happens to produce a count.
- naijaboiler 3y agoyeah if i ready the line using "sum", I would be expecting the result 48 (18+30) not 2
- zuminator 3y agoUsing the same format, sum((age > 17)*age for age in ages), perhaps.
- pavon 3y agonumpy (which is inspired by Matlab which is inspired by APL) does indeed have a count_nonzero function, which is intended to be used in situations like this. Unfortunately, it (like most of numpy) doesn't work with generators, just array-like objects (aka numpy arrays and python lists), so it has the same memory performance issues as filtering and using len. If your input was a numpy array to begin with you could skip the array comprehension, and shorten it to numpy.count_nonzero(ages > 17), since numpy automatically broadcasts the comparison operation to each element of the array.
- fuzztester 3y agoHere, is "broadcasts" like apply or map of functional programming?
- pavon 3y agoYes, very similar. When performing an operation between an array and a scalar, it is identical to mapping that operation on each element of the array. Broadcasting generalizes this to also handle operations between matrices and vectors, such that the operation with the vector is applied to each row or column of the matrix.
- fuzztester 3y agoThank you.
- heavyset_go 3y agofrom collections import Counter total = Counter(range(10)).total() assert total == 10