-3

In C the shortest and obvious way to avoid conditions is:

int x = 42;

int oneorzero = !!x;   /* Will give us a 1 if x is non-zero or 0 if zero */

Is there a similar way in python?

Zenon
  • 1
  • 1
  • 1
    `oneorzero = 0 if x == 0 else 1` – Tom Dalton Jun 11 '21 at 13:49
  • 6
    `oneorzero = int(bool(x))` should do the trick – Diptangsu Goswami Jun 11 '21 at 13:50
  • 1
    I'd say `bool(x)` is pretty decent too. It does not give `int` type, but in Python, there is barely any difference. And it does not obstruct clarity much. – Superior Jun 11 '21 at 13:55
  • A boolean is an integer. `isinstance(True, int)` will give you `True`. – Matthias Jun 11 '21 at 13:58
  • Does this answer your question? [if x>=1, then 1, otherwise 0, as pure math equation?](https://stackoverflow.com/questions/66516120/if-x-1-then-1-otherwise-0-as-pure-math-equation) – asd-tm Jun 11 '21 at 14:04
  • @asd-tm: I don't think so. I was looking more into a bit operations answer like the C solution I describe, and also negative numbers should return a 1. My intention was to avoid branching operations caused by conditions. But I am not sure if a solution like `int(not(not(x)))` in python is better (in terms of speed) than the solution I accepted. – Zenon Jun 11 '21 at 14:30
  • @Zenon if you care about speed...don't use Python. – Matt Jun 11 '21 at 14:30
  • @Matt: it's for quick prototyping to test different methods, but speed is still important although I admit optimizing such a thing is an overkill. – Zenon Jun 11 '21 at 14:38

2 Answers2

4

I lately used something like

oneorzero = 1 if x else 0

which has the benefit that x is just tested for its truth value and doesn't necessarily need to be 0 for "false".

glglgl
  • 89,107
  • 13
  • 149
  • 217
2

you can use tenrary operators.


oneorzero = 1 if x else 0

George Imerlishvili
  • 1,816
  • 2
  • 12
  • 20