如何实现一种在数组中删除对的方法

2024-05-23 18:41:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在解决一个问题,需要删除字符串数组中的“对”(南北对和东西对)。我不确定如何在Python上解决这个问题

问题是:

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). (link to problem: https://www.codewars.com/kata/550f22f4d758534c1100025a)

一些测试输入和输出:

Input  : ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
Output : ["WEST"]

Input  : ["NORTH", "WEST", "SOUTH", "EAST"]
Output : ["NORTH", "WEST", "SOUTH", "EAST"]

第二组输入和输出对于任务没有多大意义。我最初的想法是使用堆栈,但现在我不确定如何使用它


Tags: of字符串aninputoutputfunction数组array
1条回答
网友
1楼 · 发布于 2024-05-23 18:41:55

一个简单的实现可以使用字典来定义相反的方向。处理列表时,如果当前方向与最后一个方向相反,请从输出中删除最后一个方向。否则,将新方向添加到列表中:

dirs = {'NORTH': 'SOUTH', 'SOUTH': 'NORTH', 'EAST': 'WEST', 'WEST': 'EAST'}

def dirReduc(input):
    output = []

    for dir in input:
        if output and output[-1] == dirs[dir]:
            output.pop()
        else:
            output.append(dir)

    return output

print(dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]))
print(dirReduc(["NORTH", "WEST", "SOUTH", "EAST"]))

相关问题 更多 >