0

My problem is basically that both of this peaces of code work proparly, however, the second solution with key = min doesn't make sence to me. How does python go through this code? Why does it ignore sorting the letters and goes straight to sorting by digits? I can't understand the underlying logics of this code.

My code:

def order(sentence):
    return ' '.join(sorted(sentence.split(), key=lambda s: int("".join(filter(str.isdigit, s)))))


print(order("is2 Thi1s T4est 3a"))

Second solution

def order(sentence):
    return ' '.join(sorted(sentence.split(), key=min))


print(order("is2 Thi1s T4est 3a"))

The answer is correct in both cases:

Thi1s is2 3a T4est
  • 1
    Well, what does `min('Thi1s')` return? `'1'`. Why? Because *"[`min` returns] the smallest item in an iterable"*. A string is an *iterable*, and `1` is the "smallest" character in it. – deceze Jan 29 '20 at 14:42

1 Answers1

3

This works because numbers come before letters in the Unicode encoding system, and given that sorted sorts lexicographically, the list will be sorted according to the smaller value in the table in each string. You can see this with:

s = "is2 Thi1s T4est 3a"
[min(i) for i in s.split()]
# ['2', '1', '4', '3']

You can check that indeed the Unicode value for the numbers are smaller by using ord, which will return the position in the table for each value:

s = "is2 Thi1s T4est 3a"
for i in s.split():
    for j in i:
        print(f'{j} -> {ord(j)}')
    print()

i -> 105
s -> 115
2 -> 50

T -> 84
h -> 104
i -> 105
1 -> 49
s -> 115

T -> 84
4 -> 52
e -> 101
s -> 115
t -> 116

3 -> 51
a -> 97
yatu
  • 86,083
  • 12
  • 84
  • 139
  • Note that it's not necessarily the *ASCII* value, since you can do this with all Unicode characters… – deceze Jan 29 '20 at 14:49
  • Well yes this applies to unicode, values, I will update. However if I'm not mistaking all numbers and basic latin characters are mapped in the same way @deceze – yatu Jan 29 '20 at 14:51
  • Yes, sure, in the range we're talking about here ASCII equals Unicode. It just might send the wrong message to future readers. – deceze Jan 29 '20 at 14:54