I am writing a program that accepts a sentence and then prints out the longest line, this is what I have so far, but I am lost on what the x variable should be equal to. Any help is appreciated, thanks.

sent=raw_input('Enter sentence:')
splicedsent=sent.split(" ")
longestword=splicedsent[0]
if x in range(splicedsent[1:])>splicedsent[0]:
print x
else:
longestword=splicedsent[0]
print "Longest word:", longestword

Dani AI

Generated

Nice progress so far. Two quick correctness notes that explain why your earlier attempt kept returning the last word: (1) after you update the current best word, you must also update the tracked length (as pointed out), and (2) split(" ") produces empty strings if there are multiple spaces; prefer split() so you only get real words. Also, there is no need for an x variable here; just keep the current best word and its length. Debug prints like suggested are perfect for verifying the loop logic.

If you want a concise approach that also handles punctuation and ties, tokenize first and then filter by the maximum length. This version prints all longest words (deduplicated, order preserved):

import re

sent = input("Enter sentence: ").strip()  # use raw_input(...) on Python 2
words = re.findall(r"[A-Za-z']+", sent)   # keeps words like don't
if not words:
    print("No words found.")
else:
    maxlen = max(map(len, words))
    winners = [w for w in dict.fromkeys(w for w in words if len(w) == maxlen)]
    print("Longest word(s): " + ", ".join(winners))

Notes and options:

  • If you do not want to drop duplicates, replace the dict.fromkeys(...) line with a plain list comprehension so repeated longest words are listed multiple times.
  • Want just one word? longest = max(words, key=len) returns the first longest word it encounters; ties go to the earliest word.
  • If you consider hyphenated words one token, tweak the regex to r"[A-Za-z'-]+". If you prefer to keep punctuation attached, skip re and use words = sent.split() instead.

Recommended Answers

All 11 Replies

You will need to examine the length of each word to determine its length. The current compare is doing a lexicographic compare not a length compare. Use len()

I have worked on this for a few hrs and this is what I now have, it still isnt right. I am not sure what is wrong, and what to set the variable x to. Thanks a lot for all the help

sent=raw_input('Enter sentence:')
splicedsent=sent.split(" ")
longestword=splicedsent[0]
if x in len(splicedsent[1:])>splicedsent[0]:
print x
else:
longestword=splicedsent[0]
print "Longest word:", longestword

The line:

if x in len(splicedsent[1:])>splicedsent[0]:

should be something like:

if len(splicedsent[1:]) > len(splicedsent[0]):

At this point, you have determined that the 2nd word is longer than the first word. To make this more generic and be able to deal with the case where there are more than two words in the sentence, you need to iterate over them using a for loop or something similar.

Or to give a more direct hint:

longestLength = 0
longestWord = ''

for word in splicedsent:
    if len(word) > longestLength:
        # Update longestLength and longestWord

The minute you sent that reply, I figured that out. But after the if statement I set longestword=word, but that is wrong, and prints the first item in the list as the longestword. This is what I have, it now makes the last word the longest? I am still confused, thanks for all of your help so far.

sent=raw_input('Enter sentence:')
splicedsent=sent.split(" ")
longestLength = 0
longestword = ''
for word in splicedsent:
    if len(word) > longestLength:
        longestword=word
print "Longest word:", longestword

it now makes the last word the longest?

Add some print statements and you should be able to see what is going on.

for word in splicedsent:
    print "\ncomparing word %s, length=%d, longest=%s" % \
             (word, len(word), longestLength)
    if len(word) > longestLength:
        longestword=word
        print "length > longest is true"

ok so that compares each word entered to the longest, which is set as zero. But I need to make longest the length of the first word that I enter, and compare it to the rest, if the compared word is longer than the stored word, then it replaces the stored word and so on, until it has checked all the words entered and it prints the word that is stored. But I am still lost about how to do that.

Try this ...

for word in splicedsent:
    if len(word) > longestLength:
        longestword=word
        longestLength = len(word)

Thanks a ton, but if there are two or more words with the same length, would you use a similar code to print multiple words?
I tried doing this, but it is evaluating it as true, because it is a boolean statement, but I am not sure how to set the multiple words equal to something, any ideas...this is what I have:

sent=raw_input('Enter sentence:')
splicedsent=sent.split(" ")
longestLength = 0
longestWords = ''
for word in splicedsent:
    if len(word) > longestLength:
        longestWords=word
        longestLength=len(word)
    if longestWords > 1:
        longestWords=longestWords > 1        
print "Longest word(s):", longestWords

You need to use a list for holding the longest words if you need to capture multiple words of the same length.

sent=raw_input('Enter sentence:')
splicedsent=sent.split(" ")
longestLength = 0
longestWords = []
for word in splicedsent:
    if len(word) > longestLength:
        longestWords = [word]
        longestLength = len(word)
    elif len(word) == longestLength:
        longestWords.append(word)
print "Longest word(s):", longestWords

Or if you to format the longestWords a bit better than just dumping the list:

print "Longest word(s):", ', '.join(longestWords)

thanks a ton for all of your help it is greatly appreciated

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.