Hi, i was solving this coding problem ( https://www.codewars.com/kata/5a331ea7ee1aae8f24000175 ) which in short is about reducing a string composed of letters indicating colors 'R' ,'G', 'B' into a single letter with rules like : combining red and green gives blue so : 'R' + 'G' will be reduced to 'B' similarly , 'B' and 'G' give 'R' and so on.
my idea is to recursively reduce the string in each iteration by combing every two adjacent colors until it becomes a single letter and return it, but that doesnt seem to be optimal in terms of time since i cant pass the random tests in a short amount of time, my question is, how can i optimize this even further ? because to me, it seems that this is the best we can do.
here's the code :
def triangle(row):
color_lookup = {
('R', 'R'): 'R', ('R', 'G'): 'B', ('R', 'B'): 'G',
('G', 'R'): 'B', ('G', 'G'): 'G', ('G', 'B'): 'R',
('B', 'R'): 'G', ('B', 'G'): 'R', ('B', 'B'): 'B',
}
while len(row) > 1:
row = [color_lookup[row[i], row[i+1]] for i in range(len(row)-1)]
return row[0]
Thanks!