Coding
Write code to implement a text wrapper that takes in a long string and a character limit as inputs and returns a list of strings, where each string is limited to the specified number of characters, split only at spaces.
Machine Learning Engineer
Flexport
Uber
Bloomberg
Symantec
Lyft
Answers
Anonymous
5 months ago
def text_wrapper(text, char_limit):
# Initialize a list to hold the wrapped text
wrapped_text = []
# Split the original text into words
words = text.split()
# Initialize a temporary string to build the current line
current_line = ""
for word in words:
# Check if adding the next word exceeds the character limit
if len(current_line) + len(word) + 1 > char_limit:
# If it does, append the current line to the list and start a new line
wrapped_text.append(current_line.strip())
current_line = word # Start a new line with the current word
else:
# Otherwise, add the word to the current line
current_line += " " + word
# Append any remaining text as the last line
if current_line:
wrapped_text.append(current_line.strip())
return wrapped_text
# Example usage
long_string = "This is an example of a long string that needs to be wrapped according to a specified character limit without breaking any words."
char_limit = 30
wrapped_result = text_wrapper(long_string, char_limit)
# Print the wrapped result
for line in wrapped_result:
print(f'"{line}"')
Interview question asked to Machine Learning Engineers interviewing at Mozilla, Bloomberg, Uber and others: Write code to implement a text wrapper that takes in a long string and a character limit as inputs and returns a list of strings, where each string is limited to the specified number of characters, split only at spaces..