A Python program to print the longest consecutive chain of words of the same length from a sentence

Question:

I got tasked with writing a Python script that would output the longest chain of consecutive words of the same length from a sentence. For example, if the input is "To be or not to be", the output should be "To, be, or".

text = input("Enter text: ")
words = text.replace(",", " ").replace(".", " ").split()
x = 0
same = []
same.append(words[x])

for i in words:
    if len(words[x]) == len(words[x+1]):
        same.append(words[x+1])
        x += 1
    elif len(words[x]) != len(words[x+1]):
        same = []
        x += 1
    else:
        print("No consecutive words of the same length")

print(words)
print("Longest chain of words with similar length: ", same)

In order to turn the string input into a list of words and to get rid of any punctuation, I used the replace() and split() methods. The first word of this list would then get appended to a new list called "same", which would hold the words with the same length. A for-loop would then compare the lengths of the words one by one, and either append them to this list if their lengths match, or clear the list if they don’t.

if len(words[x]) == len(words[x+1]):
                         ~~~~~^^^^^
IndexError: list index out of range

This is the problem I keep getting, and I just can’t understand why the index is out of range.

I will be very grateful for any help with solving this issue and fixing the program. Thank you in advance.

Asked By: Dan_the_Man

||

Answers:

using groupby you can get the result as

from itertools import groupby
string = "To be or not to be"
sol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))
print(sol)
# 'To, be, or'
Answered By: sahasrara62

len() function takes a string as an argument, for instance here in this code according to me first you have to convert the words variable into a list then it might work.

Thank You !!!

Answered By: ISHAANT KUMAR SINGH
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.