Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created June 19, 2019 03:27
Show Gist options
  • Save Shaddyjr/d1b65ae54be369c5fb7d9813b094df39 to your computer and use it in GitHub Desktop.
Save Shaddyjr/d1b65ae54be369c5fb7d9813b094df39 to your computer and use it in GitHub Desktop.
def dirReduc(arr):
if(len(arr) <= 1): # short circuit
return arr
directions = {
"NORTH" : "SOUTH" ,
"SOUTH" : "NORTH" ,
"WEST" : "EAST" ,
"EAST" : "WEST"
}
output = []
i = 0
while(i < len(arr)):
move = arr[i]
try:
next_move = arr[i + 1]
except IndexError:
next_move = None
if (next_move == directions[move]):
i += 2
else:
output.append(move)
i += 1
if(len(output) == len(arr)): # base case of no redudant directions
return output
else:
return dirReduc(output) # recursive call
# testing - should return ["WEST"]
dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"])
# Oh, yeah! ["WEST"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment