How can i use just one if statement and include all these conditions in OR (python)

57 Views Asked by At

How can i use just one if statement and include all these conditions along with i++ based on each condition? (using & or etc)??

def validator_fn(value):
i=0
if re.search(r'experience',value.casefold()):
    i+=1
if re.search(r'programmer',value.casefold()):
    i+=1
if re.search(r'computer',value.casefold()):
    i+=1
if re.search(r'work',value.casefold()): #skill
    i+=1
if re.search(r'skill',value.casefold()):
    i+=1
if re.search(r'work',value.casefold()):
    i+=1
return i
4

There are 4 best solutions below

1
formicaman On

You could just do

if re.search('experience|programmer|computer|work|skill',value.casefold()):
    i+=1

You can use | ("or") to separate the patterns you want to search for.

1
sahinakkaya On

Create a loop:

def validator_fn(value):
    i = 0
    for s in [r'experience', r'programmer', r'computer', ...]:
        if re.search(s, value.casefold()):
            i += 1
    return i
0
chepner On

Apply all of them at once; i is just the number of them that return True.

def validator_fn(value):
    v = value.casefold()
    search_terms = ['experience', 'programmer', 'computer', 'work', 'skill', 'work']
    return sum(re.search(x, v) is not None for x in search_terms)

The sum works because True == 1 and False == 0, bool being a subclass of int.

0
alani On

You are just summing 1 for each one that matches, so can do something like:

def validator_fn(value):
    v = value.casefold()
    return sum([1 if re.search(pat, v) else 0
               for pat in ['experience', 'programmer', 'computer',
                           'work', 'skill', 'work']])