Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: infix_to_postfix_with_tests.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This script converts infix expressions to postfix expressions.
- - It features an interactive menu that allows users to input their own infix expressions for conversion.
- - Additionally, users can run a series of predefined test cases to verify the accuracy of the conversion function.
- Functions:
- - infix_to_postfix(infix_expression):
- Converts an infix expression to a postfix expression.
- - run_tests():
- Runs a set of predefined test cases to verify the correctness of the conversion function.
- - main():
- Provides an interactive menu for the user to choose between entering their own infix expression or running predefined test cases.
- Requirements:
- - Python 3.x
- Usage:
- 1. Run the script: python infix_to_postfix_with_tests.py
- 2. Follow the menu prompts:
- - Choose option 1 to enter your own infix expression and get the postfix result.
- - Choose option 2 to run predefined test cases and see the results.
- - Choose option 3 to exit the script.
- Additional Notes:
- - The script handles basic arithmetic operators (+, -, *, /, ^) and parentheses.
- - It includes error handling for mismatched parentheses in the input expression.
- - The predefined test cases cover various scenarios to ensure the function works correctly.
- """
- def infix_to_postfix(infix_expression):
- """
- Convert an infix expression to a postfix expression.
- Params:
- infix_expression (str): Infix expression provided by the user.
- Returns:
- str: Postfix expression converted from the infix one.
- """
- stack = []
- postfix_expression = ""
- for char in infix_expression:
- if char.isalnum(): # If an operand, add to postfix expression
- postfix_expression += char
- elif char == '(':
- stack.append(char)
- elif char == ')':
- while stack and stack[-1] != '(':
- postfix_expression += stack.pop()
- if not stack:
- raise ValueError("\nMismatched parentheses!\n")
- stack.pop()
- else:
- while stack and stack[-1] != '(' and priorities[char] <= priorities[stack[-1]]:
- postfix_expression += stack.pop()
- stack.append(char)
- while stack:
- top = stack.pop()
- if top == '(' or top == ')':
- raise ValueError("\nMismatched parentheses!\n")
- postfix_expression += top
- return postfix_expression
- # Set of operators and their priorities
- operators = set(["+", "-", "*", "/", "(", ")", "^"])
- priorities = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
- # Function to run test cases (Option 2)
- def run_tests():
- """
- Run a series of predefined test cases to verify the correctness of the infix_to_postfix function.
- """
- test_cases = [
- ("A+B", "AB+"),
- ("A+B*C", "ABC*+"),
- ("(A+B)*C", "AB+C*"),
- ("A+B*(C^D-E)", "ABCD^E-*+"),
- ("A+B-C", "AB+C-"),
- ("((A+B)*C-(D-E))^(F+G)", "AB+C*DE--FG+^"),
- ("A", "A"),
- ("(A+B)*(C+D)", "AB+CD+*")
- ]
- print("\nRunning test cases...\n")
- for i, (infix, expected_postfix) in enumerate(test_cases):
- try:
- result = infix_to_postfix(infix)
- assert result == expected_postfix, f"Test case {i+1} failed: expected {expected_postfix}, got {result}"
- print(f"Test case {i+1} passed: {infix} -> {result}")
- except AssertionError as e:
- print(e)
- print("\nAll test cases completed.\n")
- def main():
- """
- Main function to provide an interactive menu for the user.
- Allows the user to enter their own infix expression or run predefined test cases.
- """
- while True:
- print("\nOptions Menu:\n")
- print("1. Enter your own infix expression")
- print("2. Run predefined test cases")
- print("3. Exit")
- choice = input("\nChoose an option (1/2/3): ")
- if choice == '1':
- infix_expression = input("\nEnter infix expression: ").replace(" ", "")
- try:
- postfix_expression = infix_to_postfix(infix_expression)
- print("\nPostfix expression:", postfix_expression)
- except ValueError as ve:
- print("\nError:", ve)
- elif choice == '2':
- run_tests()
- elif choice == '3':
- break
- else:
- print("\nInvalid choice! Please choose again.\n")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement