A certain robot can perform only 4 types of movement. It can move either up or down or left or right. These movements are represented by ’U’, ’D’, ’L’, ’R’. Assume all these movements to be of unit distance. Write a function named theRoundTrip that takes all the movements the robot made in a day as input and output True of bool type if the robot returned to its starting position after its journey. Otherwise return False. If the input is bad print the message "bad input" and return to solve the next question.

Have a main function from which the answer to questions are retrieved and run the program as a whole.

Examples:
Test Case 1:
input: movement = [’U’, ’L’, ’D’, ’R’]
output: True
Explanation: In a 2D plane a unit movement up by 1, left by 1, down by 1 and right by 1 would result in arriving at the starting posistion. So we return True.

Test Case 2:
input: movement = [’U’, ’U’, ’R’, ’L’, ’D’, ’R’]
output: False
Explanation: After traversing this movement we see that we have not arrived at the start- ing position. So we return False.

Test Case 3:
input: movement = [’U’, ’U’, ’I’, ’L’, ’D’, ’R’] output: bad input

Respuesta :

Answer:

Explanation:

Let's do this in python 3. The logic is simple, we begin by counting the number of each of the command and compare them. If the number of Up (U) commands is the same as the number of Down (D) command AND the number of Left (L) command is the same as the number of Right (R) command, then return True, otherwise return false.

def theRoundTrip(movements):

    up_count = movements.count('U')

    down_count = movements.count('D')

    left_count = movements.count('L')

    right_count = movements.count('R')

    move_count = len(movements)

    if up_count + down_count + left_count + right_count < move_count:

         # check if there are anything other than 'UDLW', if true, then print bad input

         print('bad input')

         return false

    else:

         return (up_count == down_count) and (left_count == right_count)

ACCESS MORE