簡體   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