【发布时间】:2021-12-16 16:30:39
【问题描述】:
try:
def variables():
OPERATORS = set(['+', '-', '*', '/', '(', ')', '^'])
PRIORITY = {'+':1, '-':1, '*':2, '/':2, '^':3}
def formula1(expression):
variables()
stack = []
output = ''
for ch in expression:
if ch not in OPERATORS:
output+= ch
elif ch=='(':
stack.append('(')
elif ch==')':
while stack and stack[-1]!= '(':
output+=stack.pop()
stack.pop()
else:
while stack and stack[-1]!='(' and PRIORITY[ch]<=PRIORITY[stack[-1]]:
output+=stack.pop()
stack.append(ch)
while stack:
output+=stack.pop()
return output
expression = input('Enter infix expression: ')
print('infix expression: ',expression)
print('postfix expression: ',formula1(expression))
except Exception as e:
print (e)
示例输出:
输入中缀表达式:(a+b)
中缀表达式:(a+b)
名称“操作员”未定义
[程序结束]
我想调用函数变量的全部内容。我的任务是用 2 个函数对后缀做一个中缀。但我之前所做的只是 1 个功能,它工作正常。我想让它成为 2 个功能,但出现错误,我不知道如何修复它。
【问题讨论】:
-
您可以将这些变量保留为全局变量对吗?
-
将它们设为全局变量。
-
摆脱这个
def variables(): -
JacksonB 先生,我的任务是使用该程序创建 2 个函数 :( 这就是为什么我创建了 2 个函数,但是如何创建?是否可以在这 2 个函数中执行附加或弹出操作?
-
@MarkPauloCruz,我已经编辑了我的答案,你问我是否可以使用两个功能。如果您想使用两个功能,那么您可以尝试。