繁体   English   中英

使用堆栈数据结构中缀表示法的 Python 前缀

[英]Python prefix to infix notation using a stack data structure

我有一个关于使用堆栈数据结构解决问题的分配问题。 提示我制作以下堆栈函数。

任务:使用您创建的堆栈,编写函数prefix_infix ,该函数接受前缀表达式(表示为列表)并以完全括号中的中缀表示法返回表达式。 考虑仅涉及二元运算符(+,-,*,/)表达式您可以在此处找到有关前缀的信息: http : //en.wikipedia.org/wiki/Polish_notation

def make_stack(): 
    stack=[]
    def helper(*args): 
        if args[0]=='push': 
            stack.append(args[1])
        elif args[0]=='peek': 
            return (stack[-1]) 
        elif args[0]=="pop": 
            return (stack.pop())
        elif args[0]=="size": 
            return (len(stack))
    return helper 



def prefix_infix(lst): 
    stk=make_stack() 
    def helper(lst):
        if type(lst)==int: 
            stk('push',str(lst))
        elif lst in ('+','-','*','/'): 
            left=stk('pop')
            right=stk('pop')
            element="("+left+" "+lst+" "+right+")"
            stk('push',element)
        else:
            return helper(lst[2]),helper(lst[1]),helper(lst[0]) 
    helper(lst)
    return stk('pop')

prefix_infix(['+',['*',5,4],['-',2,1]])
#Output: "((5 * 4) + (2 - 1))"

prefix_infix(['-',['*',5,4],['-',['/',1,45],['+',1,1]]])
#Output:((5 * 4) - ((1 / 45) - (1 + 1)))

我以某种方式让我的代码产生正确的输出,但我对我的方法不是很自信,因为我是用递归来做的,但我不知道用递归来做的正确方法是什么(我的递归调用,似乎随意)。 有人可以建议我可以编写一些其他版本的代码以使其更容易理解吗? 我无法真正想象堆栈,大多数时候我只是因为我的递归函数很幸运。

如果使用递归,则不必手动管理堆栈(递归为您管理堆栈)。 例如:

def prefix_infix(expression):
    if isinstance(expression, list):
        op, left, right = expression
        return '(' + prefix_infix(left) + op + prefix_infix(right) + ')'
    else:
        return str(expression)

print(prefix_infix(['+',['*',5,4],['-',2,1]]))
print(prefix_infix(['-',['*',5,4],['-',['/',1,45],['+',1,1]]]))

输出:

((5 * 4) + (2 - 1))
((5 * 4) - ((1 / 45) - (1 + 1)))

编辑(评论后):这是添加表达式数值计算的版本:

def eval_prefix(expression):
  return eval(prefix_infix(expression))

输出:

eval_prefix(['+',['*',5,4],['-',2,1]])) # --> 21
eval_prefix(['-',['*',5,4],['-',['//',9,3],['+',1,1]]])) # --> 19
def is_operand(c):
    return c.isdigit()

def prefix_to_infix(expression):
    stack = []
    for c in expression[::-1]:
        if is_operand(c):
            stack.append(c)
        else:
            o1=stack.pop()
            o2=stack.pop()
            if c== "+":
                element=   o1 + c + o2
                stack.append(element)
            if c=="-":
                element= o1 + c +o2 
                stack.append(element)
            if c== "*":
                element=  o1 + c +o2 
                stack.append(element)
    return stack
def evaluate(stack):
    expression=str(stack[0])
    return eval(expression) 
        

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM