I have some code below, for a given name that matches pattern with 2 lower case letters (such as ‘aa’), the valid name can be V-aa
or X-aa
def verify_helper(valid_name): do something return true #meaning the name starts either V or X is valid def example(name): if re.match("^[a-z]{2}$", name) valid_name_1 = f"V-{name}" valid_name_2 = f"X-{name}" verify_helper(valid_name_1) verify_helper(valid_name_2)
My question is: can I do something like:
def example(name): if re.match("^[a-z]{2}$", name) valid_name_1 = f"V-{name}" valid_name_2 = f"X-{name}" if valid_name matches either 'V-' or 'X-' call the first function
Advertisement
Answer
From your description, I assume that verify_helper()
is computationally expensive regardless of names
being valid
.
Now you want to optimize the code, by having verify_helper()
only execute for valid names
.
If that’s the case, you could have the condition inside verify_helper()
, like this.
def verify_helper(name): if re.match("^[XV]-[a-z]{2}", name): # checks for valid names like X-aa, X-aa11, V-bb etc. # do something only for valid names return True else: return False