在Python中查詢差值為k的所有不同對
在這篇文章中,我們將學習如何計算具有精確差值k的數字對的數量。給定的數字以列表的形式給出,我們將向程式提供k的值。
使用for迴圈
在這種方法中,我們設計了兩個for迴圈,一個巢狀在另一個裡面。外部for迴圈跟蹤訪問給定列表的每個元素。內部for迴圈將每個剩餘元素與外部迴圈的元素進行比較,如果匹配所需的差值,則增加計數變數的值。
示例
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
使用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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP