This is and answer to one of the Vegaseat's recent projects for beginners.
I share my solution here because -as a begginer and do learn python as a hobby-
I need your feedback. So please tell me am I doing it the right way?
Thanks in advance for comments

from string import punctuation as punc

def find_longest(text):

    words = list(set(word.strip(punc) for word in text.split()))
    length = len(sorted(words,key=len,reverse=1)[0])
    longest= [word for word in words if len(word)==length]

    return longest, length



#=============== TEST ==============#

text = """Python is probably one of the few programming languages which is both simple and
powerful. This is good for both and beginners as well as experts, and more importantly, is
fun to program with. This book aims to help you learn this wonderful language and show
how to get things done quickly and painlessly - in effect 'The Perfect Anti-venom to your
programming problems'."""

wordlist, length = find_longest(text)
print "Longest Word's Length: %d" %length
print "Longest Word(s): %s" %(str(wordlist))

Dani AI

Generated

Good set of solutions and a useful learning thread — 's starter, 's itertools idea, 's max trick and ’s simple use of max(..., key=len) cover the usual approaches. A few practical points that often trip beginners, plus a compact, robust alternative.

takewhile clarification and common gotchas

  • itertools.takewhile yields elements from the start of the iterable while the predicate is True; it does not skip the first match. If it produced an empty result, likely causes are: the list actually began with an empty token (e.g. '' after aggressive strip()), words was empty, or the iterator was inspected without materializing (in some contexts you must convert the takewhile iterator to list(...) to see contents). Also beware that calling set() before inspecting order removes duplicates and can change what you expect to see when debugging.

robust streaming tokenizer (handles punctuation, hyphens, apostrophes)

  • Use a simple regex to extract word-like tokens, normalize case, and do a single-pass scan that keeps only the current longest words. This avoids building and sorting the whole list and deals explicitly with hyphenated or quoted tokens.
import re

def longest_words_stream(text, allow_hyphen=True):
    pattern = r"[A-Za-z0-9'-]+" if allow_hyphen else r"[A-Za-z0-9']+"
    max_len = 0
    longest = set()
    for m in re.finditer(pattern, text):
        w = m.group(0).strip("'-").lower()
        if not w:
            continue
        L = len(w)
        if L > max_len:
            max_len = L
            longest = {w}
        elif L == max_len:
            longest.add(w)
    return sorted(longest), max_len

notes and trade-offs

  • Decide policy for hyphens/apostrophes (keep them, split them, or remove them) up front — the sample text’s “Anti-venom” shows why that matters. For true Unicode-aware word boundaries use a library built for Unicode segmentation. The streaming approach is O(n) and memory-friendly for large inputs.

Recommended Answers

All 7 Replies

Your code is actually very nice for beginner!

I would slightly rearrange the calling the functions and do itertools.takewhile from sorted wordlist to rechecking whole word list.

from string import punctuation as punc
from itertools import takewhile

def find_longest(text):
    """ find length of longest word and what are those words in text

    """
    words = sorted(set(word.strip(punc) for word in text.split()), key=len, reverse=True)
    length = len(words[0])
    longest = [word for word in takewhile(lambda word: len(word)==length, words)]
    return longest, length


if __name__ == '__main__':
    text = """Python is probably one of the few programming languages which is both simple and
powerful. This is good for both and beginners as well as experts, and more importantly, is
fun to program with. This book aims to help you learn this wonderful language and show
how to get things done quickly and painlessly - in effect 'The Perfect Anti-venom to your
programming problems'."""
    wordlist, length = find_longest(text)
    print("Longest word's length: %d" % length)
    print("Longest word%s: %s" % ('s' if len(wordlist) > 1 else '', wordlist))

"""OUtput:
Longest word's length: 11
Longest words: ['importantly', 'programming']
"""

Thank you pyTony. your Code motivated me to read about itertools :)

Using takewhile doesnt return any word, but an empty list. I think its bacause when takewhile meets the first matching word, it stops iteration and excludes the first found word from the list. In other word, the list of longest words will always be Empty.

PS: yes I call myself beginner because I have no background inProgramming, CS or any other kind of tech. I am a Rehabilitation profesional. BUT I'm in Love with Python and whenever I find free time, I spend it on Learning python. :D

Another way:

# find one of the longest words in a text

from string import punctuation as punc

def find_longest(text):
    word_set = set(word.strip(punc).lower() for word in text.split())
    return max((len(word), word) for word in word_set)    

text = """Python is probably one of the few programming languages which is 
both simple and powerful. This is good for both and beginners as well as 
experts, and more importantly, is fun to program with. This book aims to 
help you learn this wonderful language and show how to get things done 
quickly and painlessly - in effect 'The Perfect Anti-venom to your
programming problems'."""

length, long_word = find_longest(text)

print("Longest Word: %s" % long_word)
print("Longest Word Length: %s" % length)

'''result -->
Longest Word: programming
Longest Word Length: 11
'''

Sounds like a fun project! Another possibility:

text = """\
arguing with a software engineer is like wrestling with a pig
in the mud after a while you realize the pig is enjoying it
"""

print("Longest word = {}".format(max(text.split(), key=len)))

wow thank you all for these nice codes. I'm learning from them. But qhat your codes should look like if I needed to print out all longest words not just the first occurance of first max len word.

You can do something like this (similar to your solution).

text = """\
arguing with a software engineer is like wrestling with a pig
in the mud after a while you are realizing the pig is enjoying it
"""

words = text.split()
max_len = len(max(words, key=len))
max_wordlist = [word for word in words if len(word) == max_len]

print("Longest word(s) = {} with length {}".format(max_wordlist, max_len))

'''
Longest word(s) = ['wrestling', 'realizing'] with length 9
'''
commented: Efficient one! +12

I'm satisfied now hehehe ;-)

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.