0

I need to check if any of my variables are larger than a threshold.

Currently I'm doing if b > a or c > a or d > a ... etc

Is there a faster way to write this (similar to if a in {b, c, d}:?)

dennlinger
  • 9,890
  • 1
  • 42
  • 63
  • `if any(i > a for i in {b, c, d}):` – Green Cloak Guy Oct 12 '21 at 13:28
  • 7
    `if max(b, c, d) > a:` - doesn't have short-circuiting, but it does what you want. – kaya3 Oct 12 '21 at 13:29
  • 1
    @kaya3 Oh very smart! – flakes Oct 12 '21 at 13:30
  • 1
    `any(map(a.__lt__, (b,c,d)))` to have it all covered :D – user2390182 Oct 12 '21 at 13:35
  • @schwobaseggl That will fail when `a = 5` and `b = 4.0`, because `a.__lt__(b)` is `NotImplemented`, which is truthy. – kaya3 Oct 12 '21 at 13:38
  • @schwobaseggl The only way to get short-circuit evaluation of `b`, `c` and `d`, other than using `or` like the original code, would be to defer them with lambdas. But the question says "any of my variables" so I think this isn't an issue. – kaya3 Oct 12 '21 at 13:40
  • The map version provided by @schwobaseggl looks way faster. – MSH Oct 12 '21 at 13:44
  • 1
    @MSH The `map` version is also not correct in some cases, see my comment. – kaya3 Oct 12 '21 at 13:44
  • 1
    @schwobaseggl If `<` causes an error then what you are trying to do doesn't make sense. But if `<` fails then it raises an exception - it does not silently fail by producing the wrong result, which would be far more dangerous. – kaya3 Oct 12 '21 at 13:55
  • @kaya3 Touché. I am advocating for the functional devil here anyway, being a fan of the generator expression :-) – user2390182 Oct 12 '21 at 14:00

1 Answers1

1

I'm not sure of the best approach, but I know the any built-in function can help with this:

numbers = [8, 9, 4]
threshold = 3

if any(n > threshold for n in numbers):
    print("At least one is above the threshold")
else:
    print("None are above the threshold")
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
  • 1
    No need for the condition, `any` already returns a boolean. Just do `print(any(...))` – Tomerikoo Oct 12 '21 at 13:55
  • @Tomerikoo I think the point here is to demonstrate how to use `any` in an `if` statement, not to demonstrate how to print the boolean result of `any`. – kaya3 Oct 12 '21 at 13:56
  • @kaya3 yes, that sounds about right. I did realize the `print(any(...))` would be much cleaner though. – rv.kvetch Oct 12 '21 at 13:57
  • 1
    @kaya3 yep in the context of the question you are right, I just find it hard to look at `if ...: print(True) else: print(False)`... – Tomerikoo Oct 12 '21 at 13:58
  • @Tomerikoo Fair enough, I edited to make it more aesthetically pleasing. – kaya3 Oct 12 '21 at 14:00