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
JavaScript
x
15
15
1
def verify_helper(valid_name):
2
do something
3
return true #meaning the name starts either V or X is valid
4
5
6
def example(name):
7
8
if re.match("^[a-z]{2}$", name)
9
valid_name_1 = f"V-{name}"
10
valid_name_2 = f"X-{name}"
11
12
verify_helper(valid_name_1)
13
verify_helper(valid_name_2)
14
15
My question is: can I do something like:
JavaScript
1
9
1
def example(name):
2
3
if re.match("^[a-z]{2}$", name)
4
valid_name_1 = f"V-{name}"
5
valid_name_2 = f"X-{name}"
6
7
if valid_name matches either 'V-' or 'X-'
8
call the first function
9
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.
JavaScript
1
7
1
def verify_helper(name):
2
if re.match("^[XV]-[a-z]{2}", name): # checks for valid names like X-aa, X-aa11, V-bb etc.
3
# do something only for valid names
4
return True
5
else:
6
return False
7