Security Alarm
Note: This page contains a small but interesting piece of Python code which I call snippets. You can find more such codes on my Python snippets page.
Contents
Problem ¶
You are in charge of security at a casino, and there is a thief who is trying to steal the casino's money! Look over the security diagrams to make sure that you always have a guard between the thief and the money! There is one money location, one thief, and any number of guards on each floor of the casino.
Task:
Evaluate a given floor of the casino to determine if there is a guard between the money and the thief, if there is not, you will sound an alarm.
Input Format:
A string of characters that includes $ (money), T (thief), and G (guard), that represents the layout of the casino floor.
Space on the casino floor that is not occupied by either money, the thief, or a guard is represented by the character x.
Output Format:
A string that says 'ALARM' if the money is in danger or 'quiet' if the money is safe.
Sample Input:
xxxGxxGxx$xxxTG
Sample Output:
ALARM
Solution ¶
Here is my solution to the above problem. Remember that there could be more than one way to solve a problem. If you have a more efficient or concise solution, please leave a comment.
i=input().replace('x','')
if abs(i.index('$')-i.index('T'))==1:
print('ALARM')
else:
print('quiet')
Explanation ¶
My approach (or the algorithm)¶
- Remove the noise in the data. We are only interested in the floors with \$ (money), T (thief), and G (guard). Delete all "x".
- If there is no G between \$ and T then \$ and T will be adjacent to each other. The distance between the two will be 1. If so, then sound alarm, else quiet.
The code¶
-
replace('x','')
remove unnecessary data (all "x"s). -
abs(i.index('$')-i.index('T'))
distance between \$ and T.
The problem question is picked from SoloLearn. Here is my SoloLearn code and my SoloLearn profile page.
Last updated 2021-01-09 22:02:23.522813 IST
Comments