python loop returning wrong answer

Question:

I want my loop to return true if any element of positions match with the string. First, i split to find the position needed. positions = ['founder','cto','partner'] and string is person_title = "director and cto at company"

My code:

def check_title(person_title,positions):

     person_titles = person_title.split(" ")
     for one_title in person_titles:
        for one_position_check in positions:
            if  one_position_check == one_title :
                answer = True
            
            else:
               answer = False
  return answer

The answer should be True but I am getting False. Any help?

Asked By: JM17

||

Answers:

Instead of setting answer to True, you should simply return True. Or else, after finding a match, a non-match might change answer to False again.

Do something like this.

def check_title(person_title,positions):

     person_titles = person_title.split(" ")
     for one_title in person_titles:
        for one_position_check in positions:
            if  one_position_check == one_title :
                return True

     return False
Answered By: Ryan Zhang

You could return True when match instead of looking through all and assign it to answer. But the simpler and faster would be using sets and checking for any intersection.

A better solution avoiding nests

positions = ['founder','cto','partner'] 
person_title = "director and cto at company"

def check_title(person_title: str, positions: list) -> bool:
     positions_ = set(positions)
     person_titles = {title for title in person_title.split()}
    
     return any(person_titles.intersection(positions_))
     
Answered By: Prayson W. Daniel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.