3 ms·
The author seems to misunderstand one part of The Zen of Python: | Simple is better than complex. by saying: > Our code is more complex (O(n2) instead of O(n
by vog 11y ago
The author seems to misunderstand one part of The Zen of Python:
| Simple is better than complex.
by saying:
> Our code is more complex (O(n2) instead of O(n)), less beautiful, and less readable
The Zen is not about computation complexity! It's about complexity of the source code.
The code in question is:
color_counts = dict((c, colors.count(c)) for c in set(colors))
And while I agree that this is inefficient and shouldn't be used in a library, I find this to be very readable and would always prefer that code if I know that I'm dealing only with small lists. It translates neatly to a natural-language description of the problem:
Give me a dictionary that maps each distinct color
to the number of times it occurs in the list.
So I don't think this violates the guide "Simple is better than complex". Rather, it is a good example where it makes sense to introduce additional complexity to improve the performance of an often-used helper function.
- adrianN 11y agoI don't think you should get into the habit of writing O(n^2) algorithms if the O(n) solution is not much more complex. Unless the constants are very dissimilar, you probably hurt your performance already for a few hundred elements. Writing reusable code includes using algorithms that are ok for a wide range of input sizes.
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- SZJX 11y agoI have no idea how the author found this code more complex. Probably he's still more used to imperative programming, but functional programming styles and one liners will mostly greatly simply the understanding of the code.