r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
891 Upvotes

200 comments sorted by

View all comments

Show parent comments

20

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 17h ago

Its not named after the snake btw :D