0
a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]

def dirReduc(arr):
index = int(0)
for i in arr:
    for j in arr:
        if (len(arr[index]) == len(arr[index + 1])) and (arr[index] != arr[index + 1]):
            arr.pop(index)
            arr.pop(index)
            index = 0
        else:
            index += 1
    print(arr)


dirReduc(a)

The purpose of this code is to reduce opposite directions which are next to each other. While my pycharm giving me correct output without any errors which is:

arr = ["WEST"]

At codewars website where it should compile i'm passing all test but the site giving me:

IndexError: list index out of range

Any simple way to handle that error to make it work at codewars?

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
Aaken00
  • 11
  • 2

1 Answers1

0

Instead of kicking out another way of doing this is to assemble a new array while traversing the original array:

a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
opposite = {"NORTH": "SOUTH", "SOUTH": "NORTH", "WEST": "EAST", "EAST":"WEST"}

def dirReduc(arr):
    if not arr:
        return []
    b=[]
    i = 0
    while i < len(arr):
        if i == len(arr)-1:
            b = b+[arr[i]]
            break
        else:
            if arr[i+1] == opposite[arr[i]]:
                i = i+2
            else:
                b=b+[arr[i]]
                i = i+1
    return b


reduced_a = a
while True:
    reduced_b = dirReduc(reduced_a)
    if reduced_b == reduced_a:
        reduced_a = reduced_b
        break
    else:
        reduced_a = reduced_b

print(dirReduc(reduced_b))
piiipmatz
  • 400
  • 1
  • 10