I literally just finished a leetcode problem[1] to practice some python. I found two solutions, one seems more "pythonic" to me and the other seems more clear though also more verbose.
Clear/Verbose -
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
x_coords = sorted(x for x, _ in points)
greatest_diff_so_far = 0
for i in range(len(x_coords)-1):
diff = x_coords[i+1] - x_coords[i]
if diff > greatest_diff_so_far:
greatest_diff_so_far = diff
return greatest_diff_so_far
Pythonic -
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
xs = sorted(x for x, _ in points)
return max(x2-x1 for x1, x2 in zip(xs, xs[1:]))
I'm curious which approach is bad/worse? On the one hand, the "pythonic" approach seems brief and kind of neat and I feel clever writing it. On the other hand, it is also ~20% slower per my testing, it's less obvious what it's doing, and it would be harder to make some change to the logic (or add logging/metrics) without completely rewriting it.
On the one hand, just from the reasons I wrote above, it seems to me like the first way is better and the second worse, but on the other hand, the first way is what I would write while knowing zero python features. Curious if anyone else has thoughts on this.
1 - https://leetcode.com/problems/widest-vertical-area-between-t...
Clear/Verbose -
Pythonic - I'm curious which approach is bad/worse? On the one hand, the "pythonic" approach seems brief and kind of neat and I feel clever writing it. On the other hand, it is also ~20% slower per my testing, it's less obvious what it's doing, and it would be harder to make some change to the logic (or add logging/metrics) without completely rewriting it.On the one hand, just from the reasons I wrote above, it seems to me like the first way is better and the second worse, but on the other hand, the first way is what I would write while knowing zero python features. Curious if anyone else has thoughts on this.
1 - https://leetcode.com/problems/widest-vertical-area-between-t...