简体   繁体   English

Python for 循环迭代未完成,跳过步骤

[英]Python for loop iteration not completing, skipping steps

I got a 'wrong answer' error in my " queue from stack " algorithm when I expected it to work.当我期望它起作用时,我的“堆栈队列”算法中出现了“错误答案”错误。 For those not familiar with the algorithm, the solution requires two stacks of list type- a "push stack" and a 'pop stack', which is in effect a queue buffer that the push stack dumps itself into when the queue stack gets called and is empty.对于那些不熟悉该算法的人来说,该解决方案需要两个列表类型的堆栈——一个“推送堆栈”和一个“弹出堆栈”,它实际上是一个队列缓冲区,当队列堆栈被调用时,推送堆栈将自己转储到其中。是空的。 See if you can determine what's going on and where the problem is.看看您是否可以确定发生了什么以及问题出在哪里。

def pop(self):
    self.stack_to_push_to= [1,2] # sample hard coding
    self.queue_to_pop = [] # sample hard coding

    if self.queue_to_pop == 0: # trigger a dump to form a new queue buffer
        for _ in stack_to_push_to:
            self.queue_to_pop.append(self.stack_to_push_to.pop())
    print(self.queue_to_pop) # [2] but expected [2,1]

Too much was being done on the append line, clever and concise though it seemed to be. append 产品线做的太多了,虽然看起来很聪明和简洁。 When one pops from an iterable that is currently being iterated on, it confuses the count and python iterator process, or that's what I'm guessing is happening.当一个从当前正在迭代的迭代中弹出时,它会混淆计数和 python 迭代器进程,或者这就是我猜正在发生的事情。 A similar thing happens in excel when you delete rows while at the same time traversing down them (not up them though).类似的事情发生在 excel 中,当您删除行同时向下遍历它们(虽然不是向上)。 I just assumed Python would have been able to handle this on it's own somehow.我只是假设 Python 能够以某种方式自行处理。

Problematic code.有问题的代码。

if self.queue_to_pop == 0: # trigger a dump to form a new sub-queue
    for _ in stack_to_push_to:
        self.queue_to_pop.append(self.stack_incoming.pop()) #!!!!!!

The pop method served the interest of automatically working backwards, which I want, and I also thought it would save time and space complexity, but it ultimately didn't work and I found two alternatives that do. pop 方法有利于自动向后工作,这是我想要的,我还认为它可以节省时间和空间的复杂性,但它最终不起作用,我找到了两个替代方案。 I'd be interested in learning if there's a way to reduce the complexities of my solutions.我有兴趣了解是否有办法降低我的解决方案的复杂性。

Option 1:选项1:

    for i in range(len(self.stack_to_push_to)-1,-1,-1):
        self.queue_buffer.append(self.stack_to_push_to[i])
    self.stack_to_push_to = []

Option 2:选项 2:

    for _ in reversed(self.stack_to_push_to):
        self.queue_buffer.append(_)
    self.stack_to_push_to = []

I didn't see anyone else post this issue so I thought it was worth sharing and hope it enlightens others.我没有看到其他人发布此问题,因此我认为值得分享并希望它能启发其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM