Skip to content

Fix bug in natural_sort_le#400

Merged
gkreitz merged 1 commit intoKattis:masterfrom
Matistjati:natural-sort-bug-fix
Apr 13, 2026
Merged

Fix bug in natural_sort_le#400
gkreitz merged 1 commit intoKattis:masterfrom
Matistjati:natural-sort-bug-fix

Conversation

@Matistjati
Copy link
Copy Markdown
Contributor

@Matistjati Matistjati commented Mar 22, 2026

The current version has a subtle bug:

if ord('0') <= ord(a[i]) <= ord('9') and ord('0') <= ord(b[i]) <= ord('9'):

Should almost certainly be

if ord('0') <= ord(a[i]) <= ord('9') and ord('0') <= ord(b[j]) <= ord('9'):

(The index for b)

The old version can crash

def natural_sort_le(a: str, b: str) -> bool:
    a += '\0'
    b += '\0'
    i = j = 0

    def parse_num(s: str, i: int) -> tuple[int, int]:
        ret = 0
        while ord('0') <= ord(s[i]) <= ord('9'):
            ret = ret * 10 + ord(s[i]) - ord('0')
            i += 1
        return ret, i

    while i < len(a) and j < len(b):
        if ord('0') <= ord(a[i]) <= ord('9') and ord('0') <= ord(b[i]) <= ord('9'):
            anum, i = parse_num(a, i)
            bnum, j = parse_num(b, j)
            if anum == bnum:
                continue
            return anum < bnum
        if a[i] == b[j]:
            i += 1
            j += 1
            continue
        return a[i] < b[j]
    return True

print(natural_sort_le('00a0', '0a'))

@gkreitz gkreitz merged commit 67f021c into Kattis:master Apr 13, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants