Train Collision T69987


Statement
 

pdf   zip   main.py

We represent with a string str composed only of the characters ’+’ and ’=’ the displacements of a train moving to the right. Similarly, we represent with a str composed only of ’-’ and ’=’ the displacements of a train moving to the left.

The character ’+’ means that the train moves one position to the right during that second; the character ’=’ means that the train remains stationary that second; and the character ’-’ indicates that the train moves one position to the left.

Design a function choque(m1: str, m2: str, d: int) -> int that, given the displacement m1 of a train moving to the right, the displacement m2 of another train moving to the left, with m1 and m2 having the same length, and an initial distance d > 0 indicating the initial separation between the two trains, returns the number of seconds until they collide. If they do not collide, the function must return 0.

It is understood that the trains collide at an instant if, after applying the displacements corresponding to that second, the distance between them becomes less than 0. If they are at zero distance, they have not collided yet; they will collide when one of the two moves and reduces the distance.

The trains do not move backward, that is, the train on the right never moves to the left, and the train on the left never moves to the right.

You may use functions such as zip or range to solve the problem.

Sample session

Sample session
>>> choque('+=====+++++++', '-=====-=========', 3)
7
>>> choque('==+=++++=======', '-----=========', 10)
0
>>> choque('+++', '---', 6)
0
>>> choque('++++', '----', 6)
4
Information
Author
infbesos
Language
English
Translator
infbesos
Original language
Spanish
Other languages
Catalan Spanish
Official solutions
Python
User solutions
Python