progress

~/problems / Arrays & hashing / Sorting, custom keys, coordinate compression

Natural order for scanned photos

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

As plain strings, "img10" sorts before "img9", which annoys everyone. Write natural_sort(names: list[str]) -> list[str] that returns a new list in natural order:

  1. Split names into chunks: maximal runs of digits and of non-digits ("Roll2_img10.jpg" is "Roll", "2", "_img", "10", ".jpg").
  2. Compare chunk by chunk: digit chunks by numeric value ("007" equals "7"), text chunks case-insensitively, and a digit chunk sorts before a text chunk.
  3. If one name runs out first, it comes first. Still tied? Compare the whole names as plain strings.
natural_sort(["img10.jpg", "img9.jpg", "IMG2.jpg", "img2.JPG"])
# ["IMG2.jpg", "img2.JPG", "img9.jpg", "img10.jpg"]

natural_sort(["a7", "a07", "a", "7a"])
# ["7a", "a", "a07", "a7"]

Up to 10^5 names of 0 to 30 printable ASCII characters; don't change the input.

⭐ Bonus: a speed test with 20,000 names earns a star if you compute one key per name and sort once.

Show hint

re.findall(r"\d+|\D+", name) gives the chunks. Make each a same-shaped tuple, (0, int(c), "") or (1, 0, c.lower()), and sort by (chunk_tuples, name).

Topic: Sorting, custom keys, coordinate compression. sorted(key=...), multi-key and stable sorts, cmp_to_key, compressing coordinates.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc