Elsa
Elsa

Reputation: 626

How to speed up nested for-loop logic in Python with Pandas, Numpy?

I would like to check out whether the field of table TestProjectcontains the parameter from the Client-side passed, nested for loop is ugly, is there any efficient and easy way to realize it? Thanks so much for any advice.

def test(parameter_a: list, parameter_b: list) -> bool:
    age = TestPeople.age
    project_code = TestProject.project_code
    if age is not None and age <= 16:
        for code in project_code:
            for p in parameter_a:
                if code[:len(p)] == p:
                    return False
    return True

Upvotes: 2

Views: 81

Answers (1)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

May be use itertools.product and all?

from itertools import product

def test(parameter_a: list, parameter_b: list) -> bool:
    age = TestPeople.age
    project_code = TestProject.project_code
    return (
        age is None 
        or age > 16
        or all(code.startswith(p) for code, p in product(project_code, parameter_a))
    )

EXPLANATION:

Here python tries to use short-circuit evaluation, so it will first check whether age is None, if it is, return True, otherwise check age > 16, if it is return True otherwise check if all the code, p pair match the condition code.startswith(p), if all the pairs pass the condition, return True, otherwise if any of the pair fail, return False immediately without checking the rest.

Upvotes: 4

Related Questions