# Shortening words within a string

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
else:
j = 0
if(j > 4):
array[i] = ''
i -= 1
i += 1
string = ''.join(array)
return(string)


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

• 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? – Gareth Rees Nov 27 '18 at 9:11
• @GarethRees this has been done, thanks for letting me know – Comte_Zero Nov 27 '18 at 10:17
• 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. – l0b0 Nov 27 '18 at 18:36

• 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.
• 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.