Oldletter
279 天前
def select_numbers_optimized(seq, n):
# 计算总间隔数:相邻数字之间的差值总和
intervals = [seq[i + 1] - seq[i] for i in range(len(seq) - 1)]
# 计算目标间隔长度:将总间隔数除以(n-1),得到每个子区间的目标间隔长度
target_interval_length = sum(intervals) / (n - 1)
selected, current_interval_length = [seq[0]], 0
for i in range(len(intervals)):
current_interval_length += intervals[i]
# 当累积的间隔长度达到或超过目标间隔长度时,选择当前数字
if current_interval_length >= target_interval_length:
selected.append(seq[i + 1])
current_interval_length = 0
if len(selected) == n - 1: # 如果已选择了 n-1 个数字,则停止循环
break
selected.append(seq[-1]) # 总是包括序列的最后一个数字
return selected
if __name__ == '__main__':
sequence = [1, 2, 3, 5, 7, 8, 9, 10]
n = 4
selected_numbers_optimized = select_numbers_optimized(sequence, n)
print("干预后选出的数字:", selected_numbers_optimized)