Possible Duplicate:
python takes list and returns only if negative value also exists using set
I’m having problems with another homework problem.
By using a set, write a method negated(a) that takes a list, a, as an
argument and returns a list containing only the elements x such that
-x is also in a
His example shows that the input is
[-6, 8, 7, 3, 2, -9, 1, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, 1, -9,
-3, -7, -3, -5, 6, -3, 6, -3, -10, -8]
and the output is
[-6, 8, 7, 3, 2, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, -3, -7, -3, 6,
-3, 6, -3, -8]
I was able to figure out how to do it without using a set with
return [x for x in a if -x in a]
I’m just having problems implementing a set into the problem.
Can someone give me the steps to take, how I should tackle the problem… I’m not looking for the complete work, but it would be nice to see how you do it also.
Here’s the algorithm that you need to implement:
It’s usually a bad idea to delete elements from a list as you’re iterating over it, so it’s best to make a new empty list and keep adding (or not) to it.
Here’s a list comprehension for the same:
There’s a performance issue when you do this though. Checking if an element is in a list is an O(n) operation and O(1) in a set. So, it’s better to turn
Linto a set first:Here’s a list comprehension for the same:
Hope this helps