The function receives a string containing a sentence. Its goal is to shorten every word in it to a length of 4 characters until the string is shorter than 38 characters and return.

The 38 characters max length is mandatory and must be reached with the least amount of deletion possible.

Here is what I've done:

# reduces each word to a lenght of 4
def shorten_words(string):
    i = 0
    j = 0
    while(len(string) > 38 and i < len(string)):
         array = list(string)
         if(array[i] != ' ' and array[i] != '-'):
             j += 1
             j = 0
         if(j > 4):
             array[i] = ''
             i -= 1
         i += 1
         string = ''.join(array)

I feel like the list/join method is inefficient and would like to know how I could improve this function

  • 2
    \$\begingroup\$ The post says, "its goal is to shorten every word in it to a length of 4 characters" but if the string is 38 characters or shorter, then the code returns the string unchanged. Could you fix the description of the problem please? \$\endgroup\$ Commented Nov 27, 2018 at 9:11
  • \$\begingroup\$ @GarethRees this has been done, thanks for letting me know \$\endgroup\$
    – Comte_Zero
    Commented Nov 27, 2018 at 10:17
  • \$\begingroup\$ What do you mean by "least amount of deletion" though? Is there a requirement that each word in the end should be as close in length as possible? If not the problem is much simpler. \$\endgroup\$
    – l0b0
    Commented Nov 27, 2018 at 18:36

1 Answer 1


Some suggestions:

  • Naming is really important. string, array, i and j are not descriptive. After reading the entire function I think they could be renamed sentence, words, string_index and word_length.
  • There's no point in adding empty strings to the array - they aren't printed anyway.
  • What is the significance of 38? If it's not significant it should be removed, if it is it should be named something like max_result_length.
  • In Python return is a simple statement, which means its argument should not be put in parentheses.

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.