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