To solve the problem of setting the correct color on a broken switch that shifts colors cyclically (red → green, green → blue, blue → red), we need to determine the input color that will result in the desired output color after the error. The solution involves mapping each desired color to its corresponding input color by reversing the cyclic shift.
-
Problem Analysis: The switch has a consistent error where:
- Setting to red results in green.
- Setting to green results in blue.
- Setting to blue results in red.
-
Key Insight: To achieve a desired output color, we must set the switch to the color that precedes it in the cycle (red → green → blue → red). For example:
- To get red (output), set blue (input) because blue shifts to red.
- To get green (output), set red (input) because red shifts to green.
- To get blue (output), set green (input) because green shifts to blue.
-
Algorithm Selection: Use a dictionary to map each desired output color to its corresponding input color. This allows O(1) lookups for efficient color conversion.
Solution Code
def set_color(desired_color):
color_map = {
'red': 'blue',
'green': 'red',
'blue': 'green'
}
return color_map.get(desired_color, 'red')
Explanation
- Dictionary Mapping: The dictionary
color_mapdefines the input color needed for each desired output color:'red'→'blue'(setting blue results in red)'green'→'red'(setting red results in green)'blue'→'green'(setting green results in blue)
- Default Handling: If an invalid color is provided, the function defaults to returning
'red'as a safe fallback, though the problem assumes valid inputs. - Efficiency: The solution efficiently converts the desired color to the correct input color in constant time using dictionary lookup.
This approach ensures the switch displays the correct color by accounting for the cyclic shift error, providing a straightforward and optimal solution.
Request an On-site Audit / Inquiry