Reputation: 59
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.
Upvotes: 0
Views: 80
Reputation: 6908
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.
Upvotes: 1
Reputation: 736
Your code its ok. I check it with the version 3.6.9
Upvotes: 1
Reputation: 43
I copied and pasted your code, it runs fine for me both on 3.9 and on a 3.6 online editor, not sure why you are getting a problem though.
My output for both is
0
1
2
3
4
Upvotes: 1