0

I was wondering how to have an if statement in python that will react to any 3 out of 5 conditions being true to make the if statement true.

    if (a>2) and (b>3) and (c>2) and (d>6) and (e>4):
       list.append(True)

This code would add true to the array "list" if all 5 conditions are met but I was wondering how to get it to work if any 3 of the 5 are true to then append true to "list"?

2 Answers2

6

How about this?

values = [a>2, b>3, c>2, d>6, e>4]
if sum(values) >= 3:
    list.append(True)

Just copying what @Blckknght said in the comments b/c I can't explain it better. This works because:

True is equal to 1 and False is equal to 0 (the bool class is a subclass of int)

sum sums numbers, so you check for a sum of booleans >= 3!

Tom
  • 8,310
  • 2
  • 16
  • 36
  • 2
    You might want to explain that this works because `True` is equal to `1` and `False` is equal to `0` (the `bool` class is a subclass of `int`). – Blckknght Jul 10 '20 at 18:23
0

Similar to @Tom 's answer but with using tuples that leads to (maybe) faster construction, garbage collection and (maybe) a nicer syntax.

if sum((a > 2, b > 3, c > 2, d > 6, e > 4)) >= 3:
        lst.append(True)
Jake Schmidt
  • 1,558
  • 9
  • 16
  • The syntax might be nicer (depending on your preferences) but I doubt it will be faster. – Mark Ransom Jul 10 '20 at 18:43
  • Nothing is referencing the tuple being created external to the ```sum``` function, so as far as reference counting that is a plus. I don't know enough about tuples in python (I'm more of a c++ guy) but I'd imagine that an immutable data structure is cheaper to construct than a list. Edit: I looked it up, and it is *usually* indeed *slightly* faster: https://stackoverflow.com/questions/68630/are-tuples-more-efficient-than-lists-in-python – Jake Schmidt Jul 10 '20 at 18:48