-2

I'm using the numexpr module for python. I'm trying to run the next code snippet:

import numexpr as ne


def main():
    result = ne.evaluate('where((1 > 9) & (where(1 > 9, 9, 1) == 0), 2, 3)')
    print(f'Result: {result}')


if __name__ == "__main__":
    main()

But numexpr throws the following error:

TypeError: unsupported operand type(s) for &: 'bool' and 'ConstantNode'

However, if I extract the conflicting section in a separate expression, it works.

def main():
    intermediate_result = ne.evaluate('where(1 > 9, 9, 1) == 0')
    result = ne.evaluate(f'where((1 > 9) & {intermediate_result}, 2, 3)')
    print(f'Result: {result}')

But the idea is to have a single expression. Does anyone know how I could rewrite this formula to make it work?

Thanks in advance.

  • 1
    Do you want the & to be a logical AND? I am assuming you do, in which case you probably just need a double ampersand (&&), otherwise you're doing to do a bitwise AND, which is an arithmetic operation and "True" isn't a number in python. – Tom Lubenow Apr 17 '19 at 17:44
  • @TomLubenow: what does it mean ""True" isn't a number in python"? `True` is a `bool` which is a subclass of `int`, `int` is a numeric type -> `True` is a number – Azat Ibrakov Apr 17 '19 at 18:13
  • @TomLubenow `True` is a keyword that means `1` – Alec Apr 17 '19 at 18:53
  • You guys appear to be right (you learn something new every day) but I would still consider it a bad idea to do arithmetic on booleans. – Tom Lubenow Apr 17 '19 at 19:00
  • Thanks @TomLubenow, the `and` operator worked. Sorry but the documentation never mention that operator. – Victor Del Rio Apr 17 '19 at 19:13

1 Answers1

1

& is the bitwise and operator. Why not just use and?

Alec
  • 8,529
  • 8
  • 37
  • 63