我只会点python ,尝试用python 做了一遍:


python题解脚本
#!/usr/bin/env python3
date = '''5
7 1 3 14 5
56
0 2''' # 输出 7 1 56 3 14 5
print(
f"\n\n{' 数组增加元素 ':*^36}"
f"\n\n输入样例:\n{date}")
# 数据梳理 #
date = date.split('\n')
n = int(date[0]) # 班级同学人数0 < n < 60
students = list(map(int, date[1].split())) # 班级同学列表(学号列表)
new_stu = int(date[2])
p, q = map(int, date[-1].split()) # p,新同学排位前后“开关”;q,新同学排位入口
print(
f"\n数据梳理:"
f"\n{n = }\n{students = }"
f"\n{new_stu = }\n{p = }, {q = }"
)
# 新同学排位 #
new_index = q-1 if p == 1 else q # 确认新同学排位入口
print(f"\n{new_index = }")
students.insert(new_index, new_stu) # 新同学排位(list插入,list.insert方法是在index之前插入,就“抵消”list元素对象从0起index。所以,直接new_stu插入)
students = ' '.join(map(str, students))
print(
f"\n输出:"
f"\n{students = }"
f"\n\n{'':=^42}"
)
# 精细解题 #
def data_input() -> tuple:
''' 数据输入 '''
print(f"\n\n{' 数组增加元素 ':*^36}")
try:
n = int(input(
f"\n输入班级同学人数"
f"\n{'(0 < n < 60):':>15}"))
except ValueError:
raise ValueError(f"{' 请输入整数 ':-^37}")
if not (0 < n < 60):
raise ValueError(f"\n{' 班级同学人数必须在0到60之间 ':-^30}")
students = list(map(int, input(f"输入班级同学学号:\n{'如7 1 3 14 5':>27}\n{'':>18}").strip().split())) # 班级同学列表(学号列表)
if len(students) != n:
raise ValueError(f"\n{' 输入的学号数量与班级人数不符 ':-^28}")
try:
new_stu = int(input('输入新同学学号:'))
except ValueError as e:
raise ValueError(f"{' 请输入整数 ':-^37}")
try:
p, q = map(int, input(f"输入p和q的值,用空格分隔\n{'(q为大于等于1的整数)':>10}").strip().split())
except ValueError as e:
raise ValueError(f"{' 请输入两个整数':-^35}")
if q < 1:
raise ValueError(f"{' q的值必须大于等于1 ':-^34}")
return n, students, new_stu, p, q
def in_date():
''' 递归数据输入函数 '''
try:
return data_input()
except ValueError as e:
print(
f"\n{e}"
f"\n\n{' 请根据提示重新输入 ':.^33}"
)
return in_date()
# 调用递归函数并获取数据
n, students, new_stu, p, q = in_date()
# 根据q的值插入新同学
new_index = q-1 if p == 1 else q # 保证当p不是1时,在q之后安排新同学入座
students.insert(new_index, new_stu) # 新同学排位(list插入,list.insert方法是在index之前插入,就“抵消”list元素对象从0起index。所以,直接new_stu插入)
# 打印结果
print(
f"\n输出:"
f"\n{' '.join(map(str, students))}"
f"\n\n{'':=^42}"
)