
- 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 longest contiguous sublist with same first letter words in Python
Suppose we have a list of lowercase alphabet strings called words. We have to find the length of the longest contiguous sublist where the first letter of each words have the same first letter.
So, if the input is like words = ["she", "sells", "seashells", "on", "the", "sea", "shore"], then the output will be 3, the longest contiguous sublist is ["she", "sells", "seashells"]. The first letter for each words is 's'.
To solve this, we will follow these steps −
cnt := 1
maxcnt := 0
prev_char := blank string
for each word in words, do
if prev_char is empty, then
prev_char := first letter of word
otherwise when prev_char is same as first letter of word, then
cnt := cnt + 1
otherwise,
prev_char := first letter of word
cnt := 1
maxcnt := maximum of maxcnt and cnt
return maxcnt
Example
Let us see the following implementation to get better understanding
def solve(words): cnt = 1 maxcnt = 0 prev_char = "" for word in words: if prev_char == "": prev_char = word[0] elif prev_char == word[0]: cnt += 1 else: prev_char = word[0] cnt = 1 maxcnt = max(maxcnt, cnt) return maxcnt words = ["she", "sells", "seashells", "on", "the", "sea", "shore"] print(solve(words))
Input
["she", "sells", "seashells", "on", "the", "sea", "shore"]
Output
3
- Related Articles
- Program to find length of contiguous strictly increasing sublist in Python
- Program to find length of longest sublist with given condition in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find length of longest sublist with value range condition in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find length of longest strictly increasing then decreasing sublist in Python
- Program to find length of longest sublist whose sum is 0 in Python
- Program to find length of shortest sublist with maximum frequent element with same frequency in Python
- Program to find length of longest contiguously strictly increasing sublist after removal in Python
- Program to find length of longest sublist containing repeated numbers by k operations in Python
- Python Program to Count of Words with specific letter
- Program to find a sublist where first and last values are same in Python
- Program to find all words which share same first letters in Python
