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

PythonServer Side ProgrammingProgramming

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


 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))


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


Updated on 10-Nov-2020 09:08:50