Skip to content

Custom RGB To Hex Conversion with Python

The challenge

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(,,) # returns 000000 rgb(148, , 211) # returns 9400D3
Code language: Python (python)

Test cases

test.assert_equals(rgb(,,),"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")
Code language: Python (python)

The solution using Python

def rgb(r, g, b): # helper function def help(c): if c<: return if c>255: return 255 return c # make sure that values are within bounds r = help(r) g = help(g) b = help(b) # convert to hex # maintain 2 spaces each val = "%02x%02x%02x" % (r, g, b) # return UpperCase string return val.upper()
Code language: Python (python)

See also  Solving the "Catching Car Mileage Numbers" Challenge using Python
Tags:
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
anon
anon
1 year ago

Thanks

1
0
Would love your thoughts, please comment.x
()
x