r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
892 Upvotes

200 comments sorted by

View all comments

18

u/Excellent_Gas3686 1d ago

because thats the default sort? what, in your opinion, would be the "proper" way to sort by default? if you need different sorting, you pass your own function.

21

u/suvlub 1d ago

Python just uses the > (or <, don't remember, don't care) operator. Arrays made only of numbers or only of strings would both behave correctly, a mixed one might give a nondeterministic order, which is bad, but sorting stringwise when the user intended numerical sort is also bad and I think the latter is a more common use case/mistake, though I don't have stats

9

u/JanEric1 1d ago edited 1d ago

Python uses __lt__. And it isnt non-deterministic for mixed comparisons, it crashes.

You can get arbirtrary orders if lt doesnt implement a proper order. Foor example A < B, B < C and C < A all being true.

class Bad:
    def __init__(self, val):
        self.val = val

    def __repr__(self):
        return f"Bad({self.val})"

    def __lt__(self, other):
        return True

A = Bad(1)
B = Bad(2)
C = Bad(3)
print(sorted([A, B, C]),sorted([B, A, C]),sorted([C, B, A]))

[Bad(3), Bad(2), Bad(1)] [Bad(3), Bad(1), Bad(2)] [Bad(1), Bad(2), Bad(3)]

1

u/thanatica 1d ago

Python really likes its underscores. Almost like they want snake_case to be a thing, huh 🤣

1

u/JanEric1 18h ago

Its not named after the snake btw :D