Advertisement
Python253

infix_to_postfix_with_tests

May 15th, 2024
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.65 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: infix_to_postfix_with_tests.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script converts infix expressions to postfix expressions.
  10.    - It features an interactive menu that allows users to input their own infix expressions for conversion.
  11.    - Additionally, users can run a series of predefined test cases to verify the accuracy of the conversion function.
  12.  
  13. Functions:
  14.    - infix_to_postfix(infix_expression):
  15.      Converts an infix expression to a postfix expression.
  16.    - run_tests():
  17.      Runs a set of predefined test cases to verify the correctness of the conversion function.
  18.    - main():
  19.      Provides an interactive menu for the user to choose between entering their own infix expression or running predefined test cases.
  20.  
  21. Requirements:
  22.    - Python 3.x
  23.  
  24. Usage:
  25.    1. Run the script: python infix_to_postfix_with_tests.py
  26.    2. Follow the menu prompts:
  27.        - Choose option 1 to enter your own infix expression and get the postfix result.
  28.        - Choose option 2 to run predefined test cases and see the results.
  29.        - Choose option 3 to exit the script.
  30.  
  31. Additional Notes:
  32.    - The script handles basic arithmetic operators (+, -, *, /, ^) and parentheses.
  33.    - It includes error handling for mismatched parentheses in the input expression.
  34.    - The predefined test cases cover various scenarios to ensure the function works correctly.
  35. """
  36.  
  37. def infix_to_postfix(infix_expression):
  38.     """
  39.    Convert an infix expression to a postfix expression.
  40.    
  41.    Params:
  42.        infix_expression (str): Infix expression provided by the user.
  43.        
  44.    Returns:
  45.        str: Postfix expression converted from the infix one.
  46.    """
  47.     stack = []
  48.     postfix_expression = ""
  49.     for char in infix_expression:
  50.         if char.isalnum():  # If an operand, add to postfix expression
  51.             postfix_expression += char
  52.         elif char == '(':
  53.             stack.append(char)
  54.         elif char == ')':
  55.             while stack and stack[-1] != '(':
  56.                 postfix_expression += stack.pop()
  57.             if not stack:
  58.                 raise ValueError("\nMismatched parentheses!\n")
  59.             stack.pop()
  60.         else:
  61.             while stack and stack[-1] != '(' and priorities[char] <= priorities[stack[-1]]:
  62.                 postfix_expression += stack.pop()
  63.             stack.append(char)
  64.    
  65.     while stack:
  66.         top = stack.pop()
  67.         if top == '(' or top == ')':
  68.             raise ValueError("\nMismatched parentheses!\n")
  69.         postfix_expression += top
  70.  
  71.     return postfix_expression
  72.  
  73. # Set of operators and their priorities
  74. operators = set(["+", "-", "*", "/", "(", ")", "^"])
  75. priorities = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
  76.  
  77. # Function to run test cases (Option 2)
  78. def run_tests():
  79.     """
  80.    Run a series of predefined test cases to verify the correctness of the infix_to_postfix function.
  81.    """
  82.     test_cases = [
  83.         ("A+B", "AB+"),
  84.         ("A+B*C", "ABC*+"),
  85.         ("(A+B)*C", "AB+C*"),
  86.         ("A+B*(C^D-E)", "ABCD^E-*+"),
  87.         ("A+B-C", "AB+C-"),
  88.         ("((A+B)*C-(D-E))^(F+G)", "AB+C*DE--FG+^"),
  89.         ("A", "A"),
  90.         ("(A+B)*(C+D)", "AB+CD+*")
  91.     ]
  92.    
  93.     print("\nRunning test cases...\n")
  94.     for i, (infix, expected_postfix) in enumerate(test_cases):
  95.         try:
  96.             result = infix_to_postfix(infix)
  97.             assert result == expected_postfix, f"Test case {i+1} failed: expected {expected_postfix}, got {result}"
  98.             print(f"Test case {i+1} passed: {infix} -> {result}")
  99.         except AssertionError as e:
  100.             print(e)
  101.     print("\nAll test cases completed.\n")
  102.  
  103. def main():
  104.     """
  105.    Main function to provide an interactive menu for the user.
  106.    Allows the user to enter their own infix expression or run predefined test cases.
  107.    """
  108.     while True:
  109.         print("\nOptions Menu:\n")
  110.         print("1. Enter your own infix expression")
  111.         print("2. Run predefined test cases")
  112.         print("3. Exit")
  113.         choice = input("\nChoose an option (1/2/3): ")
  114.  
  115.         if choice == '1':
  116.             infix_expression = input("\nEnter infix expression: ").replace(" ", "")
  117.             try:
  118.                 postfix_expression = infix_to_postfix(infix_expression)
  119.                 print("\nPostfix expression:", postfix_expression)
  120.             except ValueError as ve:
  121.                 print("\nError:", ve)
  122.         elif choice == '2':
  123.             run_tests()
  124.         elif choice == '3':
  125.             break
  126.         else:
  127.             print("\nInvalid choice! Please choose again.\n")
  128.  
  129. if __name__ == "__main__":
  130.     main()
  131.  
  132.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement