Return Values In List That Also Have A Negated Value
def negated(a): a = set(a) for i in a: a.add(-i) return list(a) if a = [ 3, 4, 5, 6, 7, 8, -3, -4]. I only want to print the values that have a negated counte
Solution 1:
>>>s = set(a)>>>[item for item in a if -item in s]
[3, 4, -3, -4]
In your code you've reassigned the original list to a set, better assign it to different variable.
defnegated(a):
s = set(a)
for item in a:
if -item notin s:
s.remove(item)
returnlist(s)
... >>> negated(a)
[3, 4, -4, -3]
Solution 2:
You're close.
Instead of adding the negations to the set, however, you want to remove the ones whose negations aren't in the set. Like this:
defnegated(a):
a = set(a)
return [i for i in a if -i in a]
If you want to get tricky:
def negated(a):
return set(a) & {-i for i in a}
This just makes a set of a, and a set of a's negations, and returns the intersection. (It might be slightly faster as {-i for i in a}.intersection(a)
, but I think it's more readable this way.)
Post a Comment for "Return Values In List That Also Have A Negated Value"