

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 all words which share same first letters in Python
Suppose we have a list of words in lowercase letters, we have to find the length of the longest contiguous sublist where all words have the same first letter.
So, if the input is like ["she", "sells", "seashells", "on", "the", "seashore"], then the output will be 3 as three contiguous words are "she", "sells", "seashells", all have same first letter 's'.
To solve this, we will follow these steps −
- maxlength := 0
- curr_letter := Null, curr_length := 0
- for each word in words, do
- if curr_letter is null or curr_letter is not same as word[0], then
- maxlength := maximum of maxlength, curr_length
- curr_letter := word[0], curr_length := 1
- otherwise,
- curr_length := curr_length + 1
- if curr_letter is null or curr_letter is not same as word[0], then
- return maximum of maxlength and curr_length
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, words): maxlength = 0 curr_letter, curr_length = None, 0 for word in words: if not curr_letter or curr_letter != word[0]: maxlength = max(maxlength, curr_length) curr_letter, curr_length = word[0], 1 else: curr_length += 1 return max(maxlength, curr_length) ob = Solution() words = ["she", "sells", "seashells", "on", "the", "seashore"] print(ob.solve(words))
Input
["she", "sells", "seashells", "on", "the", "seashore"]
Output
3
- Related Questions & Answers
- Program to find length of longest contiguous sublist with same first letter words in Python
- Interchanging first letters of words in a string in JavaScript
- Program to find out the minimum path to deliver all letters in Python
- Program to find number of quadruples for which product of first and last pairs are same in Python
- Program to check whether there is any pair of words which are almost same in Python
- Python Program that Displays which Letters are in the First String but not in the Second
- Program to find a sublist where first and last values are same in Python
- Python Program that Displays which Letters are Present in Both the Strings
- Program to count number of words we can generate from matrix of letters in Python
- Program to find smallest index for which array element is also same as index in Python
- Program to find list of all possible combinations of letters of a given string s in Python
- Find whether all tuple have same length in Python
- Program to find minimum deletion cost to avoid repeating letters in Python
- Regex in Python to put spaces between words starting with capital letters
- Python program to find uncommon words from two Strings
Advertisements