
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Subsequences in Word List using Python
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[0]]
- 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[1]]
- if size of word is 1, then
- return ans
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict class Solution: def solve(self, words, s): ans = 0 d = defaultdict(list) for word in words: d[word[0]].append(word) for c in s: l = d[c] d[c] = [] for word in l: if len(word) == 1: ans += 1 else: d[word[1]].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
Advertisements