I have a working program for a problem, but need to optimize it in a way where the processing time is less than 3 seconds. This is where I found the problem:
https://open.kattis.com/problems/battlesimulation
Condensed description of the problem:
The input is a string that represents a combination of attacks from a monster (R, B, and L).
The program checks the attacks and provides a counter move based on the letter ('S' to counter 'R', 'K' to counter 'B', and 'H' to counter 'L').
However, if the combination of attacks is in the list called Combos ("RBL", "RLB", "BLR", "BRL", "LBR", "LRB"), your counter is a 'C' as opposed to what it would have been.
Sample | Input | Output |
---|---|---|
1 | RRBBBLLR | SSKKKHHS |
2 | RBLBR | CKS |
This is my code so far:
attack = input()
combos = ("RBL", "RLB", "BLR", "BRL", "LBR", "LRB")
counterattack = {"R": "S", "B": "K", "L": "H"}
defense = ''
b = -1
for i in range(len(attack)):
if b-2 <= i <= b:
continue
if i < (len(attack)-2):
combo = attack[i] + attack[i+1] + attack[i+2]
if combo in combos:
defense += "C"
b = i+2
else:
defense += counterattack[attack[i]]
else:
defense += counterattack[attack[i]]
print(defense)
The b
is just so that the for loop skips two letters if there is a combo. I couldn't find a way to do it without that.
And this was my first attempt:
attack = input()
combos = {"RBL", "RLB", "BLR", "BRL", "LBR", "LRB"}
counterattack = {"R": "S", "B": "K", "L": "H"}
defense = ''
while len(attack) >= 3:
combo = attack[:3]
if combo in combos:
defense += "C"
attack = attack[3:]
else:
defense += counterattack[attack[0]]
attack = attack[1:]
for el in attack:
defense += counterattack[el]
print(defense)
Could the problem be that I put too many if statements? How else could I check for the combo in the input?