Guest User

Untitled

a guest
Dec 17th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. def cut_everything(sentence, max_length):
  2. """
  3. reduces each word in sentence to a length of 4
  4.  
  5. :type sentence: string
  6. :param sentence: the sentence to cut
  7. :type max_length: int
  8. :param max_length: the length to which the sentence will be reduced
  9. """
  10. words = sentence.split()
  11. for index, word in enumerate(words):
  12. word_length = len(word)
  13. if word_length > 4:
  14. to_cut = len(sentence) - max_length
  15. to_keep = word_length - to_cut
  16. if to_keep < 4:
  17. to_keep = 4
  18. words[index] = word[:to_keep]
  19. sentence = ' '.join(words)
  20. if len(sentence) <= max_length:
  21. break
  22.  
  23. return sentence
  24.  
  25. MAX_WORD_LENGHT = 4
  26.  
  27. to_keep = word_length - to_cut
  28. if to_keep < 4:
  29. to_keep = 4
  30.  
  31. to_keep = max(word_length - to_cut, 4)
  32.  
  33. import doctest
  34.  
  35. MAX_WORD_LENGHT = 4
  36.  
  37. def cut_everything(sentence, max_length):
  38. """
  39. reduces each word in sentence to a length of 4
  40.  
  41. :type sentence: string
  42. :param sentence: the sentence to cut
  43. :type max_length: int
  44. :param max_length: the length to which the sentence will be reduced
  45.  
  46. >>> cut_everything('foo bar foooobar', 16)
  47. 'foo bar foooobar'
  48.  
  49. >>> cut_everything('foo bar foooobar', 8)
  50. 'foo bar fooo'
  51.  
  52. >>> cut_everything('foo bar foooobar baaarfoo', 20)
  53. 'foo bar fooo baaarfo'
  54.  
  55. >>> cut_everything('fooooooo baaaaaaar foooobar baaarfoo', 2)
  56. 'fooo baaa fooo baaa'
  57. """
  58. words = sentence.split()
  59. chars_to_cut = len(sentence) - max_length
  60. for index, word in enumerate(words):
  61. word_length = len(word)
  62. if chars_to_cut > 0 and word_length > MAX_WORD_LENGHT:
  63. to_keep = max(word_length - chars_to_cut, MAX_WORD_LENGHT)
  64. words[index] = word[:to_keep]
  65. chars_to_cut -= word_length - to_keep
  66. return ' '.join(words)
  67.  
  68. if __name__ == '__main__':
  69. doctest.testmod()
Add Comment
Please, Sign In to add comment