Reputation:
function should change sentence to list of words separated by space and than checks if there are 3 words in a row containing only letters
def words(str):
slowa = str.split(str)
if len(slowa) < 2:
return 0
else:
for x in range(2,len(slowa)):
if slowa[x].isalpha() and slowa[x-1].isalpha() and slowa[x-2].isalpha():
return 1
else:
return 0
fe: words("one one one") returns true
but words("one one 1 one one one 1 one one 1 one one 1") returns false. Any tips why this happens?
Upvotes: 0
Views: 130
Reputation: 1123400
Because you return 0
on the first failed test in your loop. The loop exits with a return
, you never tested the rest of your list. "one one 1"
is not a match, you need to continue looping until you find the "one one one"
sequence later on.
Move the return 0
to after the for
loop, only when you have tested all positions do you know for sure there is nothing matching:
for x in range(2,len(slowa)):
if slowa[x].isalpha() and slowa[x-1].isalpha() and slowa[x-2].isalpha():
return 1
return 0
Note that your test for the length is redundant; the range()
will simply be empty for shorter sequences:
def words(inputstring):
slowa = inputstring.split()
for x in range(2, len(slowa)):
if slowa[x].isalpha() and slowa[x-1].isalpha() and slowa[x-2].isalpha():
return 1
return 0
Upvotes: 1