
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find length of shortest supersequence in Python
Suppose we have two strings s and t. We have to find the length of the shortest string that has both s and t as subsequences.
So, if the input is like s = "pipe" t = "people", then the output will be 7, as one possible supersequence is "pieople".
To solve this, we will follow these steps −
m := size of s, n := size of t
table := a table of size (n + 1) x (m + 1) and fill with 0
for i in range 0 to m, do
for j in range 0 to n, do
if i is same as 0 or j is same as 0, then
table[i, j] := 0
otherwise,
if s[i - 1] is same as t[j - 1], then
table[i, j] := 1 + table[i - 1, j - 1]
otherwise,
table[i, j] = maximum of table[i, j - 1] and table[i - 1, j]
return m + n - table[m, n]
Example
Let us see the following implementation to get better understanding −
class Solution: def solve(self, s, t): m = len(s) n = len(t) table = [[0 for i in range(n + 1)] for j in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: table[i][j] = 0 else: if s[i - 1] == t[j - 1]: table[i][j] = 1 + table[i - 1][j - 1] else: table[i][j] = max(table[i][j - 1], table[i - 1][j]) return m + n - table[m][n] ob = Solution() s = "pipe" t = "people" print(ob.solve(s, t))
Input
"pipe", "people"
Output
7
- Related Articles
- Shortest Common Supersequence in C++
- Program to find shortest cycle length holding target in python
- C++ Program to Find the Shortest Supersequence that Contains Two or more Sequences as Subsequences
- Program to find length of shortest sublist with maximum frequent element with same frequency in Python
- Program to find distance of shortest bridge between islands in Python
- Program to find length of longest matrix path length in Python
- Python - Filter Supersequence Strings
- Program to find minimum length of lossy Run-Length Encoding in Python
- Program to find shortest string after removing different adjacent bits in Python
- Program to find maximum length of k ribbons of same length in Python
- Program to find out the shortest path to reach the goal in Python
- Program to find shortest subarray to be removed to make array sorted in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest consecutive sequence in Python

Advertisements