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.
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
題目理解:設計一函數將RGB的10進位制轉換為16進位值,且返還值需始終為6字符。
import math
def rgb(r, g, b):
lst = [r,g,b]
#直接按照十六進位的字符照順序建立成列表,使代表的『值』等於『索引』
hexadecimal_lst = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
reslut = ""
for num in lst:
#依據題目示例,將大於255的值視為255;將小於0的值視為0
if num > 255:
num = 255
elif num < 0:
num = 0
#將十進位值除以16並下向取整可得到十六進位值的第一位數
reslut += hexadecimal_lst[math.floor(num/16)]
#將十進位除以16之餘數為十六進位值的第二位數
reslut += hexadecimal_lst[num%16]
return reslut
其中import的math模組中,math.floor(num)會將代入數num向下取整數,即無條件捨去。
pi = 3.14159
print(math.floor(pi)) # 輸出: 3
print(type(math.floor(pi))) #輸出: <class 'int'>
另留意其輸出值會轉換為Int屬性。