Bauer
Bauer

Reputation: 159

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 counterpart ex: 3, -3, 4, -4

I don't know what's wrong with my code.

Upvotes: 0

Views: 128

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

>>> 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.

def negated(a):
    s = set(a)
    for item in a:
        if -item not in s:
            s.remove(item)
    return list(s)
... 
>>> negated(a)
[3, 4, -4, -3]

Upvotes: 4

abarnert
abarnert

Reputation: 366133

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:

def negated(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.)

Upvotes: 3

Related Questions