TheAlgorithms/Python · error · ValueError

The given input must be positive

Error message

The given input must be positive

What it means

Raised by gray_code when bit_count is negative. Gray code sequences are defined for a non-negative bit width; a negative width cannot generate a sequence, so it is rejected. Note: floats like 10.6 pass this guard and fail later with TypeError from the `<<` operator inside gray_code_sequence_string.

Source

Thrown at bit_manipulation/gray_code_sequence.py:38

    [0, 1]

    >>> gray_code(3)
    [0, 1, 3, 2, 6, 7, 5, 4]

    >>> gray_code(-1)
    Traceback (most recent call last):
        ...
    ValueError: The given input must be positive

    >>> gray_code(10.6)
    Traceback (most recent call last):
        ...
    TypeError: unsupported operand type(s) for <<: 'int' and 'float'
    """

    # bit count represents no. of bits in the gray code
    if bit_count < 0:
        raise ValueError("The given input must be positive")

    # get the generated string sequence
    sequence = gray_code_sequence_string(bit_count)
    #
    # convert them to integers
    for i in range(len(sequence)):
        sequence[i] = int(sequence[i], 2)

    return sequence


def gray_code_sequence_string(bit_count: int) -> list:
    """
    Will output the n-bit grey sequence as a
    string of bits

    >>> gray_code_sequence_string(2)
    ['00', '01', '11', '10']

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp or validate the computed width: only call gray_code when bit_count >= 0.
  2. Use max(0, bit_count) if an empty/zero-width result is acceptable for your use case.
  3. For float widths, int() the value first so you fail fast with this clear ValueError instead of the later operand TypeError.

Example fix

# before
gray_code(bits - offset)  # ValueError when offset > bits

# after
width = max(0, bits - offset)
gray_code(width)
Defensive patterns

Strategy: validation

Validate before calling

bit_count = int(bit_count)
if bit_count < 0:
    raise ValueError("bit_count must be non-negative")

Type guard

def is_non_negative_int(n: object) -> bool:
    return isinstance(n, int) and not isinstance(n, bool) and n >= 0

Prevention

When it happens

Trigger: Calling gray_code(-1) or any negative int. gray_code(10.6) does NOT raise this — it raises TypeError from `1 << bit_count` in the helper.

Common situations: Deriving the bit width from data (e.g., width = maxlen - k) that goes negative on degenerate input; passing a size parameter from user config without validation.

Related errors


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