简体   繁体   中英

Return all pairs of integers from a given list of integers that have a difference of 2

Like the title says, i need to find the difference of integers in a list by 2 and must return a list with tuples.

initial_list = [1, 2, 3, 4]
expected_output = [(1, 3), (2, 4)]

I wrote this code:

arr = [1, 2, 3, 4]
n = 2
arr1 = []
for i in range(len(arr)):
    x = i + n
    if x in arr:
        arr1.append(x)
print(arr1)

But doesn't work... Can u help me? Thx

If you make the initial list a set, you can efficiently test if n+2 is in the set for every n and include the tuple if it is:

initial_list = [1, 2, 3, 4]
s = set(initial_list)

[(n, n+2) for n in initial_list if n + 2 in s ]
# [(1, 3), (2, 4)]

You can do itertools.combinations and fetch only combinations that differ by 2:

[(x, y) for x, y in combinations(lst, 2) if abs(x-y) == 2]

Code :

from itertools import combinations

lst = [1, 2, 3, 4]

result = [(x, y) for x, y in combinations(lst, 2) if abs(x-y) == 2]
# [(1, 3), (2, 4)]

Why do you get your output?

You are iterating over the indices of the list, not the elements itself. Even if you iterate over the elements, you are ignoring one element resulting in a list instead of a list of tuples as output.

Your immediately problem is that i is just an index, not one of your list elements. Either

for i in arr:
    ...

or

for i in range(len(arr)):
    x = arr[i] + n
    ...

will fix the problem.

However, calling x in arr takes O(n) time, and you don't really need to search the entire list, especially if you sort it first. You only need to walk the list until you find a value larger than your target, so something like

for i, x in enumerate(sorted(arr)):
    for y in arr[i:]:
        d = y - x
        if d == 2:
            arr1.append((x,y))
        elif d > 2:
            break

A simple way of doing this is to use a function like the one shown below, which takes in the list of integers and the desired seperation as input, and returns an array of tuples of values matching the seperation.

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def findIntsWithDif(data, dif):
    res = []
    for val1 in data:
        for val2 in data:
            if abs(val2 - val1) == dif and (val2, val1) not in res:
                res.append((val1, val2))

    return res

print(findIntsWithDif(arr, 2))

This is not the most efficient method of doing this, but it does give the correct output. It will work quickly for small arrays, though for larger arrays it will be quite slow as it is O(n^2) in complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM