python数字重排(用栈实现)

题目要求:
输入:两行,第一行为一列数字的长度 n,第二行为希望得到的新序列,该列表保证
长度为 n,由 1-n 组成。
输出:如果能得到另一种给定的排列,则输出两行,第一行为 Yes,第二行为由 01
串表示的入栈出栈操作顺序,0 表示入栈,1 表示出栈。如果不能,输出 No。
输入样例:
5
3 5 4 2 1
输出样例:
Yes
0001001111
问题:我的代码输出为No
代码:

n=int(input())
list2=map(int,input().split())
stack=[]
ans=''
num=0

for i in list2:
    if stack==[]:
        while  num<i:
           num+=1
           stack.append(num)
        c=num
        num=i
        while c>=1:
            ans=ans+'0'
            c-=1
        stack.pop()
        ans=ans+'1'
    else:
        if stack[-1]==i:
            stack.pop()
            ans=ans+'1'
        elif stack[-1]<i:
            d=num
            while  num<i:
                num+=1
                stack.append(num)
            c=num
            num=i
            while c>=1:
                ans=ans+'0'
                c-=1
            stack.pop()
            ans=ans+'1'
        else:
            break
if len(ans)==2*n:
    print('Yes\n',format(ans),sep='')
else:
    print('No')

麻烦帮忙看看问题在哪~该怎么改 感谢!


# -*- encoding: utf-8 -*-
"""
@File    :   test.py    

@Modify Time          @Version    @Description
------------          --------    -----------
2021/8/24 2:11 下午         1.0         None
"""

# import lib
n = int(input())
list2 = map(int, input().split())
stack = []
ans = ''
num = 0
for i in list2:
    print("i===", i)
    if stack == []:
        while num < i:
            num += 1
            stack.append(num)
        c = num
        num = i
        while c >= 1:
            ans = ans + '0'
            c -= 1
        stack.pop()
        ans = ans + '1'
    else:
        if stack[-1] == i:
            stack.pop()
            ans = ans + '1'
        elif stack[-1] < i:
            d = num
            while num < i:
                num += 1
                stack.append(num)
            c = d
            num = i
            while c > 1:
                ans = ans + '0'
                c -= 1
            stack.pop()
            ans = ans + '1'
        else:
            break
if len(ans) == 2 * n:
    print('Yes\n', format(ans), sep='')
else:
    print('No')