5
\$\begingroup\$

I have a function that compares the values of a tuple and a list of equal length. It compares each value in combination to see if it is equal to its respective value in the path or if the value in combination is '*', that is valid.

So for example: combination=('dog', 'cat', '*'), path=['dog', 'cat', 'bird'] would return True.

What I have is below and works fine, but is there a better way to accomplish this?

def _is_valid_combination(combination, path):
    """
    Check if the combination is valid for the path

    Keyword arguments:
    combination -- tuple of pattern combination
    path -- list of the actual path
    """
    index = 0
    for part in combination:
        if (part == path[index]) or ('*' == part):
            index += 1
            continue
        else:
            return False
    return True
\$\endgroup\$
4
\$\begingroup\$

If I've understood your code correctly, you can do this trivially with zip:

def _is_valid_combination(combination, path):
    """
    Check if the combination is valid for the path

    Keyword arguments:
    combination -- tuple of pattern combination
    path -- list of the actual path
    """
    return all(part == '*' or part == path_ for part, path_ in zip(combination, path))
\$\endgroup\$
1
  • \$\begingroup\$ Thank you @jonrsharpe! This is exactly the simple thing I was looking for! I overlooked all. Cheers! \$\endgroup\$
    – drincruz
    May 10 '15 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.