计算机基础期末考试模拟试卷(第三套)
一、单选题(共15题,30.0分)
1. (单选题, 2.0分) 在Python中,关于类的继承说法正确的是____。
A. 子类不能访问父类的私有成员
B. Python不支持多继承
C. 子类必须重写父类的所有方法
D. 子类不能调用父类的构造函数
2. (单选题, 2.0分) 在下列关于Python包和模块的说法中,正确的是____。
A. 包必须包含__main__.py文件
B. 一个包就是一个包含__init__.py的文件夹
C. 模块不能包含类定义
D. 导入模块时必须使用绝对路径
3. (单选题, 2.0分) 执行下面的代码后,要在第2行第4列的位置绘制饼图,正确的语句是____。
python
fig, ax = plt.subplots(nrows=3, ncols=5, figsize=(10,6))
A. ax[1,3].pie([30,40,30])
B. ax[2,4].pie([30,40,30])
C. ax[1][3].pie([30,40,30])
D. A和C都正确
4. (单选题, 2.0分) 以下列表推导式中,能正确生成1到100之间所有偶数的平方组成的列表是____。
A. [x**2 for x in range(1,101) if x%2==1]
B. [x**2 for x in range(2,101,2)]
C. [x for x in range(1,101) if x**2%2==0]
D. [x**2 for x in range(1,101) if x//2==0]
5. (单选题, 2.0分) 执行语句from PIL import Image后,要将图像转换为灰度模式,正确的语句是____。
A. im = Image.convert("L")
B. gray_im = im.convert("L")
C. im.to_gray()
D. gray_im = Image.gray(im)
6. (单选题, 2.0分) 关于文件操作,下列说法错误的是____。
A. fp.read()一次性读取整个文件内容
B. fp.readline()每次读取一行
C. fp.readlines()返回包含所有行的列表
D. fp.read(10)读取10行内容
7. (单选题, 2.0分) 在下列关于异常处理的说法中,错误的是____。
python
try:
num = int(input("请输入数字: "))
result = 100 / num
except ValueError:
print("输入格式错误")
except ZeroDivisionError:
print("不能除以零")
finally:
print("程序结束")
A. finally块一定会执行
B. 如果输入"abc",会输出"输入格式错误"
C. 如果输入0,会输出"不能除以零"
D. 如果没有异常,不会输出"程序结束"
8. (单选题, 2.0分) 关于jieba分词,下列说法正确的是____。
A. jieba.lcut()返回字符串
B. jieba.lcut_for_search()用于搜索引擎模式
C. jieba.add_word()用于删除词语
D. 全模式会跳过不能识别的词
9. (单选题, 2.0分) 已知text = 'apple,banana,orange,grape',则text.split(',', 2)的返回值是____。
A. ['apple', 'banana']
B. ['apple', 'banana', 'orange,grape']
C. ['apple', 'banana', 'orange', 'grape']
D. 报错
10. (单选题, 2.0分) 关于面向对象编程,下列说法正确的是____。
A. 封装是指隐藏对象的实现细节
B. 继承是指子类不能使用父类的方法
C. 多态是指一个类只能有一个方法
D. 类和对象是同一个概念
11. (单选题, 2.0分) 关于CSV文件,下列说法错误的是____。
A. CSV文件是逗号分隔值文件
B. CSV文件可以用Excel打开
C. CSV文件只能包含数字数据
D. Python的csv模块可以处理CSV文件
12. (单选题, 2.0分) 利用matplotlib绘制柱状图时,设置柱子宽度的参数是____。
A. width
B. barwidth
C. size
D. height
13. (单选题, 2.0分) 假定执行了如下的语句,则____。
python
fp = open("data.txt", "a+", encoding='utf-8')
A. 文件不存在会报错
B. 可以读取文件内容
C. 写入的内容会覆盖原内容
D. 不能写入文件
14. (单选题, 2.0分) 要绘制一个包含5个数据点的折线图,并用红色三角形标记,正确的语句是____。
A. plt.plot([1,2,3,4,5], [2,4,6,8,10], 'r^-')
B. plt.plot([1,2,3,4,5], [2,4,6,8,10], color='red', marker='triangle')
C. plt.line([1,2,3,4,5], [2,4,6,8,10], 'r^')
D. plt.scatter([1,2,3,4,5], [2,4,6,8,10], 'r^-')
15. (单选题, 2.0分) NumPy中用于获取数组形状的属性是____。
A. size
B. shape
C. dimension
D. length
二、程序填空题(共2题,24.0分)
16. (程序填空题, 12.0分) 程序的功能是读取彩色图像,分别提取RGB三个通道,并在三个子图中显示,同时计算并输出各通道的最大值和最小值。
python
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
try:
im = Image.__(1)__(r"photo.jpg")
arr = np.array(im)
plt.rcParams['font.sans-serif'] = ['SimHei']
fig, axes = plt.__(2)__(1, 3, figsize=(15,5))
colors = ['Reds', 'Greens', 'Blues']
channels = ['红色', '绿色', '蓝色']
for i in range(3):
channel_data = arr[:, :, i]
axes[__(3)__].imshow(channel_data, cmap=colors[i])
axes[i].set_title(f'{channels[i]}通道')
max_val = np.__(4)__(channel_data)
min_val = np.min(channel_data)
print(f"{channels[i]}通道 - 最大值: {max_val}, 最小值: {min_val}")
plt.tight_layout()
plt.show()
except FileNotFoundError:
print("图像文件不存在!")
第1空:________
第2空:________
第3空:________
第4空:________
17. (程序填空题, 12.0分) 程序的功能是读取JSON格式的员工信息文件,计算平均工资,找出工资最高的员工,并按工资降序排序输出。
文件employees.json内容示例:
json
[
{"name": "张三", "department": "技术部", "salary": 15000},
{"name": "李四", "department": "销售部", "salary": 12000},
{"name": "王五", "department": "技术部", "salary": 18000},
{"name": "赵六", "department": "人事部", "salary": 10000}
]
python
import __(1)__
file = open(r"employees.json", "r", encoding='utf-8')
data = json.__(2)__(file)
file.close()
total_salary = 0
max_employee = None
max_salary = 0
for emp in data:
salary = emp['salary']
total_salary += salary
if salary __(3)__ max_salary:
max_salary = salary
max_employee = emp
avg_salary = total_salary / len(data)
print(f"平均工资: {avg_salary:.2f}元")
print(f"最高工资员工: {max_employee['name']} ({max_employee['department']}) - {max_salary}元")
# 按工资降序排序
data.__(4)__(key=lambda x: x['salary'], reverse=True)
print("\n按工资排序(降序):")
for emp in data:
print(f"{emp['name']}: {emp['salary']}元")
第1空:________
第2空:________
第3空:________
第4空:________
三、程序调试题(共2题,20.0分)
18. (程序调试题, 10.0分) 下面的程序有4个错误,请改正。改正的语句后面添加注释:#此行有错误,已经改正
程序功能:读取温度数据,绘制折线图显示温度变化趋势,并在另一个子图中绘制温度的直方图分布。
python
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ('SimHei')
# 模拟一周温度数据(7天,每天4个时间点)
days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
temps = [
[15, 22, 25, 18],
[16, 23, 26, 19],
[14, 21, 24, 17],
[17, 24, 27, 20],
[15, 22, 25, 18],
[18, 25, 28, 21],
[16, 23, 26, 19]
]
# 计算每天平均温度
avg_temps = []
for temp in temps:
avg_temps.append(sum(temp) // len(temp))
fig = plt.figure(figsize=(12,5))
# 绘制折线图
plt.subplot(1,2,1)
plt.plot(days, avg_temps, 'bo-', linewidth=2)
plt.title('一周平均温度变化')
plt.xlabel('日期')
plt.ylabel('温度(°C)')
plt.grid(True)
# 绘制直方图
plt.subplot(1,2,2)
all_temps = np.array(temps).flatten
plt.hist(all_temps, bins=15, color='orange', edgecolor='black')
plt.title('温度分布直方图')
plt.xlabel('温度(°C)')
plt.ylable('频次')
plt.show()
请将改正后的完整程序粘贴在答题框中。
19. (程序调试题, 10.0分) 下面的程序有4个错误,请改正。改正的语句后面添加注释:#此行有错误,已经改正
程序功能:定义一个处理字符串列表的函数,统计列表中每个字符串的长度,返回长度最长和最短的字符串。
python
def analyze_strings(str_list):
if len(str_list) = 0:
return None, None
max_str = str_list[0]
min_str = str_list[0]
length_dict = []
for s in str_list:
length = len(s)
length_dict[s] = length
if length > len(max_str):
max_str = s
if length > len(min_str):
min_str = s
return max_str, min_str, length_dict
words = ['Python', 'Java', 'C++', 'JavaScript', 'Go', 'Rust']
longest, shortest, lengths = analyze_strings(words)
print(f"最长的字符串: {longest} (长度: {len(longest)})")
print(f"最短的字符串: {shortest} (长度: {len(shortest)})")
print("所有字符串长度:")
for word, length in lengths.items():
print(f" {word}: {length}")
请将改正后的完整程序粘贴在答题框中。
四、编程题(共2题,26.0分)
20. (编程题, 14.0分)
文本文件books.csv中存放了图书信息,包括书名、作者、类别、价格、库存,文件内容如下:
书名,作者,类别,价格,库存
Python编程,张三,计算机,89.0,100
数据结构,李四,计算机,78.5,80
机器学习,王五,计算机,128.0,50
红楼梦,曹雪芹,文学,45.0,200
三国演义,罗贯中,文学,42.0,150
西游记,吴承恩,文学,40.0,180
水浒传,施耐庵,文学,43.0,160
请编写程序,完成如下功能:
- 从文件中读取数据
- 计算所有图书的总库存量和总价值(价格×库存)
- 统计各类别图书的数量和平均价格
- 找出价格最高和最低的图书
- 将计算机类别的图书按价格降序排序,写入文件computer_books.csv
输出示例:
总库存量: 920本
总价值: 67830.0元
类别统计:
计算机类 - 数量: 3本, 平均价格: 98.50元
文学类 - 数量: 4本, 平均价格: 42.50元
价格最高: 机器学习 (128.0元)
价格最低: 西游记 (40.0元)
computer_books.csv示例内容:
书名,作者,价格,库存
机器学习,王五,128.0,50
Python编程,张三,89.0,100
数据结构,李四,78.5,80
请将完整程序代码粘贴在答题框中。
21. (编程题, 12.0分)
设计一个表示学生的Student类,包含以下内容:
- 数据成员:student_id(学号)、name(姓名)、scores(成绩列表,包含3门课程)
- 构造函数:初始化学号、姓名和成绩列表
- get_average()方法:计算并返回平均分
- get_total()方法:计算并返回总分
- get_grade()方法:根据平均分返回等级(90以上为A,80-89为B,70-79为C,60-69为D,60以下为E)
- display()方法:显示学生完整信息
编写主程序测试所定义的类。要求:创建3个学生对象,计算并显示各自的成绩信息,找出平均分最高的学生。
输出界面示例:
====== 学生成绩管理系统 ======
学生1信息:
学号: 2024001
姓名: 张三
成绩: [85, 92, 78]
总分: 255
平均分: 85.00
等级: B
学生2信息:
学号: 2024002
姓名: 李四
成绩: [95, 88, 92]
总分: 275
平均分: 91.67
等级: A
学生3信息:
学号: 2024003
姓名: 王五
成绩: [78, 82, 75]
总分: 235
平均分: 78.33
等级: C
====== 统计信息 ======
平均分最高的学生: 李四 (91.67分)
请将完整程序代码粘贴在答题框中。
参考答案
一、单选题答案
- A 2. B 3. D 4. B 5. B
- D 7. D 8. B 9. B 10. A
- C 12. A 13. B 14. A 15. B
二、程序填空题答案
16题答案:
- open
- subplots
- i
- max
17题答案:
- json
- load
- sort
三、程序调试题参考答案
18题参考答案:
python
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei'] #此行有错误,已经改正
# 模拟一周温度数据(7天,每天4个时间点)
days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
temps = [
[15, 22, 25, 18],
[16, 23, 26, 19],
[14, 21, 24, 17],
[17, 24, 27, 20],
[15, 22, 25, 18],
[18, 25, 28, 21],
[16, 23, 26, 19]
]
# 计算每天平均温度
avg_temps = []
for temp in temps:
avg_temps.append(sum(temp) / len(temp)) #此行有错误,已经改正
fig = plt.figure(figsize=(12,5))
# 绘制折线图
plt.subplot(1,2,1)
plt.plot(days, avg_temps, 'bo-', linewidth=2)
plt.title('一周平均温度变化')
plt.xlabel('日期')
plt.ylabel('温度(°C)')
plt.grid(True)
# 绘制直方图
plt.subplot(1,2,2)
all_temps = np.array(temps).flatten() #此行有错误,已经改正
plt.hist(all_temps, bins=15, color='orange', edgecolor='black')
plt.title('温度分布直方图')
plt.xlabel('温度(°C)')
plt.ylabel('频次') #此行有错误,已经改正
plt.show()
19题参考答案:
python
def analyze_strings(str_list):
if len(str_list) == 0: #此行有错误,已经改正
return None, None
max_str = str_list[0]
min_str = str_list[0]
length_dict = {} #此行有错误,已经改正
for s in str_list:
length = len(s)
length_dict[s] = length
if length > len(max_str):
max_str = s
if length < len(min_str): #此行有错误,已经改正
min_str = s
return max_str, min_str, length_dict
words = ['Python', 'Java', 'C++', 'JavaScript', 'Go', 'Rust']
longest, shortest, lengths = analyze_strings(words)
print(f"最长的字符串: {longest} (长度: {len(longest)})")
print(f"最短的字符串: {shortest} (长度: {len(shortest)})")
print("所有字符串长度:")
for word, length in lengths.items():
print(f" {word}: {length}")
四、编程题参考答案
20题参考答案:
python
# 读取数据
fp = open(r"books.csv", "r", encoding='utf-8')
lines = fp.readlines()
fp.close()
books = []
for i in range(1, len(lines)):
data = lines[i].strip().split(',')
book = {
'title': data[0],
'author': data[1],
'category': data[2],
'price': float(data[3]),
'stock': int(data[4])
}
books.append(book)
# 计算总库存和总价值
total_stock = sum([b['stock'] for b in books])
total_value = sum([b['price'] * b['stock'] for b in books])
print(f"总库存量: {total_stock}本")
print(f"总价值: {total_value}元")
# 统计各类别
category_stats = {}
for book in books:
cat = book['category']
if cat not in category_stats:
category_stats[cat] = {'count': 0, 'total_price': 0}
category_stats[cat]['count'] += 1
category_stats[cat]['total_price'] += book['price']
print("\n类别统计:")
for cat, stats in category_stats.items():
avg_price = stats['total_price'] / stats['count']
print(f"{cat}类 - 数量: {stats['count']}本, 平均价格: {avg_price:.2f}元")
# 找出最高和最低价格
max_book = max(books, key=lambda x: x['price'])
min_book = min(books, key=lambda x: x['price'])
print(f"\n价格最高: {max_book['title']} ({max_book['price']}元)")
print(f"价格最低: {min_book['title']} ({min_book['price']}元)")
# 保存计算机类图书
computer_books = [b for b in books if b['category'] == '计算机']
computer_books.sort(key=lambda x: x['price'], reverse=True)
fp_out = open("computer_books.csv", "w", encoding='utf-8')
fp_out.write("书名,作者,价格,库存\n")
for book in computer_books:
fp_out.write(f"{book['title']},{book['author']},{book['price']},{book['stock']}\n")
fp_out.close()
21题参考答案:
python
class Student:
def __init__(self, student_id, name, scores):
self.student_id = student_id
self.name = name
self.scores = scores
def get_total(self):
return sum(self.scores)
def get_average(self):
return sum(self.scores) / len(self.scores)
def get_grade(self):
avg = self.get_average()
if avg >= 90:
return 'A'
elif avg >= 80:
return 'B'
elif avg >= 70:
return 'C'
elif avg >= 60:
return 'D'
else:
return 'E'
def display(self):
print(f"学号: {self.student_id}")
print(f"姓名: {self.name}")
print(f"成绩: {self.scores}")
print(f"总分: {self.get_total()}")
print(f"平均分: {self.get_average():.2f}")
print(f"等级: {self.get_grade()}")
# 测试程序
print("====== 学生成绩管理系统 ======\n")
students = [
Student("2024001", "张三", [85, 92, 78]),
Student("2024002", "李四", [95, 88, 92]),
Student("2024003", "王五", [78, 82, 75])
]
for i, stu in enumerate(students, 1):
print(f"学生{i}信息:")
stu.display()
print()
# 找出平均分最高的学生
max_student = max(students, key=lambda s: s.get_average())
print("====== 统计信息 ======")
print(f"平均分最高的学生: {max_student.name} ({max_student.get_average():.2f}分)")