代码示例:
def my_within_tolerance(A, a, tol):
"""返回 A 中所有满足 |A − a| < tol 的元素的索引列表"""
indices = []
for i in range(len(A)):
if abs(A[i] - a) < tol:
indices.append(i)
return indices
该函数接受三个参数:列表 A、目标值 a 和容差 tol。函数首先创建一个空列表 indices 用于存储满足条件的元素索引。然后遍历 A 中的每一个元素,如果该元素与 a 的差小于容差 tol,则将其索引添加到 indices 中。最后返回 indices 列表作为函数的输出。
例如,我们调用 my_within_tolerance([1, 2, 3, 4, 5], 3, 1),函数将返回 [2, 3, 4],因为 A 中第 2、3、4 个元素与 a 的差均小于 1。