Skip to content

Fix bug in natural_sort_le#400

Open
Matistjati wants to merge 1 commit intoKattis:masterfrom
Matistjati:natural-sort-bug-fix
Open

Fix bug in natural_sort_le#400
Matistjati wants to merge 1 commit intoKattis:masterfrom
Matistjati:natural-sort-bug-fix

Conversation

@Matistjati
Copy link
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'))

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.

1 participant