Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- MAX_WORD_LENGHT = 4
- to_keep = word_length - to_cut
- if to_keep < 4:
- to_keep = 4
- to_keep = max(word_length - to_cut, 4)
- import doctest
- MAX_WORD_LENGHT = 4
- 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
- >>> cut_everything('foo bar foooobar', 16)
- 'foo bar foooobar'
- >>> cut_everything('foo bar foooobar', 8)
- 'foo bar fooo'
- >>> cut_everything('foo bar foooobar baaarfoo', 20)
- 'foo bar fooo baaarfo'
- >>> cut_everything('fooooooo baaaaaaar foooobar baaarfoo', 2)
- 'fooo baaa fooo baaa'
- """
- words = sentence.split()
- chars_to_cut = len(sentence) - max_length
- for index, word in enumerate(words):
- word_length = len(word)
- if chars_to_cut > 0 and word_length > MAX_WORD_LENGHT:
- to_keep = max(word_length - chars_to_cut, MAX_WORD_LENGHT)
- words[index] = word[:to_keep]
- chars_to_cut -= word_length - to_keep
- return ' '.join(words)
- if __name__ == '__main__':
- doctest.testmod()
Add Comment
Please, Sign In to add comment