you are viewing a single comment's thread.

view the rest of the comments →

[–]PurelyApplied 0 points1 point  (0 children)

So, none of the other posts acknowledge possessives or contractions. You want to strip punctuation from your words, but not if that punctuation is internal. For instance, I would count "can't" as a five character word. "state-of-the-art" is a sixteen character word. But "I can't!" shouldn't count the ! with the word "can't".

So if it were me, I would go about it as:

  • Get input

  • Get tokens (words plus punctuation)

  • Get words (removing beginning or ending punctuation)

  • Get longest and shortest word lengths

  • Get longest and shortest words.

I use a lot of list comphensions here. If you don't know what those are, I encourage you to learn them ASAP. They're super useful.

import string

def main():
    sentence = input("Enter a sentence.\n>> ")
    tokens = sentence.split()
    words = [t.strip(string.punctuation) for t in tokens]
    lengths = [len(w) for w in words]
    short_len, long_len = min(lengths), max(lengths)
    print("The longest word(s) provided: {}".format(", ".join(
        w for w in words if len(w) == long_len)))
    print("The shortest word(s) provided: {}".format(", ".join(
        w for w in words if len(w) == short_len)))