This function's goal is to reduce the length of a sentence
to exactly max_length
characters by cutting each word in the sentence to a length of minimum 4 characters, if cutting each word to 4 characters isn't enough the the sentence is returned anyway.
All sentences are free of special characters and words are separated by spaces.
Here is the function:
def cut_everything(sentence, max_length):
"""
reduces each word in sentence to a length of 4
:type sentence: string
:param sentence: the sentence to cut
:type max_length: int
:param max_length: the length to which the sentence will be reduced
"""
words = sentence.split()
for index, word in enumerate(words):
word_length = len(word)
if word_length > 4:
to_cut = len(sentence) - max_length
to_keep = word_length - to_cut
if to_keep < 4:
to_keep = 4
words[index] = word[:to_keep]
sentence = ' '.join(words)
if len(sentence) <= max_length:
break
return sentence
My main concern for this review is performance, but any readability comment is appreciated