A string is given, in which words and numbers are separated by a space. It is necessary to find three words in a row in this line.

def m (words) : a = 0 for w in words.split() : pass while w.isalpha() is True : a += 1 if a == 3 : return True else : return False # вот на этом я застрял. 
  • My code does not work gives False all the time. - D.Ryksd
  • Give the source data for your example, what are you testing? - Alexcei Shmakov
  • On IDLE I'm testing. Suppose words = 'ddd ddd ddd 55 88', should output True in theory and displays False. - D.Ryksd
  • And if you remove the bottom two lines, it will output True - D.Ryksd

3 answers 3

Here is the function that does what you need.

 def m (words) : count = 0 for w in words.split() : if w.isalpha() : count += 1 if count == 3 : return True else : count = 0 return False # вот на этом я застрял. 

The function runs according to the words in the loop. If the word consists of letters (the isalpha () function checks it), then it accumulates a counter (incrementing the variable), otherwise it resets it to zero. If the counter has accumulated from three words, then we have found words in line 3 in a row.

  • I would remove the second if in the then section of the first to avoid unnecessary checks. - user194374
  • @kff, of course, thanks for the advice. And he did. - Alexcei Shmakov

The problem can be solved, for example, as follows:

 def three_words(s): t = s.split() start = end = 0 while end < len(t): if t[end].isalpha(): if end - start >= 2: return t[start:end + 1] end += 1 else: start = end = end + 1 

The method will return a list of the first three words encountered in a row or None if there is no such group of words.

    To find three words in a row in a line and display them:

     words = text.split() for triple in zip(words, words[1:], words[2:]): if all(s.isalpha() for s in triple): print(*triple) break else: print("not found") 

    This is straightforward for Python programmer code, but it performs unnecessary copying and comparison.

    Here is the code that is similar to the solution that uses the count from the @Alexcei Shmakov answer — this option prints the three words itself, and not only is it on the line, like the count solution:

     triple = [] for s in text.split(): if s.isalpha(): triple.append(s) if len(triple) == 3: print(*triple) break else: del triple[:] # empty else: print("not found") 

    In order not to create a possibly large list of strings separated by a space, you can use regular expressions:

     import re m = re.search(r'\s+'.join([r'[^\d\s]+']*3), text) print(m.group() if m else "not found") 

    This option looks for characters that are not numbers, spaces (which is suitable for setting the problem in question), since the re module does not support the analog str.isalpha . regex module supports \p{Letter} .

    Measurements can show whether there is a performance difference for the actual input.