Skip to content

Instantly share code, notes, and snippets.

@aljorhythm
Created May 24, 2020 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aljorhythm/31b6ef331f3a1b718c1c530361a4301e to your computer and use it in GitHub Desktop.
Save aljorhythm/31b6ef331f3a1b718c1c530361a4301e to your computer and use it in GitHub Desktop.
python generators for iteration
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