Selva
Selva

Reputation: 3

check if a number has its equivalent negative number in a list

need to traverse through a list and check if list members has its equivalent negative numbers also in same list Note: list will not have duplicates and considering performance as well

l = [2, -3, 1, 3, 5, 0, -5, -2]

d=defaultdict(list)
for num in l:
    if num>0:
        d['pos'].append(num)
    else:
        d['neg'].append(num)
print (d)

not sure how to proceed further. Could you help please

l = [2, -3, 1, 3, 5, 0, -5, -2]

output: [[2,-2],[-3,3],[5,-5]]

Upvotes: 0

Views: 57

Answers (2)

Nelewout
Nelewout

Reputation: 6554

As there cannot be duplicates and you thus do not need to consider exclusive use of each number, you may use a set, like so,

numbers = [2, -3, 1, 3, 5, 0, -5, -2]
unique_numbers = set(numbers)

paired = [[number, -number] for number in numbers
          if number > 0 and -number in unique_numbers]

print(paired)

For a result of [[2, -2], [3, -3], [5, -5]].

Sets support O(1) membership checks. Constructing one from an existing list costs O(n), where n is the number of elements in the list. Iterating over the list to compute the pairs is again O(n), such that it runs in O(n) total, at the additional cost of some more memory for the set (again around n).

Upvotes: 2

daltonfury42
daltonfury42

Reputation: 3714

If you don't care much about performance,

[[x, -x] for x in l if x > 0 and -x in l]

Upvotes: 1

Related Questions