TheAlgorithms/Python · error · TypeError

perfect_cube_binary_search() only accepts integers

Error message

perfect_cube_binary_search() only accepts integers

What it means

perfect_cube_binary_search() in maths/perfect_cube.py checks whether an integer is a perfect cube using binary search over candidate cube roots. The function explicitly rejects any input that is not an int (isinstance(n, int) is False), raising TypeError before any math is done. This is a deliberate API contract: the binary-search midpoint arithmetic (// floor division, mid*mid*mid) assumes exact integers, and floats would silently give wrong answers. Note that even float values that are mathematically integral (e.g. 27.0) are rejected.

Source

Thrown at maths/perfect_cube.py:36

    Space complexity: O(1)

    >>> perfect_cube_binary_search(27)
    True
    >>> perfect_cube_binary_search(64)
    True
    >>> perfect_cube_binary_search(4)
    False
    >>> perfect_cube_binary_search("a")
    Traceback (most recent call last):
        ...
    TypeError: perfect_cube_binary_search() only accepts integers
    >>> perfect_cube_binary_search(0.1)
    Traceback (most recent call last):
        ...
    TypeError: perfect_cube_binary_search() only accepts integers
    """
    if not isinstance(n, int):
        raise TypeError("perfect_cube_binary_search() only accepts integers")
    if n < 0:
        n = -n
    left = 0
    right = n
    while left <= right:
        mid = left + (right - left) // 2
        if mid * mid * mid == n:
            return True
        elif mid * mid * mid < n:
            left = mid + 1
        else:
            right = mid - 1
    return False


if __name__ == "__main__":
    import doctest

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert the value to int before calling: perfect_cube_binary_search(int(n)) when you know n is integral.
  2. If the input may be non-numeric, validate/cast at the boundary (e.g. int(input().strip()) inside try/except ValueError) rather than letting the function raise.
  3. If float support is genuinely needed, use round/verify n == int(n) first and only then call the function.

Example fix

# before
perfect_cube_binary_search(float(value))  # TypeError

# after
perfect_cube_binary_search(int(value))
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(n, int) or isinstance(n, bool):
    raise TypeError(f"expected int, got {type(n).__name__}")
result = perfect_cube_binary_search(n)

Type guard

def is_strict_int(v) -> bool:
    return isinstance(v, int) and not isinstance(v, bool)

Prevention

When it happens

Trigger: Calling perfect_cube_binary_search('a'), perfect_cube_binary_search(0.1), perfect_cube_binary_search(27.0), or passing any value read from input()/JSON/config that has not been converted to int. bool inputs pass (bool is a subclass of int).

Common situations: Feeding unparsed user input or data from json.load (which yields floats for '27.0') into the function; refactoring code that previously used a float-tolerant cube check; passing numpy scalar types (np.int64 is not a Python int for isinstance purposes on some paths).

Related errors


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