A problem from Coderbyte. Find the longest word in a sentence after removing the punctuations and if two or more words are of same length return the first word

Below is my solution:

def cleanWord(word):
  # To remove punctuations
  punctuations = ['!','.','\'','"',',','&']
  new_word = ''

  for c in word:
    if c in punctuations:
      new_word += c  

  return new_word    

def LongestWord(sen):

  words = sen.split(' ')

  word_lengths = {}
  # finding length of each word
  for word in words:
      clean_word = cleanWord(word)
      if len(clean_word) not in word_lengths.keys():
        word_lengths[len(clean_word)] = word

  longest_word_length = max(word_lengths.keys())
  longest_word = word_lengths[longest_word_length]

  return longest_word

1 Answer 1

def cleanWord(word):
  # To remove punctuations

The comment is a better name without_punctuation. Also you should be following snake case as per PEP-8.

Much of your logic in the longest word function can be handled by max with a key function. The overall solution can be written like so.

def without_punctuation(text):                                                  
    translator = str.maketrans('','',string.punctuation)                        
    return text.translate(translator)                                           
def longest_word(sentence):                                                     
    words = without_punctuation(sentence).split()                               
    return max(words,key=len)
  • 1
    \$\begingroup\$ If the sentence is written like your code, i.e., without the standard space after commas (rather bad for someone pointing out PEP 8 :-), then you incorrectly combine words. \$\endgroup\$ Mar 1, 2021 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.