我的个人博客
更多内容,请跳转我的个人博客
题目
RGB To Hex Conversion
RGB到十六进制的转换
描述
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
rgb功能不完整。完成它,以便传入RGB十进制值将导致返回十六进制表示。RGB的有效十进制值为0-255。任何超出该范围的值都必须四舍五入到最接近的有效值。
注意:你的答案应该总是6个字符长,3的速记在这里不起作用。
例子
The following are examples of expected output values:
以下是预期输出值的示例:
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3
test.assert_equals(rgb(0,0,0),"000000", "testing zero values")
test.assert_equals(rgb(1,2,3),"010203", "testing near zero values")
test.assert_equals(rgb(255,255,255), "FFFFFF", "testing max values")
test.assert_equals(rgb(254,253,252), "FEFDFC", "testing near max values")
test.assert_equals(rgb(-20,275,125), "00FF7D", "testing out of range values")
思路
看到本题,觉得思路非常简单,不就是把十进制转换为十六进制不,然后把转换后的结果拼接成字符串即可,虽然确实是如此,但是当你真正写的时候,发现有很多坑,需要注意的地方很多
- 注意1:当你使用hex转换为十六进制,并且使用str变成字符串格式化,结果为"0xff",那么很明显’0x’不是我们想要的,需要切片
- 注意2:当我们传入的颜色为个位数的时候,转换之后的结果为"0x0",很明显这个格式是不符合的,结果要六个字符,这里需要补位"00"
- 注意3:当我们转换后是小写,但是我们需要的是大写,所以需要转换成大小,‘ff’->‘FF’
- 注意4:并不是都是两个字母组合,存在一个字母和一个数字的组合,所以需要判断,当我们转换大写的时候
- 注意5:因为对三个值的操作是一样的,写了一个新的函数,专门用来处理,这样这个标准整洁。
完整代码
def rgb(r, g, b):
# 组合成列表,用于后面的循环处理
rgb = [r,g,b]
# 保存结果
result = []
# 循环处理RGB,因为做法是一样的
for color in rgb:
switch_hex(result,color)
# 组合,返回
return "".join(result)
pass
def switch_hex(result,color):
# 判断边界,颜色只在0-255
if color < 0:
color = 0
elif color > 255:
color = 255
# 转换
color = str(hex(color))
# 切片,因为这里转换之后,前面两个是'0x',这个我们是不需要的
color = color[2:]
# 增加'0'补位,上面的转换之后,如果是个位数,那么转换后还是个位数,但是我们的格式始终是6个字符
if len(color) == 1:
color = '0' + color
# 因为python不支持字符串修改,需要一个临时变量
temp = ""
# 因为我们返回的结构是大写,但是转换后的结果是小写,所以要转换为大写,当然只要字母转换即可
for i in color:
if i.isalpha():
temp += i.upper()
else:
temp += i
# 最后添加到result中即可
result.append(temp)