0

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 Answers4

3

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
Asocia
  • 5,935
  • 2
  • 21
  • 46
  • 1
    And you don't really need those `r`s before your strings but I included them just in case you want to modify your regex in future. – Asocia Jun 20 '20 at 19:56
2

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

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.

formicaman
  • 1,317
  • 3
  • 16
  • 32
  • 1
    That's what I thought at first, but that won't increment i more than once. For the original code, 'experience,programmer' would increment i twice. – Aaron Bentley Jun 20 '20 at 19:54
0

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']])
alani
  • 12,573
  • 2
  • 13
  • 23