# Program to find number of subsequence that are present inside word list in python

PythonServer Side ProgrammingProgramming

Suppose we have a list of words and a string s, we have to find the number of strings in the words list that are subsequences of s.

So, if the input is like words = ["xz", "xw", "y"] s = "xyz", then the output will be 2, as "xz" and "y" are subsequences of "xyz".

To solve this, we will follow these steps −

• ans := 0
• d := an empty map
• for each word in words, do
• insert word at the end of d[word]
• for each c in s, do
• l := d[c]
• d[c] := a new list
• for each word in l, do
• if size of word is 1, then
• ans := ans + 1
• otherwise,
• insert substring of word[from index 1 to end] at the end of d[word]
• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

from collections import defaultdict
class Solution:
def solve(self, words, s):
ans = 0

d = defaultdict(list)
for word in words:
d[word].append(word)

for c in s:
l = d[c]
d[c] = []

for word in l:
if len(word) == 1:
ans += 1
else:
d[word].append(word[1:])
return ans
ob = Solution()
words = ["xz", "xw", "y"]
s = "xyz"
print(ob.solve(words, s))

## Input

["xz", "xw", "y"], "xyz"

## Output

2