提交到PTA,报错非零返回
请问需要怎么修改
x = 0
try:
while True:
x += 1
V = 1
F = 0
expression = input()
if expression == "":
break
else:
stack1 = []
stack2 = []
n1 = len(expression)
for i in range(n1):
if expression[i] == "V":
stack1.append(V)
elif expression[i] == "F":
stack1.append(F)
else:
stack1.append(expression[i])
while "!" in stack1:
n2 = len(stack1)
for i in range(n2):
if stack1[i] == "!":
if stack1[i+1] == "!":
stack1.pop(i)
stack1.pop(i)
break
elif stack1[i+1] == "(":
stack1[i] = "-"
else:
stack1[i+1] = int(not stack1[i+1])
stack1.pop(i)
break
for i in stack1:
if i == "(":
continue
elif i == ")":
x2 = stack2.pop()
op = stack2.pop()
if op == "&":
x1 = stack2.pop()
x3 = x1 and x2
stack2.append(x3)
elif op == "|":
x1 = stack2.pop()
x3 = x1 or x2
stack2.append(x3)
elif op == "-":
x3 = not x2
stack2.append(x3)
else:
stack2.append(i)
n3 = len(stack2)
for i in range(n3):
if stack2[i] == "-":
stack2[i + 1] = int(not stack2[i + 1])
else:
continue
if "-" in stack2:
stack2.pop(stack2.index("-"))
stack2.reverse()
while len(stack2) > 1:
x2 = stack2.pop()
op = stack2.pop()
if op == "&":
x1 = stack2.pop()
x3 = x1 and x2
stack2.append(x3)
elif op == "|":
x1 = stack2.pop()
x3 = x1 or x2
stack2.append(x3)
if stack2[0] == 1:
print("Expression {}: V".format(x))
elif stack2[0] == 0:
print("Expression {}: F".format(x))
else:
break
except EOFError:
pass
我的思路是:
先处理表达式中重复的操作符!,再对第一次化简的表达式进行栈入栈出的第二次化简运算,再将最后得到的最简表达式进行计算
!( F | F | V | ! ( F | V & F ) | ( F | V & F ) )
一二轮操作过后
_ F | F | V | _ F | F | F
在第二轮操作中,首先是你直接去除了左括号,但是你的操作却没有完全将这个式子算完,那在后面这个括号的优先级就消失了(答案就很难说了);其次,你的算bool式子的方向也错了,虽然说你每次只算一个,但是方向也应该从左至右
我没有修正你的思路后再去写一份,但是这里有我已经AC的大致思路
! | ( | or | & |
---|---|---|---|
F | V | F | V |
注:在我们使用栈这个数据结构来解决表达式相关问题时,一般是动态的,而不是说将所有的字符都入栈后再依次pop判断
粗浅的解释,可能也会有错误()
第二行 try后面的冒号,你这里用的是中文符号,改成英文半角试试。
非零返回一般提示的是语法错误
Mouth={
1:"Jan",
2:"Feb",
3:"Mar",
4:"Apr",
5:"May",
6:"Jun",
7:"Jul",
8:"Aug",
9:"Sept",
10:"Oct",
11:"Nov",
12:"Dec"
}
ans=int(input())
print(Mouth[ans])
打表输出