알고리즘 문제/CodeWar

Difference of 2

BEstyle 2022. 11. 1. 13:54

DESCRIPTION:

The objective is to return all pairs of integers from a given array of integers that have a difference of 2.

The result array should be sorted in ascending order of values.

Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter.

Examples

[1, 2, 3, 4]  should return [(1, 3), (2, 4)]

[4, 1, 2, 3]  should also return [(1, 3), (2, 4)]

[1, 23, 3, 4, 7] should return [(1, 3)]

[4, 3, 1, 5, 6] should return [(1, 3), (3, 5), (4, 6)]

def twos_difference(lst): 
    lst.sort()
    print(lst)
    alist=[]
    for i in range(len(lst)-1):
        for j in range(i+1,len(lst)):
            if lst[i]+2==lst[j]:
                alist.append((lst[i],lst[j]))
    print(alist)
    return alist