Created
May 24, 2020 15:58
-
-
Save aljorhythm/31b6ef331f3a1b718c1c530361a4301e to your computer and use it in GitHub Desktop.
python generators for iteration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def isPrefixOfWord(sentence, searchWord): | |
""" | |
:type sentence: str | |
:type searchWord: str | |
:rtype: int | |
""" | |
words = sentence.split(" ") | |
for i, word in enumerate(words): | |
if word.startswith(searchWord): | |
return i + 1 | |
return -1 | |
def isPrefixOfWord_short(sentence, searchWord): | |
""" | |
:type sentence: str | |
:type searchWord: str | |
:rtype: int | |
""" | |
try: | |
return 1 + next(i for i, w in enumerate(sentence.split(" ")) if w.startswith(searchWord)) | |
except: | |
return -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment