Python编程题目答疑「Python一对一辅导考试真题解析」
2023-12-23 18:20:59
你好,我是悦创。
某大学在线编程考试,代考。「本文已经发布时,已经考完且出完成绩才发布」
更新计划
- 答案
- 题目
- 记得点赞收藏!
题目
题目链接:https://bornforthis.cn/blog/2023/12month/python-kaoshi.html
Solution
Question 1
# 读取输入
a = float(input("请输入实数 a: "))
b = float(input("请输入实数 b: "))
c = float(input("请输入实数 c: "))
# 计算和
sum = a + b + c
# 输出结果,保留两位小数
print(f"{sum:.2f}")
Question 2
class Add:
def __init__(self):
self.value = None
def add(self, a, b):
self.value = a + b
class AddInt(Add):
def add(self, a, b):
if isinstance(a, int) and isinstance(b, int):
self.value = a + b
class AddN(Add):
def __init__(self, n):
super().__init__()
self.n = n
def add(self, a):
self.value = self.n + a
a = Add()
a.add(2023, 1223)
print(a.value)
a = AddInt()
a.add(2023, 12.23)
print(a.value is None)
a = AddN(-1)
a.add(1)
print(a.value)
Question 3
class Vector:
def __init__(self, values):
# 如果values是单一的数字,将其转换为长度为1的列表
if isinstance(values, (int, float)):
values = [values]
self.values = values
def __str__(self):
return str(self.values)
def __len__(self):
return len(self.values)
def __add__(self, other):
# 处理与实数的加法,将实数转换为长度为1的向量
if isinstance(other, (int, float)):
if len(self) != 1:
raise ValueError("Cannot add scalar to Vector of length other than 1.")
return Vector([self.values[0] + other])
if isinstance(other, Vector):
if len(self) != len(other):
raise ValueError("Vectors are of different lengths.")
return Vector([a + b for a, b in zip(self.values, other.values)])
raise ValueError("Can only add Vector or scalar to Vector.")
def __radd__(self, other):
return self.__add__(other)
# 用于判题程序的交互部分
try:
eval(input())
except ValueError:
eval(input())
# print(len(Vector([])))
# print(5 + Vector([1, 2, 3, 4]))
# print("HelloWorld")
Question 4
def two_numbers_star(x, y):
if x == 0 or y == 0:
return 0
if x % 2 == 0 and y % 2 == 0:
return 2 * two_numbers_star(x // 2, y // 2)
elif x % 2 == 1 and y % 2 == 1:
return 2 * two_numbers_star((x - 1) // 2, (y - 1) // 2)
elif x % 2 == 0 and y % 2 == 1:
return 1 + 2 * two_numbers_star(x // 2, (y - 1) // 2)
else:
return two_numbers_star(y, x)
# 测试样例
x = 12
y = 23
result = two_numbers_star(x, y)
result
Question 5
def find_minimal_sum_revised(n, numbers):
total_sum = sum(numbers)
index_dict = {}
min_value = float('inf')
for i in range(n):
pair_num = total_sum - numbers[i]
if pair_num in index_dict and index_dict[pair_num] != i:
current_value = i + 1 + (index_dict[pair_num] + 1) * (n + 1)
min_value = min(min_value, current_value)
if numbers[i] not in index_dict:
index_dict[numbers[i]] = i
return min_value if min_value != float('inf') else 0
n = 5
numbers = [15, -11, 2, 7, -4]
find_minimal_sum_revised(n, numbers)
文章来源:https://blog.csdn.net/qq_33254766/article/details/135167378
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!