Skip to content

Commit 6a20de0

Browse files
committed
Fix natural_sort key comparison bug by normalizing numeric/text tokens to comparable tuples and add regression doctest
1 parent 6e03a48 commit 6a20de0

1 file changed

Lines changed: 9 additions & 2 deletions

File tree

‎sorts/natural_sort.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,17 @@ def natural_sort(input_list: list[str]) -> list[str]:
2222
['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
2323
>>> natural_sort(example2)
2424
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
25+
26+
>>> natural_sort(['a2', 'aB', 'a10'])
27+
['a2', 'a10', 'aB']
2528
"""
2629

27-
def alphanum_key(key):
28-
return [int(s) if s.isdigit() else s.lower() for s in re.split("([0-9]+)", key)]
30+
def alphanum_key(key: str):
31+
return [
32+
(0, int(part)) if part.isdigit() else (1, part.lower())
33+
for part in re.split(r"(\d+)", key)
34+
if part
35+
]
2936

3037
return sorted(input_list, key=alphanum_key)
3138

0 commit comments

Comments
 (0)