The rgb function is incomplete. Complete it so that passing in RGB decimal values will…
- User
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:
kata.rgb(255, 255, 255) -- returns FFFFFF kata.rgb(255, 255, 300) -- returns FFFFFF kata.rgb(0, 0, 0) -- returns 000000 kata.rgb(148, 0, 211) -- returns 9400D3
- Assistant
To solve this problem, we can follow these steps:
- Create a function named
rgbthat takes three arguments:r,g, andbrepresenting the red, green, and blue color values respectively. - Use the
minandmaxfunctions to ensure that each color value is within the valid range of 0-255. For example,r = min(255, max(0, r))will limitrto a value between 0 and 255. - Convert each color value to its hexadecimal representation using the
hexfunction and remove the0xprefix. - Pad each hexadecimal value with leading zeros if necessary using the
str.zfillmethod, specifying a width of 2. - Concatenate the three color values together and return the resulting string.
Here's the code that implements this logic:
def rgb(r, g, b): r = min(255, max(0, r)) g = min(255, max(0, g)) b = min(255, max(0, b)) return str(hex(r))[2:].zfill(2) + str(hex(g))[2:].zfill(2) + str(hex(b))[2:].zfill(2) # Examples: print(rgb(255, 255, 255)) # Output: FFFFFF print(rgb(255, 255, 300)) # Output: FFFFFF print(rgb(0, 0, 0)) # Output: 000000 print(rgb(148, 0, 211)) # Output: 9400D3 - Create a function named