85.1k views
1 vote
You are given directions to drive from a source to a destination. The directions are a combination of "East", "West", "South", and "North".

Obviously, driving to one direction and driving back in the opposite direction is a waste of time.
So you want to eliminate the useless steps so that you have only the necessary directions to the destination.
Write a function simplify that takes a list of directions and returns the simplified version of it.
>> simplify (["NORTH", "EAST" ])
['NORTH', 'EAST']
>> simplify (["NORTH", "EAST", "SOUTH", "SOUTH", "WEST"])
['SOUTH']
>> simplify (["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"])
['WEST']
>> simplify (["NORTH", "SOUTH", "SOUTH", "EAST", "NORTH", "WEST", "NORTH", "WEST"])
['NORTH', 'WEST']
>> simplify (["NORTH", "EAST", "SOUTH", "WEST"])

User Lulzim
by
8.5k points

1 Answer

1 vote

Final answer:

The simplify function helps to optimize a route made of compass directions by removing opposite and therefore redundant steps. The functionality can be understood by treating directions as vectors where opposite vectors cancel each other out. Example code in Python is provided to demonstrate this simplification process.

Step-by-step explanation:

The student is seeking assistance in writing a function called simplify that optimizes a list of compass directions by removing any redundant steps, resulting in a more efficient route. This scenario involves understanding how to manipulate lists and apply logic to reduce unnecessary steps. The compass directions of North, South, East, and West can be thought of as vectors, and opposites cancel each other out. To simplify a route, we must ensure that for every 'North' direction, a 'South' direction is removed, and similarly, each 'East' direction should be balanced by a 'West' direction.

For example, if the function receives the directions ["NORTH", "EAST", "SOUTH", "WEST"], the output should be an empty list since each direction is cancelled out by its opposite. However, exceptions exist when a certain direction is more predominant than its opposite - in such cases, only the predominant direction would remain in the output.

Example Code in Python

def simplify(directions):
opposite = {'NORTH': 'SOUTH', 'SOUTH': 'NORTH', 'EAST': 'WEST', 'WEST': 'EAST'}
result = []
for direction in directions:
if result and result[-1] == opposite[direction]:
result.pop()
else:
result.append(direction)
return result

User Travis Weber
by
8.0k points