diff --git a/DIRECTORY.md b/DIRECTORY.md index 150e4e61ea06..af8b9a34f497 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -350,6 +350,7 @@ * [Lexicographical Numbers](data_structures/stacks/lexicographical_numbers.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) + * [Postfix To Prefix Conversion](data_structures/stacks/postfix_to_prefix_conversion.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack Using Two Queues](data_structures/stacks/stack_using_two_queues.py) @@ -986,6 +987,7 @@ * [Doppler Frequency](physics/doppler_frequency.py) * [Escape Velocity](physics/escape_velocity.py) * [Grahams Law](physics/grahams_law.py) + * [Hamiltonian](physics/hamiltonian.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Hubble Parameter](physics/hubble_parameter.py) * [Ideal Gas Law](physics/ideal_gas_law.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)