- Trending Categories
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 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
Advertisements