Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
49 changes: 49 additions & 0 deletions data_structures/stacks/postfix_to_prefix_conversion.py
Original file line number Diff line number Diff line change
@@ -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.
Comment on lines +19 to +20

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Could you add checks in your code for these cases rather than relying on Stack's IndexError? That way we can have more useful error messages for this algorithm.
  2. Could you add a doctest that tests an invalid expression and a doctest that tests 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)
Loading