Karthi1234 Karthi1234 -4 years ago 84
Python Question

python check for either n out of m methods return value is true

I have written 5 methods which do some stuffs and will return

based on the stuffs. By calling those method I will assign the return value to separate variables and I want to compare those return values and if 5 out of 3 methods return True then I have to do some other stuffs else different stuffs.

def method1():
# stuffs
return True

def method2():
return False

def method3():
return True

def method4():
return True

def method5():
return True

var1 = method1()
var2 = method2()
var3 = method3()
var4 = method4()
var5 = method5()

now I have to do comparison for these variable values and out of 3 are True then have to do some stuffs.

I found
in if statements but that is not suitable for my situation. So is there any other function which will help me to take it forward?

Looking for generic way which should work on python 2 and 3.

Answer Source

Store teh result of all your methods in a list. Count the number of True!

if [method1(),method2(),method3(),method4(),method5()].count(True) == n:

This should do! Hope it helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download