Lintcode 1017. Similar RGB Color (Easy) (Python)

1017. Similar RGB Color

Description:

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”)

Example
Input: color = “#09f166”
Output: “#11ee66”
Explanation:
The similarity is -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73.
This is the highest among any shorthand color.

Code:

这题答题系统有问题,怎么回答都对

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
        a = ['0', '1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
        string = '#'
        for i in range(1,6,2):
            if color[i] == color[i+1]:
                string += color[i] + color[i]
            elif a.index(color[i]) - a.index(color[i+1]) > 0:
                if a.index(color[i]) - a.index(color[i+1]) > 8:
                    string += a[a.index(color[i])-1] + a[a.index(color[i])-1]
                else:
                    string += color[i] + color[i]
            else:

                if a.index(color[i+1]) - a.index(color[i]) > 8:
                    string += a[a.index(color[i])+1] + a[a.index(color[i])+1]
                else:
                    string += color[i] + color[i]
        return string

你可能感兴趣的:(Lintcode 1017. Similar RGB Color (Easy) (Python))