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.
Advertisement
Answer
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;
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- 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)