Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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 此代码中的堆栈是否声明为空列表?我对此有问题 def nextGreater(数组,n,可索引): 堆栈=列表() 温度=[0]*n 对于范围(n-1,-1,-1)内的i: while(len(stack)>0和stack[-1]_Python_Python 3.x_Pycharm - Fatal编程技术网

Python 此代码中的堆栈是否声明为空列表?我对此有问题 def nextGreater(数组,n,可索引): 堆栈=列表() 温度=[0]*n 对于范围(n-1,-1,-1)内的i: while(len(stack)>0和stack[-1]

Python 此代码中的堆栈是否声明为空列表?我对此有问题 def nextGreater(数组,n,可索引): 堆栈=列表() 温度=[0]*n 对于范围(n-1,-1,-1)内的i: while(len(stack)>0和stack[-1],python,python-3.x,pycharm,Python,Python 3.x,Pycharm,while循环位于for循环内,但stack在for循环之前定义 第一次运行for循环时,stack将为空,而while将被完全跳过,这是正确的。在第一次迭代结束时,stack将被追加。因此,通过for循环的下一次迭代中,while循环可能不会被跳过d、 取决于堆栈和数组的内容 您可以通过在for循环的开头放一个print语句,并打印stack的内容来测试这一点。您会看到它并不总是空的。如果不输入while循环,那么代码应该给出错误,但代码正常工作会让人困惑 def nextGreate

while循环位于
for
循环内,但
stack
在for循环之前定义

第一次运行
for
循环时,
stack
将为空,而
while
将被完全跳过,这是正确的。在第一次迭代结束时,
stack
将被追加。因此,通过
for
循环的下一次迭代中,
while
循环可能不会被跳过d、 取决于
堆栈
数组
的内容


您可以通过在for循环的开头放一个
print
语句,并打印
stack
的内容来测试这一点。您会看到它并不总是空的。

如果不输入while循环,那么代码应该给出错误,但代码正常工作会让人困惑
    def nextGreater(array, n, indexTable):
       stack = list()
        temp = [0]*n
        for i in range(n - 1, -1, -1):
            while (len(stack) > 0 and stack[-1] <= array[i]):
                stack.pop()
            if (len(stack) == 0):
                temp[i] = -1
            else:
                temp[i] = stack[-1]
            stack.append(array[i])
        for i in range(int(n/2)):
            if temp[i] == -1:
                print(temp[i])
            else:
                print(indexTable[temp[i]])
    height =  [175, 166, 184, 170, 187, 167]
    array = []
    for i in range(len(height)*2):
       array.append(height[i % len(height)])
       indexTable = {}
    for i in range(int(len(array)/2)):
       indexTable[array[i]] = i
    n = len(array)
    nextGreater(array, n, indexTable)