中缀转后缀表达式:如何实现运算符前后的正确空格分隔格式?
Hey there! Let's fix that postfix expression formatting issue you're running into.
The Root Problem
Your current output is missing spaces around operators—right now you have 11 11+ instead of 11 11 +, which breaks the desired spacing pattern. The core fix is to treat every element (operands like 11 and operators like +) as separate entities, then join them with single spaces.
How to Modify Your Code
Instead of building the postfix expression by directly concatenating strings (which leads to operators sticking to adjacent operands), use a list to store each element individually. Then, join the list with spaces at the end. Here's a concrete breakdown:
Replace string concatenation with a list:
- Initialize an empty list (e.g.,
postfix_elements = []in Python, or an equivalent array in your language) instead of an empty string. - When you parse a complete operand (like
11), add it as a separate item to the list. - When you pop an operator from your stack (like
+or*), add it as a separate item to the list.
- Initialize an empty list (e.g.,
Generate the final formatted string:
- Once all elements are in the list, join them using a single space as the separator. This automatically handles spacing between every element, no manual space tracking needed.
Example Code Snippet (Python)
If your original code looked something like this (the problematic version):
postfix_str = "" # When parsing an operand postfix_str += operand + " " # When popping an operator postfix_str += operator # No space added here causes the issue
Modify it to this:
postfix_elements = [] # When parsing an operand postfix_elements.append(operand) # When popping an operator postfix_elements.append(operator) # Generate the final formatted string postfix_str = ' '.join(postfix_elements)
For your example expression (11+11)*(11+11), the list will end up as ['11', '11', '+', '11', '11', '+', '*'], and joining with spaces gives you exactly the desired output: 11 11 + 11 11 + *.
Key Notes
- This approach avoids messy edge cases (like extra spaces at the start/end of the string) because
join()only adds spaces between elements. - Make sure you're already parsing multi-digit operands correctly (which you are, since your current output shows
11as a single unit)—this fix doesn't change that logic, just how you assemble the final string.
内容的提问来源于stack exchange,提问作者AaySquare

