# Occurrences After Bigram in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose there are words given. These are first and second, consider occurrences in some text of the form "first second third", here second comes immediately after the first, and third comes immediately after the second.

For each such cases, add "third" into the answer, and show the answer. So if the text is like “lina is a good girl she is a good singer”, first = “a”, second = “good”, the answer will be [girl, singer]

To solve this, we will follow these steps −

• text := split the string by spaces
• res is an empty list
• for i := 0 to size of text – 1
• if i + 2 < length of text, and text[i] = first and text[i + 1] = second, then append text[i + 2] into res
• return res

## Example

Let us see the following implementation to get better understanding −

Live Demo

class Solution(object):
def findOcurrences(self, text, first, second):
text = text.split(" ")
res = []
for i in range(len(text)):
if i+2<len(text) and text[i] ==first and text[i+1]==second:
res.append(text[i+2])
return res
ob1 = Solution()
print(ob1.findOcurrences("lina is a good girl she is a good
singer","a","good"))

## Input

"lina is a good girl she is a good singer"
"a"
"good"

## Output

['girl', 'singer']
Updated on 28-Apr-2020 17:45:32