前中后缀表达式转换代码
时间: 2023-10-08 21:14:43 浏览: 98
下面是将中缀表达式转换为前缀表达式的代码:
```python
def infix_to_prefix(expression):
# 定义运算符的优先级
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
stack = []
prefix = []
for char in reversed(expression):
if char.isalnum():
prefix.append(char)
elif char == ')':
stack.append(char)
elif char == '(':
while stack and stack[-1 != ')':
prefix.append(stack.pop())
stack.pop()
else:
while stack and precedence[char < precedence.get(stack[-1], 0):
prefix.append(stack.pop())
stack.append(char)
while stack:
prefix.append(stack.pop())
return ''.join(reversed(prefix))
expression = "(A*(B-C/D))*E"
prefix_expression = infix_to_prefix(expression)
print("前缀表达式:", prefix_expression)
```
下面是将中缀表达式转换为后缀表达式的代码:
```python
def infix_to_postfix(expression):
# 定义运算符的优先级
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
stack = []
postfix = []
for char in expression:
if char.isalnum():
postfix.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1 != '(':
postfix.append(stack.pop())
stack.pop()
else:
while stack and precedence[char <= precedence.get(stack[-1], 0):
postfix.append(stack.pop())
stack.append(char)
while stack:
postfix.append(stack.pop())
return ''.join(postfix)
expression = "(A*(B-C/D))*E"
postfix_expression = infix_to_postfix(expression)
print("后缀表达式:", postfix_expression)
```
希望以上代码能够帮到你!<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [中缀表达式,前缀表达式,后缀表达式之间的相互转换和代码表示](https://blog.csdn.net/FYSGXFZ/article/details/100620836)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [前缀、中缀和后缀表达式详解,中缀表达式到后缀表达式的转换规则,以及后缀表达式的计算规则,附计算代码](https://blog.csdn.net/yldmkx/article/details/109537911)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文