Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- This problem was asked by Amazon.
- 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.
- You must break it up so that words don't break across lines. Each line has to have the maximum possible amount of words.
- If there's no way to break the text up, then return null.
- You can assume that there are no spaces at the ends of the string and that there is exactly one space between each word.
- For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10, you should return:
- ["the quick", "brown fox", "jumps over", "the lazy", "dog"]. No string in the list has a length of more than 10.
- '''
- def solve(message, N):
- words = message.split(' ')
- lengths = [len(word) for word in words]
- for i in range(len(lengths)):
- if lengths[i] > N:
- print("Error. The word " + words[i] + " contains " + str(lengths[i]) + " letters, but we want to breakup lines of " + str(N) + "characters")
- WORDS = words.copy()
- result = list()
- while len(WORDS) > 0:
- sum = 0
- lines = list()
- for i in range(len(WORDS)):
- if lengths[i] < N - sum: # I use "<" and not "<=", because in the output I have to put spacebar after the lines
- sum += lengths[i]
- lines.append(WORDS[i])
- WORDS.remove(WORDS[i])
- result.append(lines)
- return result
- # MAIN FUNCTION
- message = "The quick brown fox jumps over the lazy dog"
- N = 10
- print(message.split(' '))
- print(solve(message, 10))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement