4 ms·
A super common solution to the problem of too many ideas packed into a clever solution is just naming intermediate things. For example, naming the zip(...) is a
by ianhorn 6y ago
A super common solution to the problem of too many ideas packed into a clever solution is just naming intermediate things. For example, naming the zip(...) is a little change that goes pretty far in making the second one more obvious:
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
xs = sorted(x for x, _ in points)
neighboring_coordinates = zip(xs, xs[1:]))
return max(right-left for left, right in neighboring_coordinates)
or even naming the width generator:
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
xs = sorted(x for x, _ in points)
neighboring_coordinates = zip(xs, xs[1:]))
widths = (right-left for left, right in neighboring_coordinates)
return max(widths)
Same thing, just with more built in explanation. It's easy to go overboard, of course, but it's a useful go-to to make stuff more obvious.
- michaelhoffman 6y agoWhitespace helps too! And I think using `sorted(key=)` is more Pythonic than a generator expression ;) from operator import itemgetter def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: xs = sorted(points, key=itemgetter(0)) x_pairs = zip(xs, xs[1:]) widths = (right-left for left, right in x_pairs) return max(widths) NumPy also has stuff to solve this sort of thing built-in: from numpy import diff def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: xs = sorted(points, key=itemgetter(0)) widths = diff(xs) return widths.max()
- ianhorn 6y agoFor the last bunch of years, wherever my instinct says to add white space, I instead put a comment. If you want something to be a visually separate entity, it’s the perfect place to put a couple words about that entity, and it still gets the visual separation in an editor with any syntax highlighting at all.
- roelschroeven 6y ago> And I think using `sorted(key=)` is more Pythonic than a generator expression ;) But it doesn't do the same thing. The original code extracted the xs from the coordinate pairs, sorted; your code sorts the coordinate pairs by their x values, but doesn't extract the xs from them.
- michaelhoffman 6y agoOops! Good point! Unfortunately too late for me to edit.