0

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?

1
  • 3
    Then you need to return True as soon as you find a match. Commented Aug 17, 2022 at 15:23

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

split splits by the space by default
@funnydman OP added it. Maybe he wants it for clarity. I don't think it's my job to change it, so I will leave it in the current implementation.
1

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_))
     

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.