我想创建一个列表理解或一个 for/while 循环,它采用一个 int 值(k),然后继续附加中点,直到列表的长度为(k)。所以对于 k=10,列表必须是从(0 到 k-1)和(0 到 9)。首先它会附加中点 5,即 10//2。然后它将附加 2,因为索引 0 和 4 之间的中点是 2,而 6 和 10 之间的中点紧接着是 8。这将一直持续到列表中出现 0 到 9 范围内的所有值(含 0 到 9)。请注意,它将是一个整数列表而不是浮点数。我正在尝试使用本机 python 而不使用任何外部库来执行此操作。下面的代码不起作用,我该怎么做呢?
代码:
k = 10
output = [k // 2] # initial midpoint
while len(output) != k:
formatted_list = [0] + output + [k]
for c,x in enumerate(formatted_list[:-1]):
output.append((formatted_list[c+1] - x) //2)
输入:
k = 10
预期产出:
[5,2,8,1,4,7,9,0,3,6]
输入:
k = 11
预期产出:
[5,2,8,1,4,7,10,0,3,6,9]
以下代码应该适用于您的情况
k = 10
midpoints = [k // 2]
# Start with the midpoint of the full range
while len(midpoints) < k:
# Find the index of the last midpoint
last_idx = len(midpoints) - 1
# Determine the lower and upper bounds of the remaining range
lower = midpoints[last_idx - 1] + 1 if last_idx > 0 else 0
upper = midpoints[last_idx] - 1 if last_idx < len(midpoints) - 1 else 9
# Find the midpoint of the remaining range and append it to the list
midpoint = (lower + upper) // 2
midpoints.append(midpoint)
print(midpoints)