【每日一题0717】RGB 转十六进制

:woman_mage:请编写一个函数,以便传入3个 RGB 十进制值,返回十六进制表示形式。RGB 的有效十进制值为数字0~255 ,超出该范围的任何值都必须舍入到最接近的有效值。

备注:返回值应该总是6个字符长。

题目难度:中等
题目来源:codewar

def rgb_to_hex(a, b, c):
    pass

assert rgb_to_hex(255, 255, 255) == "FFFFFF"
assert rgb_to_hex(255, 255, 300)== "FFFFFF"
assert rgb_to_hex(0, 0, 0) == "000000"
assert rgb_to_hex(148, 0, 211) == "9400D3"
def rgb_to_hex(a:int, b:int, c:int):
    """"""
    num = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
    hex = ["0","1","2","3","4","5","6","7","8","9",'A','B','C','D','E','F']
    map_hex = dict(zip(num,hex))
    map_rgb = list(map(lambda x:max(0,x),map(lambda x:min(255,x),[a,b,c])))
    result = ''
    for i in map_rgb:
        div,mod = divmod(i,16)
        result += map_hex[div]+map_hex[mod]
    return result

def rgb_to_hex(a, b, c):
    rgb_lst = list(map(lambda x: max(0, x), map(lambda x: min(255, x), [a, b, c])))
    ox_num = ''
    for i in rgb_lst:
        num = hex(i)[2:]
        if len(num) == 1:
            num = '0' + num
        ox_num = ox_num + num.upper()
    return ox_num


assert rgb_to_hex(255, 255, 255) == "FFFFFF"
assert rgb_to_hex(255, 255, 300) == "FFFFFF"
assert rgb_to_hex(0, 0, 0) == "000000"
assert rgb_to_hex(148, 0, 211) == "9400D3"

只能想到这了。。。

def rgb_to_hex(a,b,c):
    res=[]
    def translate(x):
        x = hex(x)[2:].upper()
        if len(x) == 1:
            x = '0' + x
        return str(x)
    for i in a,b,c:
        if i<0:
            i=0
            res.append(translate(i))
        elif i>255:
            i=255
            res.append(translate(i))
        else:
            res.append(translate(i))
    return ''.join(res)

assert rgb_to_hex(255, 255, 255) == "FFFFFF"
assert rgb_to_hex(255, 255, 300)== "FFFFFF"
assert rgb_to_hex(0, 0, 0) == "000000"
assert rgb_to_hex(148, 0, 211) == "9400D3"
关闭