4 ms·
As cool as they look when you write them, comprehensions this dense obfuscate your code. Splitting this into multiple lines helps, but it would be much easier t
by css 6y ago
As cool as they look when you write them, comprehensions this dense obfuscate your code. Splitting this into multiple lines helps, but it would be much easier to understand as a normal for loop.
If the goal is to just know the number of items in each slot, here is the first thing that came to my mind (and does not require any iteration):
groups = [n // g + n % g] + [n // g] * (g - 1)
- uyt 6y agoThe author wants leftovers to be evenly distributed. For example for n=15 and g=4 he wants [5,5,5]. I think his very first 3 liner is the most readable version. If we're microoptimizing, his comprehension version also has a lot of extra divisions. I would write something like this instead: q1, r1 = divmod(n, g) q2, r2 = divmod(r1, q1) print(n, [g + q2 + 1] * r2 + [g + q2] * (q1 - r2))
- llarsson 6y agoAgreed. Don't see where iteration would be needed here if knowing group size is the actual goal. It looks like a blog post that arrives at "this is essentially what the modulo operator does for you", but with an O(n) algorithm. However, add a step inside that iterative loop that chooses, at random and without repeats, the actual named employees that will be in these meetings (which I believe will be the point), and none of this matters anyway, since you will wind up with something that is worse than O(n) anyway. You intrinsically have to iterate over the entire list and then, somehow, also choose employees at random, which cannot be "free" in computational terms.