如何通过消除成对的连续互补方向,从给定的方向列表中 return 简化方向列表?

How to return the simplified direction list from a given direction list by eliminating pairs of consecutive complimentary directions?

我想 return 从给定方向列表中设置最简单的方向。因此,如果方向集有 "SOUTH" 后跟 "NORTH",反之亦然,它们应该相互抵消; "WEST" 后跟 "EAST" 相同,反之亦然。

因此,例如,如果给定的方向列表是 ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"],正确的输出应该是 return 简化列表 ['WEST']。我的逻辑是按以下方式进行:

我的实现代码如下:

arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]

while True:
    for i in range(len(arr)):
        try:
            len_old = len(arr)
            if ( ((arr[i]=='NORTH' and arr[i+1]=='SOUTH') or (arr[i]=='SOUTH' and arr[i+1]=='NORTH')) or
                 ((arr[i]=='EAST' and arr[i+1]=='WEST') or (arr[i]=='WEST' and arr[i+1]=='EAST')) ):
                arr.remove(arr[i])
                arr.remove(arr[i])
            len_new = len(arr)

            if len_new==len_old:
                break

        except:
            pass

arr

但问题是,它永远不会终止。当我手动强制代码停止并检查列表的值和列表的新旧长度时,它 return 是正确的值:

print(arr)
print(len_new)
print(len_old)
>>>
['WEST']
1
1

那么,代码有什么问题?为什么达到break条件还是不break,如何解决?

您的程序永远不会终止。外观没有任何终止条件。可能不会对所有输入都执行循环间终止。我重写了代码,它适用于提供的测试用例

def dirReduc(arr):

        if len(arr)<=1:

            return arr

        len_old = len(arr)
        arr = checkDirection(arr)
        len_new = len(arr)

        if len_new==len_old:
            return arr
        else:
            arr= dirReduc(arr)

        return arr


def checkDirection(arr):
        if len(arr)<=1:
            return arr
        for i in range(len(arr)-1):
            try:
                if ( ((arr[i]=='NORTH' and arr[i+1]=='SOUTH') or (arr[i]=='SOUTH' and arr[i+1]=='NORTH')) or
                     ((arr[i]=='EAST' and arr[i+1]=='WEST') or (arr[i]=='WEST' and arr[i+1]=='EAST')) ):
                    arr.remove(arr[i])
                    arr.remove(arr[i])
                    return arr
            except:
                print('Catching Except')
                return arr



    main_arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
    main_arr = dirReduc(main_arr)
    print('Final Result')
    print(main_arr)