Advertisement
makispaiktis

DCP57 - Breakup lines

Nov 5th, 2020 (edited)
976
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. '''
  2. This problem was asked by Amazon.
  3. Given a string s and an integer k, break up the string into multiple lines such that each line has a length of k or less.
  4. You must break it up so that words don't break across lines. Each line has to have the maximum possible amount of words.
  5. If there's no way to break the text up, then return null.
  6. You can assume that there are no spaces at the ends of the string and that there is exactly one space between each word.
  7. For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10, you should return:
  8. ["the quick", "brown fox", "jumps over", "the lazy", "dog"]. No string in the list has a length of more than 10.
  9. '''
  10.  
  11. def solve(message, N):
  12.     words = message.split(' ')
  13.     lengths = [len(word) for word in words]
  14.     for i in range(len(lengths)):
  15.         if lengths[i] > N:
  16.             print("Error. The word " + words[i] + " contains " + str(lengths[i]) + " letters, but we want to breakup lines of " + str(N) + "characters")
  17.  
  18.     WORDS = words.copy()
  19.     result = list()
  20.     while len(WORDS) > 0:
  21.         sum = 0
  22.         lines = list()
  23.         for i in range(len(WORDS)):
  24.             if lengths[i] < N - sum:          # I use "<" and not "<=", because in the output I have to put spacebar after the lines
  25.                 sum += lengths[i]
  26.                 lines.append(WORDS[i])
  27.                 WORDS.remove(WORDS[i])
  28.         result.append(lines)
  29.     return result
  30.  
  31.  
  32. # MAIN FUNCTION
  33. message = "The quick brown fox jumps over the lazy dog"
  34. N = 10
  35. print(message.split(' '))
  36. print(solve(message, 10))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement