四则运算表达式由运算数(必定包含数字,可能包含正或负符号、小数点)、运算符(包括+、-、*、/)以及小括号((和))组成,每个运算数、运算符和括号都是一个token(标记)。现在,对于给定的一个四则运算表达式,请把她的每个token切分出来。题目保证给定的表达式是正确的,不需要做有效性检查。 输入格式: 在一行中给出长度不超过40个字符的表达式,其中没有空格,仅由上文中token的字符组成 输出格式: 依次输出表达式中的tokens,每个token占一行。
时间: 2024-02-21 17:02:18 浏览: 19
好的,你的问题是如何将一个四则运算表达式切分成每个token并输出?
这可以通过遍历字符串并判断每个字符所属的token类型来实现。
具体的做法是,使用一个字符串变量存储当前正在处理的token,然后遍历输入字符串中的每个字符。对于每个字符,判断其所属的token类型,如果类型发生变化,就输出当前的token并重新开始记录下一个token。
以下是一份Python代码实现:
```python
s = input() # 输入表达式
token_types = set(['+', '-', '*', '/', '(', ')']) # token类型集合
token = '' # 当前正在处理的token
for c in s:
if c in token_types: # 当前字符属于运算符或括号
if token: # 如果当前正在处理的token不为空
print(token) # 输出当前的token
print(c) # 输出当前的运算符或括号作为一个单独的token
token = '' # 重置token
else: # 当前字符属于数字或小数点
token += c # 将当前字符加入当前正在处理的token中
if token: # 最后一个token还未输出
print(token) # 输出最后一个token
```
这样,就能将输入的表达式切分成每个token并输出了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)