为什么第一个while循环条件为False仍会运行?

问题描述:

 这是Leetcode的第496题,

我知道代码不能通过是因为我没有改第十七行标志位isFound的值,

我想知道的是为什么 stack.length != 0 为 False 的情况下仍会进入循环,最后提示

pop from emptylist。

from Stack_FUO import Stack

def nextGreaterElement(nums1,nums2):
    stack = Stack()
    res = []
    temp = Stack()

    for num in nums2:
        stack.push(num)

    for num in nums1:
        isFound = False
        nextmax = -1
        while (stack.length != 0 and not isFound):
            top = stack.pop()
            if top > num:
                nextmax = top
            elif top == num:
                isFound = False
            temp.push(top)
        res.append(nextmax)
        while temp.length() != 0:
            stack.push(temp.pop())
    return res

nums1 = [4,1,2]
nums2 = [1,3,4,2]
print(nextGreaterElement(nums1,nums2))

以下是class Stack模块的代码:

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):      # 是否为空
        return self.items == []

    def push(self,item):    # 入栈
        self.items.append(item)

    def pop(self):          # 出栈
        return self.items.pop()

    def peek(self):         # 取栈顶
        if len(self.items) != 0:
            return self.items[-1]
        else:
            return None

    def clear(self):        # 清空栈
        self.items = []

    def length(self):       # 查看栈的长度
        return len(self.items)

以下是错误截图:

 

这啥稀奇古怪的错误啊?

你的循环条件stack.length后面没有加小括号。。。

正确格式为

stack.length        # 错误格式
stack.length()      # 正确格式

from Stack_FUO import Stack
 
def nextGreaterElement(nums1,nums2):
    stack = Stack()
    res = []
    temp = Stack()
 
    for num in nums2:
        stack.push(num)
 
    for num in nums1:
        isFound = False
        nextmax = -1
        while (stack.length() != 0 and not isFound):
            top = stack.pop()
            if top > num:
                nextmax = top
            elif top == num:
                isFound = True
            temp.push(top)
        res.append(nextmax)
        while temp.length() != 0:
            stack.push(temp.pop())
    return res
 
nums1 = [4,1,2]
nums2 = [1,3,4,2]
print(nextGreaterElement(nums1,nums2))