Shifu
Shifu

Reputation: 2185

Convert an integer to its negative

I'm trying to write some code that if a certain occurence happens, a specific number has to change to -that number. I have the following code so far:

x=6

for words in foo:
   if "bar" in words:
      crazy_function(x)
   else:
      pass

if the word "bar" is in words, x will need to come out as -6, if it is not in words, it needs to come out as +6. In some cases however x=-6 in which case it needs to become positive if bar is in words. I need to replace "crazy_function()" with something that actually works.

Upvotes: 1

Views: 243

Answers (6)

dansalmo
dansalmo

Reputation: 11686

x = x*([-1 for words in foo if 'bar' in words]+[1])[0]

Upvotes: 0

abarnert
abarnert

Reputation: 365617

There's already a function for this in the standard library: neg.

In a case like this, where you just need an expression and there's no good reason it has to be a function, it's silly to use neg. Compare:

if "bar" in words:
    x = operator.neg(x)

if "bar" in words:
    x = -x

The second is clearly more readable, as well as shorter.

However, there are cases where you actually need a function. In that case, neg is better than creating a function on the fly. Compare:

foo = map(operator.neg, bar)

foo = map(lambda x: -x, bar)

(Of course in this case, you could just write foo = (-x for x in bar)… but not every higher-order function maps to a comprehension clause.)

Upvotes: 4

Óscar López
Óscar López

Reputation: 235984

The "crazy function" is trivial to implement:

def crazy_function(x):
    return -x

Use it like this:

if "bar" in words:
    x = crazy_function(x)

Or simply in-line it:

if "bar" in words:
    x = -x

To make it even shorter, as pointed by @kroolik:

x = -x if "bar" in words else x

Upvotes: 6

Lochemage
Lochemage

Reputation: 3974

Use the negation operator:

x=6

for words in foo:
  if "bar" in words:
    x = -x;

Upvotes: 13

llb
llb

Reputation: 1741

Well, there's always the old standby, multiplication.

x *= -1

Upvotes: 1

Bob Stout
Bob Stout

Reputation: 1259

Multipy the number by -1? That seems the simplest way to do it.

Upvotes: 0

Related Questions