113 lines
2.9 KiB
Markdown
113 lines
2.9 KiB
Markdown
# 计算器
|
||
|
||
## 需求
|
||
|
||
- 编写一个简单的计算器,在数组中存入算式字符串,然后在新的数组中计算得到答案
|
||
- 例如,有个数组是`["5 + 3", "6 * 2", "12 / 3", "100 - 55"]`
|
||
- 得到的输出是`[8, 12, 4, 45]`
|
||
|
||
## 参考代码
|
||
|
||
```python
|
||
# 示例输入
|
||
expressions = ["5 + 3", "6 * 2", "12 / 3", "100 - 55"]
|
||
|
||
# 创建一个新的数组,用来存储计算结果
|
||
results = []
|
||
|
||
# 遍历数组
|
||
for i in expressions:
|
||
# 将算式的两个数字取出
|
||
a = int(i.split(" ")[0])
|
||
b = int(i.split(" ")[-1])
|
||
# 判断需要使用什么运算
|
||
if i.count("+"):
|
||
results.append(a + b)
|
||
elif i.count("-"):
|
||
results.append(a - b)
|
||
elif i.count("*"):
|
||
results.append(a * b)
|
||
elif i.count("/"):
|
||
results.append(a / b)
|
||
|
||
print(results)
|
||
```
|
||
|
||
## 扩展学习
|
||
|
||
- 貌似下面的代码更加合适,想办法去搞懂吧
|
||
|
||
```python
|
||
# 示例输入
|
||
expressions = ["5 + 3", "6 * 2", "12 / 3", "100 - 55"]
|
||
|
||
# 创建一个新的数组,用来存储计算结果
|
||
results = []
|
||
|
||
# 遍历算式数组,使用 eval() 计算每个算式的结果
|
||
for expr in expressions:
|
||
result = eval(expr) # 计算表达式的值
|
||
results.append(result) # 将结果添加到结果数组中
|
||
|
||
print(results)
|
||
```
|
||
|
||
|
||
|
||
> <span style="color: red; background: yellow; padding: 2px 5px; font-size: 22px;">作业2.1提交的内容</span>
|
||
>
|
||
> - 程序运行成功的截图,单独发送给组长
|
||
|
||
|
||
|
||
# 词频统计
|
||
|
||
## 需求
|
||
|
||
- 编写一个词频统计程序,给定一个英文字符串,然后统计每个单词出现次数,并且存入一个字典中(暂不要求排序和截取)
|
||
- 例如:`Python is a powerful programming language. Python is widely used for web development, data analysis, artificial intelligence, and scientific computing. Python is simple yet versatile.`
|
||
- 输出:`{'python': 3, 'is': 3, 'a': 1, 'powerful': 1, 'programming': 1}`
|
||
|
||
## 参考代码
|
||
|
||
```python
|
||
# 示例字符串
|
||
text = """
|
||
Python is a powerful programming language. Python is widely used for web development,
|
||
data analysis, artificial intelligence, and scientific computing. Python is simple yet versatile.
|
||
"""
|
||
|
||
# 将字符串转换为小写,去掉标点符号,并按空格分割成单词
|
||
words = text.lower()
|
||
|
||
# 按照空格将单词分开
|
||
word1 = words.split(" ")
|
||
|
||
# 将单词前后的空格和换行符去除存入l2
|
||
word2 = []
|
||
for i in word1:
|
||
i = i.strip(".")
|
||
i = i.strip(",")
|
||
i = i.strip()
|
||
word2.append(i)
|
||
|
||
# 手动统计单词频率
|
||
word_count = {}
|
||
for word in word2:
|
||
if word in word_count:
|
||
word_count[word] += 1
|
||
else:
|
||
word_count[word] = 1
|
||
|
||
print(word_count)
|
||
```
|
||
|
||
## 扩展学习
|
||
|
||
- 如果想要取排名前5的应该如何,需要大家提前预习后续的知识,发挥一下学习能力吧
|
||
|
||
|
||
|
||
> <span style="color: red; background: yellow; padding: 2px 5px; font-size: 22px;">作业2.2提交的内容</span>
|
||
>
|
||
> - 程序运行成功的截图,单独发送给组长 |