diff --git a/DIRECTORY.md b/DIRECTORY.md index 2c6000c94ed4..ea2bd06b29c6 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -257,6 +257,7 @@ * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) + * [Postfix to Prefix Conversion](data_structures/stacks/postfix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) diff --git a/data_structures/stacks/postfix_to_prefix_conversion.py b/data_structures/stacks/postfix_to_prefix_conversion.py new file mode 100644 index 000000000000..16f6f26e6b36 --- /dev/null +++ b/data_structures/stacks/postfix_to_prefix_conversion.py @@ -0,0 +1,49 @@ +""" +Functions: +- postfix_to_prefix(expression): Converts a postfix expression to a prefix expression. +""" + +from .stack import Stack + + +def postfix_to_prefix(expression_str: str) -> str: + """ + Converts a postfix expression to a prefix expression. + + Args: + expression (str): A string representing a postfix expression. + + Returns: + str: A string representing the equivalent prefix expression. + + Raises: + IndexError: If the expression is invalid or contains an invalid operator. + + Example: + >>> postfix_to_prefix('23+5*') + '*+235' + """ + stack: Stack[str] = Stack() + operators = {"+", "-", "*", "/", "^"} + + for char in expression_str: + if char not in operators: + stack.push(char) + else: + operand1 = stack.pop() + operand2 = stack.pop() + stack.push(char + operand2 + operand1) + + return stack.pop() + + +if __name__ == "__main__": + from doctest import testmod + + testmod() + postfix_expression = "ab+c*" + + print("Postfix to infix demo\n") + print("Postfix expression:", postfix_expression) + prefix_expression = postfix_to_prefix(postfix_expression) + print("Prefix expression:", prefix_expression)