Solving Codewars algorithm problems in python: rgb to hex form
The goal of this blog is to teach and explain python algorithm questions to both new and experienced python software developers.
Hey there! I’m the newbieprogrammer and my goal is to make sure that my readers understand the various python algorithms/ problems I solve. Feel free to check out my instagram @newbieprogrammer_ and make sure to give me a follow on there. You can also check my github for all sourcecode @newbieprogrammer.
For today’s problem, we will be solving the codewars algorithm problem: rgb to hex conversion. Before I continue, I would like to say that there are multiple ways to solve this problem as is programming. This solution I found to be most beginner friendly unlike the other solutions that use lambda expressions. Now that is out of the way, let us begin.
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
- CREATE A FUNCTION:
Obviously, for any problem that has to be solved when it comes to coding/programming/ writing algorithms, we either have to create a function or a class. For this problem, we will be naming our function “rgb”, that takes in three values r, g and b:
2. CREATE A HELPER FUNCTION:
Now within the “rgb” function, we are going to create the “helper” function, that accepts a singular value ( c ), and check if the numbers are within the constraints and we are going to pass the values into the function to check if they are within the constraints:
3. CONVERT THE VALUES TO HEXADECIMAL:
%02x%02x%02x encodes the color triple as an RGB string like "aaffee", where every 2 characters is one color channel in hexadecimal, using string formatting.
%x means "hex",
02 means field width of two, padded on the left by zero(s). Then we return the value in uppercases by calling the .upper() method.
Thank you for taking the time to read this post. I will be posting more solutions for multiple algorithms/programming questions from codewars to hackerrank periodically. Don’t forget to checkout my instagram @newbieprogrammer_