![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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