算法similarRGB问题

本文介绍了一种寻找与给定RGB颜色最接近的16进制颜色组合的方法。通过枚举预定义的颜色集来找到距离给定颜色最近的组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In the following, every capital letter represents some hexadecimal digit from 0 to f.

The red-green-blue color “#AABBCC” can be written as “#ABC” in shorthand. For example, “#15c” is shorthand for the color “#1155cc”.

Now, say the similarity between two colors “#ABCDEF” and “#UVWXYZ” is -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2.

Given the color “#ABCDEF”, return a 7 character color that is most similar to #ABCDEF, and has a shorthand (that is, it can be represented as some “#XYZ”)


题目是从[‘00’,’11’,’22’,’33’,’44’,’55’,’66’,’77’,’88’,’99’,’aa’,’bb’,’cc’,’dd’,’ee’,’ff’]的颜色组合中找出RGB距离给出的颜色最近的,如果由多组输出一组即可,组数不多直接枚举即可。


class Solution:
    """
    @param color: the given color
    @return: a 7 character color that is most similar to the given color
    """
    def similarRGB(self, color):
        # Write your code here
        num1, num2, num3 = int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
        x,y,z = 0,0,0
        num=['00','11','22','33','44','55','66','77','88','99','aa','bb','cc','dd','ee','ff']
        sum =0
        for i in num:
            for j in num:
                for k in num:
                    tmp = (int(i,16)-num1)**2+(int(j,16)-num2)**2+(int(k,16)-num3)**2
                    if tmp > sum:
                        sum = tmp;
                        x,y,z = i, j ,k

        return '#' + x + y + z
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值