I am trying to execute the following Python code:
arr = [3, 4, 1, 6, 2]
n = len(arr)
res = [1] * n
stack = [-1]
#left
for i in range(n):
print(i)
while len(stack) > 1 and arr[stack[-1]] < arr[i]:
stack.pop()
res[i] = i - stack[-1] - 1
stack.append(i)
Although I am not changing the value of i
inside the code it is printing as follows:
0
1
0
2
3
2
1
4
Any idea about why it is behaving like this? Python 3.6.9 is the compiler.
Edit: Adding screenshot as the reference.
CodePudding user response:
I copied and pasted your code, it runs fine for me both on 3.9 and on a
CodePudding user response:
I'm guessing you're running this interactively. What you're seeing is the return value of the stack.pop()
interleaved with your explicit print()
statements.
If you assign (and ignore) the return value of the pop, you'll get the output you expect.