Reputation: 33
I'm new to programming and would like to ask in Python if I have a m-list of conditions and would like to know if n of these are true in a if statment:
eg:
if (a == b) or (c == d) or (e == f):
would return 1,2 or all 3 true, but I want to know if only 2 of these are true
eg:
if ((a == b) and ((c == d) or (e == f))) or (((a == b) or (c == d)) and (e == f)) or (((a == b) or (e == f)) and (c == d)):
is there any easier way to do this? What to do if (m,n) is large?
Thanks
Upvotes: 3
Views: 312
Reputation: 76887
If the conditions are equality tests which are guaranteed to return either True or False, then of course you can use @Tim's answer.
Otherwise, you can work out a slight variant using a list of conditions which will work with any conditional statement
conditions = [a == b,
c == d,
e == f,
e,
f is None]
And then do a simple sum using:
sum(1 if cond else 0 for cond in conditions) >= m
Note that this approach works if the conditions are boolean in nature as well.
Upvotes: 2
Reputation: 336158
Since True
is actually the integer 1
, you could do
if (a==b) + (c==d) + (e==f) == 2:
For larger sets of conditions, you could use sum()
:
conditions = [a==b, c==d, d==e, f==g, ...]
if sum(conditions) == 3:
# do something
Upvotes: 4