Program to find length of longest diminishing word chain in Python?


Suppose we have a list of valid words, and have a string s also, we have to find the length of the longest chain of diminishing words that can be generated by starting at s and removing single letters and still make valid words.

So, if the input is like words = ["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"] s = "limit", then the output will be 4, as we can make the chain, starting from the word "limit", "limit" -> "limi" -> "lii" -> "li".

To solve this, we will follow these steps

  • Define a function solve() . This will take words, s

  • max_num := 0

  • for each i in words, do

    • if i is same as s, then

      • for j in range 0 to size of s, do

        • max_num := maximum of 1 + solve(words, s[from index 0 to j-1] concatenate s[from index j + 1 to end]) and max_num

  • return max_num


Example

 Live Demo

class Solution:
   def solve(self, words, s):
      max_num = 0
      for i in words:
         if i == s:
            for j in range(len(s)):
               max_num = max(1 + self.solve(words, s[:j] + s[j + 1 :]), max_num)
      return max_num

ob = Solution()
words = ["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"]
s = "limit"
print(ob.solve(words, s))

Input

["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"],"limit"

Output

4

Updated on: 10-Nov-2020

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements