Change language

# Python | Find all different pairs with a difference equal to k

| |

Examples :

`  Input:  [1, 5, 3, 4, 2], k = 3  Output:  [(5, 2), (4, 1)]  Input:  [8, 12, 16, 4, 0, 20], k = 4  Output:  [(8, 4), (12, 8), (16, 12), (4, 0), (20, 16)] `

Approach # 1: understanding Python list

We will use a list comprehension using two loops using & # 39; e1 & # 39; and & # 39; e2 & # 39; which will go through this list. We check if e1-e2 == k or not and return a tuple (e1, e2) accordingly. Finally, a list with the required tuples will be returned.

 ` # Python3 program to find all great ones ` ` # pairs with a difference equal to k `   ` def ` ` findPairs (lst, k): `   ` return ` ` [(e1, e2) ` ` for ` ` e1 ` ` in ` ` lst ` ` for ` ` e2 ` ` in ` ` lst ` ` if ` ` (e1 ` ` - ` ` e2 ` ` = ` ` = ` ` k)] `   ` # Driver code ` ` lst ` ` = ` ` [` ` 1 ` `, ` ` 5 ` `, ` ` 3 ` `, ` ` 4 ` `, ` ` 2 ` `] ` ` k ` ` = ` ` 3 ` ` print ` ` (findPairs (lst, k)) `

Exit:

` [(5, 2), (4, 1)] `

Approach # 2:

This is an effective approach in relation to the above approach as it only uses space O (n). We take an empty list to store the output. Then we use a loop with an iterator & # 39; e & # 39; to move through the specified list. At each iteration, we check if there is e + k, i.e. the required integer pair for e is available or not. If yes, we add a tuple to res.

 ` # Python3 program to find all great ones ` ` # pairs with a difference equal to k `   ` def ` ` findPairs (lst, k): ` ` res ` ` = ` ` [] ` ` for ` ` e ` ` in ` ` lst: ` ` if ` ` e ` ` + ` ` k ` ` in ` ` lst: ` `  res.append ( tuple ((e, e + k))) ``   return res   # Driver code lst = [ 1 , 5 , 3 , 4 , 2 ] k = 3 print (findPairs (lst, k)) < / p> `

Exit:

` [(1, 4), ( 2, 5)] `

Approach # 3: ` combinations () ` from the ` itertools ` module

The best approach is to use the built-in function from the itertools module.  combinations () creates an iterator for tuples of all combinations of n elements in the inputs. We use these combinations and display the ones that have a difference of "k".

 ` # Python3 program to find all great ones ` ` # pairs with a difference equal to k ` ` from ` ` itertools ` ` import ` ` combinations `   ` def ` ` findPairs (lst, k): ` ` return ` ` [(x, y) ` ` for ` ` x, y ` ` in ` ` combinations (lst, r ` ` = ` ` 2 ` `) ` ` ` ` if ` ` abs ` ` (x ` ` - ` ` y) ` ` = ` ` = ` ` k] `   ` # Driver code ` ` lst ` ` = ` ` [` ` 1 ` `, ` ` 5 ` `, ` ` 3 ` `, ` ` 4 ` `, ` ` 2 ` `] ` ` k ` ` = ` ` 3 ` ` print ` ` (findPairs (lst , k)) `

Exit:

` [(1, 4), (5, 2)] `