<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def rgb2termhex(r: int, g: int, b: int) -> str: """ Convert an rgb value to the nearest hex value that matches a term code. The hex value will be one in `hex2term_map`. """

    incs = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]

    res = []
    parts = r, g, b
    for part in parts:
        if (part < 0) or (part > 255):
            raise ValueError(
                'Expecting 0-255 for RGB code, got: {!r}'.format(parts)
            )
        i = 0
        while i < len(incs) - 1:
            s, b = incs[i], incs[i + 1]  # smaller, bigger
            if s <= part <= b:
                s1 = abs(s - part)
                b1 = abs(b - part)
                if s1 < b1:
                    closest = s
                else:
                    closest = b
                res.append(closest)
                break
            i += 1

    # Convert back into nearest hex value.
    return rgb2hex(*res)