Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 缩短Python3中堆栈的使用时间_Python 3.x_Algorithm_Stack - Fatal编程技术网

Python 3.x 缩短Python3中堆栈的使用时间

Python 3.x 缩短Python3中堆栈的使用时间,python-3.x,algorithm,stack,Python 3.x,Algorithm,Stack,我正在处理一个编码问题 我已经写了一个解决方案 front = [] back = [] word = input() count = int(input()) for a in word: front.append(a) for i in range(count): command = input().split() if command[0] == "P": front.append(command[1]) elif command[0

我正在处理一个编码问题

我已经写了一个解决方案

front = []
back = []

word = input()
count = int(input())

for a in word:
    front.append(a)

for i in range(count):
    command = input().split()
    if command[0] == "P":
        front.append(command[1])
    elif command[0] == "L":
        if front:
            back.append(front.pop())
    elif command[0] == "D":
        if back:
            front.append(back.pop())
    else:
        if front:
            front.pop()

while (back):
    front.append(back.pop())

print(''.join(map(str, front)))
然而,当我提交时,我总是收到超时错误。
如何更改某些内容以在Python中更快地运行此代码?或者这是语言固有的问题?

让我们想象一下,您有一百万个字符和两百万个命令

  • 首先需要迭代一百万个字符,然后创建一个非常大的数组
  • 对于每个L和D操作,您需要弹出并按下。在本例中,您几乎执行了两百万次
  • 在edge情况下,当我们只进行L操作时,您必须迭代整个
    back
    并将其附加到
    front
  • 我打赌这3个案例都经过了测试

    您可以随时尝试使用deque加快性能

    但我建议不要使用列表。您只需操作
    word
    并记住当前光标所在的索引即可