Is it possible to reduce the amount of lines in the method find_indexes to just 1 line using an if/else statement like as seen in the return statement?
def find_indexes(sentence, target):
indexes = [index for index, x in enumerate(sentence.split()) if target == x]
return indexes if indexes else False
target = 'dont'
sentence = 'we dont need no education we dont need no thought control no we dont'
print(find_indexes(sentence, target))
>> [1, 6, 13]
print(find_indexes(sentence, 'johndoe'))
>> False
I'm looking to change the method to something like this, without the need to write the comprehension twice:
def find_indexes(sentence, target):
return [index for index, x in enumerate(sentence.split()) if target == x] \
if [index for index, x in enumerate(sentence.split()) if target == x] else False
Write a procedure that takes a string of words separated by spaces (assume no punctuation or capitalization), together with a ”target” word, and shows the position of the target word in the string of words.
For example, if the string is:
we dont need no education we dont need no thought control no we dont
and the target is the word:
”dont”
then your procedure should return the list 1, 6, 13 because ”dont” appears at the 1st, 6th, and 13th position in the string. (We start counting positions of words in the string from 0.) Your procedure should return False if the target word doesn’t appear in the string
return [index for index, x in enumerate(sentence.split()) if target == x] or FalseFalseis fairly pointless. Just return the listcomp itself; if it's empty, it will behave as a falsy value, and 99% of the time, that's fine (or better than fine, since it still acts like a sequence, so you can blindly do aforloop over the result and it will simply not do anything). It's generally not Pythonic to insist on actualTrue/Falsevalues, just allow implicit truthiness testing to do its thing.Falseis a better return value than[]? An empty list will be treated asFalsein any context where you should be using a Boolean value (and I'm explicitly countingfoo == Falseas something you should not be doing).returnalistlet it alwaysreturnone, not a mixture oflists andbools