Program to get final position of moving animals when they stops in Python

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a string s that is representing the initial conditions of some animals. Each animal can take one of three values: L, indicates the animal moved to left. R, indicates the animal moved to right. @, indicates the animal is standing still. Animals moving on a direction will pick up other animals unless the animal receives a force from the opposite direction. Then, it will stand still. We have to find the orientation of each animal when the animal stop moving.

So, if the input is like s = "@@L@R@@@@L", then the output will be "LLL@RRRLLL"

To solve this, we will follow these steps −

• levels := a list of size same as s and fill with -1

• q := a double ended queue

• for idx is in range 0 to size of s, do

• if s[idx] is same as "R" or s[idx] is same as "L", then

• insert (idx, 0, s[idx]) at the end of q

• l := a new list of characters of s

• while q is not empty, do

• (idx, new_level, dir) := left element of q, and delete it from q

• if levels[idx] is same as -1, then

• levels[idx] := new_level

• l[idx] := dir

• if dir is same as "R" and idx + 1 < size of l , then

• insert (idx + 1, new_level + 1, dir) at the end of q

• otherwise when dir is same as "L" and idx - 1 >= 0, then

• insert (idx - 1, new_level + 1, dir) at the end of q

• otherwise when levels[idx] is same as new_level, then

• if l[idx] is not same as dir, then

• l[idx] := "@"

• return a string by joining elements of l

Example

Let us see the following implementation to get a better understanding −

Live Demo

from collections import deque
class Solution:
def solve(self, s):
levels = [-1 for i in s]
q = deque()
for idx in range(len(s)):
if s[idx] == "R" or s[idx] == "L":
q.append((idx, 0, s[idx]))
l = list(s)
while q:
idx, new_level, dir = q.popleft()
if levels[idx] == -1:
levels[idx] = new_level
l[idx] = dir
if dir == "R" and idx + 1 < len(l):
q.append((idx + 1, new_level + 1, dir))
elif dir == "L" and idx - 1 >= 0:
q.append((idx - 1, new_level + 1, dir))
elif levels[idx] == new_level:
if l[idx] != dir:
l[idx] = "@"
return "".join(l)
ob = Solution()
s = "@@L@R@@@@L"
print(ob.solve(s))

Input

"@@L@R@@@@L"

Output

LLL@RRRLLL
Updated on 22-Dec-2020 06:24:50