0

I have a list of numbers:

nums = [-3,-2,-1,1,2,3,0,0]

And I want to iterate over the list, and add two numbers at a time, and if the sum of these two numbers is an element in the list (excluding the two we just summed), then I want to remove the element. How can I do this?

For example, since -3+2= -1 and -1 is in the list, I can remove -1 from the list.

I tried to create an empty list/set to store the sums of each pair of elements, then compare the elements in nums to this list/set, but this doesn't work, as it violates the second part of what I want to do- in brackets above!

P.S. I would like to remove as many elements as possible, and one worry is that if I remove elements as I iterate the list- before finding all of the pair sums- then I might miss some valid pair sums!

Any help is much appreciated.

2 Answers2

0

Although possibly inefficient (didn't care about efficiency when writing this answer), you could probably do the following:

for first in nums[:]:
    if first == 0: continue
    for second in nums[:]:
        if second == 0: continue
        sum = first + second
        if sum in nums:
            nums.remove(sum)

There are 2 things I will go over in this answer;

  1. nums[:] is the slicing syntax that will just create a copy of the array, whereafter that copy will be iterated over. The syntax for this was found within this answer: https://stackoverflow.com/a/1207461/6586516
  2. There are also checks to see if either the first or second number is equal to 0. This will satisfy the second condition (according to my logic). The only time the sum of a set of numbers can be equal to itself/one of the numbers used in the addition is when n - 1 numbers is equal to 0 (where n is the amount of numbers used in the addition)
Rizxcviii
  • 93
  • 8
0

You could try something like this:

itertools.combinations returns us with all possible combinations of a the argument. Since you want to numbers, providing 2 as the argument will return all possible combinations with length 2

Then we will just check the conditions and proceed to remove from the list.

from itertools import combinations
nums = [-3,-2,-1,1,2,3,0,0]
nums2=[i for i in combinations(nums,2)]
print(nums2)
for i in nums2:
    sums=i[0]+i[1]
    if sums in nums and (sums!=i[0] and sums!=i[1]):
        try:
            print(f"{sums} removed from list.\nNew List: {nums}")
            nums.remove(sums)
        except ValueError:
            print("{sums} not in list")
print(nums)