LC.800. Similar RGB Color

LC.800. Similar RGB Color_第1张图片

class Solution(object):
    def similarRGB(self, color):
        """
        :type color: str
        :rtype: str
        """
        def hex2dec(ab):
            def helper(char):
                if ord('0') <= ord(char) <= ord('9'):
                    return ord(char) - ord('0')
                return ord(char) - ord("a") + 10
            return 16 * helper(ab[0]) + helper(ab[1])

        def dec2hex(number):
            if 0 <= number <= 9:
                return chr(number + 48)
            return chr(number - 10 + ord("a"))

        def getmin(ab):
            array = [(hex2dec(dec2hex(i)*2) - hex2dec(ab)) **2  for i in range(16)]
            index = array.index(min(array))
            return dec2hex(index)


        color = color[1:]
        res = []
        for i in range(0, len(color), 2):
            res.append(getmin(color[i:i+2]))
        result = "#"
        for char in res:
            result += char * 2
        return result

你可能感兴趣的:(LeetCode)