在本文中,我们将了解如何计算精确差等于k的数字对的数量。给定的数字以列表的形式出现,我们将k的值提供给程序。
在这种方法中,我们设计了两个for循环,一个内部循环。外部的for循环跟踪访问给定列表的每个元素。内部for循环会继续将其余每个元素与外部循环的元素进行比较,如果count变量与所需的差值匹配,则增加count变量的值。
listA = [5, 3, 7, 2, 9]
k = 2
count = 0
# Elements of the list
for i in range(0, len(listA)):
# Make pairs
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
在另一种方法中,我们使用带有if else子句的while循环登录。在这里,我们根据两个对之间的差异是否与所需的差异相匹配,继续增加当前索引和下一个索引。
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