… a man was given directions to go from one point to another. The directions were “NORTH”, “SOUTH”, “WEST”, “EAST”. Clearly “NORTH” and “SOUTH” are opposite, “WEST” and “EAST” too. Going to one direction and coming back the opposite direction is a needless effort. Since this is the wild west, with dreadfull weather and not much water, it's important to save yourself some energy, otherwise you might die of thirst!
How I crossed the desert the smart way.
The directions given to the man are, for example, the following:
["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
["WEST"]
In
["NORTH", "SOUTH", "EAST", "WEST"]
The path becomes
["EAST", "WEST"]
[]
In
["NORTH", "EAST", "WEST", "SOUTH", "WEST", "WEST"]
["WEST", "WEST"]
Write a function dirReduc which will take an array of strings and returns an array of strings with the needless directions removed (W<->E or S<->N side by side).
Notes
Not all paths can be made simpler. The path
["NORTH", "WEST", "SOUTH", "EAST"]
["NORTH", "WEST", "SOUTH", "EAST"]
Одно из решений такое:
opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'} def dirReduc(plan): new_plan = [] for d in plan: if new_plan and new_plan[-1] == opposite[d]: new_plan.pop() else: new_plan.append(d) return new_plan
Вопросы:
1. по условию удалять надо пары значений, а здесь удаляется одно. Почему это работает?
2. Сравнение двух элементов списка со словарем. Как это работает без перебора элементов?