在 Python 中查找所有差异等于 k 的不同对
pythonserver side programmingprogramming更新于 2025/10/11 8:12:17
在本文中,我们将了解如何计算差异精确等于 k 的数字对的数量。给定的数字以列表的形式出现,我们将 k 的值提供给程序。
使用 for 循环
在这种方法中,我们设计了两个 for 循环,一个在另一个内部。外部 for 循环跟踪访问给定列表的每个元素。内部 for 循环不断将剩余的每个元素与外部循环的元素进行比较,如果匹配所需的差异,则增加 count 变量的值。
示例
listA = [5, 3, 7, 2, 9]
k = 2
count = 0
# 列表元素
for i in range(0, len(listA)):
# 配对
for j in range(i + 1, len(listA)):
if listA[i] - listA[j] == k or listA[j] - listA[i] == k:
count += 1
print("Required Pairs: ",count)
输出
运行上述代码得到以下结果 −
Required Pairs: 3
使用 While 循环
在另一种方法中,我们将 while 循环与 if else 子句一起使用。在这里,我们根据两对之间的差异是否与所需差异相匹配,不断增加当前和下一个索引。
示例
listA = [5, 3, 7, 2, 9]
k = 2
count = 0
listA.sort()
next_index = 0
current_index = 0
while current_index < len(listA):
if listA[current_index] - listA[next_index] == k:
count += 1
next_index += 1
current_index += 1
elif listA[current_index] - listA[next_index] > k:
next_index += 1
else:
current_index += 1
print("Required Pairs: ",count)
输出
运行上述代码得到以下结果 −
Required Pairs: 3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

