I am attempting solve this problem. In the problem am required to iterate over a list of directions (NORTH, SOUTH, EAST, WEST
) and discard any adjacent opposite directions (NORTH
and SOUTH
, EAST
and WEST
) to return a reduced array containing only non-redundant directions. When I iterate over a list that does not contain consecutive duplicates, such as ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
, my code works fine, but it breaks when I iterate over a list with consecutive duplicates, like ['EAST', 'EAST', 'WEST']
. Why is my code doing this, and how can I fix it to handle consecutive duplicates?
def dirReduc(arr):
for direction in arr[:-1]:
try:
gotdata = arr[arr.index(direction)+1]
except IndexError:
gotdata = 'null'
except ValueError:
gotdata = 'null'
if gotdata is 'null':
if arr == dirReduc(arr):
return arr
else:
return dirReduc(arr)
elif cancel_pair(direction, arr[arr.index(direction)+1]):
del arr[arr.index(direction):arr.index(direction)+2]
return arr
def cancel_pair(dir1, dir2):
if dir1 in ('NORTH') and dir2 in ('SOUTH') or dir1 in ('SOUTH') and dir2 in ('NORTH'):
return True
elif dir1 in ('WEST') and dir2 in ('EAST') or dir1 in ('EAST') and dir2 in ('WEST'):
return True
return False