Skip to content
Advertisement

Python prefix to infix notation using a stack data structure

I have an assignment problem on using a stack data structure to solve problems. I am prompted to make the following stack function.

Task: Using the stack you created, write the function prefix_infix that takes in a prefix expression (represented as a list) and returns the expression in fully parenthesized infix notation. Consider expressions involving only binary operators(+,-,*,/) You may find information regarding prefix here: http://en.wikipedia.org/wiki/Polish_notation

JavaScript

I somehow got my code to produce the correct output, but I’m not very confident on my approach as I did it with a recursion but I do not know what’s the right way to do it with a recursion (my recursive call with , seems haphazard). Can someone suggest some other versions of code that I can write to make it easier to comprehend? I can’t really visualise the stack, most of the time I’m just lucky with my recursive functions.

Advertisement

Answer

If you use recursion, you don’t have to manage your stack manually (recursion manages the stack for you). For instance:

JavaScript

Output:

JavaScript

EDIT (after comment): Here is the version that adds numerical evaluation of the expression:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement