TheAlgorithms/Python · error · ValueError

The elements inside the sequence must contains only {colors}

Error message

The elements inside the sequence must contains only {colors} values

What it means

Raised by dutch_national_flag_sort in sorts/dutch_national_flag_sort.py when the three-way partition loop encounters an element that is not one of the three sentinel values in colors = (0, 1, 2). DNF sort is a single-pass partition for exactly three distinct values (red=0, white=1, blue=2); any other value — 3, -1, 1.1, a character — falls into the else branch and raises ValueError. Empty and single-element sequences return early and never trigger it.

Source

Thrown at sorts/dutch_national_flag_sort.py:87

        return []
    if len(sequence) == 1:
        return list(sequence)
    low = 0
    high = len(sequence) - 1
    mid = 0
    while mid <= high:
        if sequence[mid] == colors[0]:
            sequence[low], sequence[mid] = sequence[mid], sequence[low]
            low += 1
            mid += 1
        elif sequence[mid] == colors[1]:
            mid += 1
        elif sequence[mid] == colors[2]:
            sequence[mid], sequence[high] = sequence[high], sequence[mid]
            high -= 1
        else:
            msg = f"The elements inside the sequence must contains only {colors} values"
            raise ValueError(msg)
    return sequence


if __name__ == "__main__":
    import doctest

    doctest.testmod()

    user_input = input("Enter numbers separated by commas:\n").strip()
    unsorted = [int(item.strip()) for item in user_input.split(",")]
    print(f"{dutch_national_flag_sort(unsorted)}")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Map your three categories to exactly 0, 1, 2 before sorting, then map back after.
  2. Sanitize input: if not set(sequence) <= {0, 1, 2}: raise/filter before calling.
  3. If more than three distinct values exist, use counting sort or a general comparison sort instead.

Example fix

# before
dutch_national_flag_sort(['red', 'blue', 'white'])  # ValueError

# after
rank = {'red': 0, 'white': 1, 'blue': 2}
rev = {v: k for k, v in rank.items()}
sorted_keys = dutch_national_flag_sort([rank[c] for c in colors_list])
sorted_colors = [rev[k] for k in sorted_keys]
Defensive patterns

Strategy: validation

Validate before calling

ALLOWED = {0, 1, 2}
if set(sequence) - ALLOWED:
    raise ValueError(f'values outside {ALLOWED}: {set(sequence) - ALLOWED}')
dutch_national_flag_sort(sequence)

Type guard

def is_dnf_sortable(seq) -> bool:
    return all(x in (0, 1, 2) for x in seq)

Try / catch

try:
    result = dutch_national_flag_sort(seq)
except ValueError as e:
    raise ValueError(f'not a 3-value sequence: {e}') from e

Prevention

When it happens

Trigger: dutch_national_flag_sort([3, 2, 3, 1, 3, 0, 3]); dutch_national_flag_sort([-1, 2, -1, 1]); dutch_national_flag_sort([1.1, 2, 1]); dutch_national_flag_sort('abacab') (string elements never equal 0/1/2).

Common situations: Using DNF sort as a general 3-value bucket sort on categorical data without mapping to 0/1/2; dirty datasets with out-of-range codes; the classic 'sort colors' (LeetCode 75) problem where input guarantees are violated.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/a35caf9c101e1ec3. Report an issue: GitHub.