Mark Li
Mark Li

Reputation: 459

How to collect a set of boolean values and return a final test combining all with 'AND' in Python?

I am trying to defining a function to return True if the pattern matches all the strings in the list. Like, matchAll(pattern, list).

My initial try is:

import re

def matchAll(pattern, list): 
    list_truth = list
    for i in list:
       list_truth[i] = re.search(pattern,i) != none
    if False in list_truth:
       return False
    else:
       return True

Yet, it doesn't work. Please let me know which part I was doing wrong. Much thanks!

For example, the sample input / output look like:

print matchAll('a', ['a', 'ab', 'abc']) # True
print matchAll('a', ['a', 'ab', 'bc'])  # False
print matchAll('(ab)?', ['a', 'ab', 'abc'])  # True
print matchAll('.', ['a', 'ab', 'abc'])      # True
print matchAll('.{2,3}', ['a', 'ab', 'abc']) # False

I have also modified my code as:

import re
def matchAll(pattern, list1): 
list_truth = list
for i in list1:
    if re.search(pattern,i) != None:
        pass
    else:
        return False
return True

Yet, it returns the correct result but I don't think it is a good way to construct the function. Does anybody has idea on how can I optimize it? Thanks!

Upvotes: 2

Views: 146

Answers (2)

akaIDIOT
akaIDIOT

Reputation: 9231

You can use all for this (a Python builtin)

def match_all(pattern, items)
    return all(re.search(pattern, item) for item in items)

Also note that

  • list is a builtin type, avoid using that for your variable names
  • the return value for re.search is either an object (truthy) or None (falsy), which is why the return value can be used as booleany for all
  • camelCase is often replaced with snake_case in Python (an ominous PEP-8 debate)

Upvotes: 3

Bharel
Bharel

Reputation: 26900

You're looking for the all() function. Here you go:

import re

def matchAll(pattern, list_): 
    return all(re.search(pattern,i) for i in list_)

Upvotes: 3

Related Questions