Skip to content

Instantly share code, notes, and snippets.

@rishi93
Created December 20, 2019 16:12
Show Gist options
  • Save rishi93/1a5341db2a20a046306ede43091ad894 to your computer and use it in GitHub Desktop.
Save rishi93/1a5341db2a20a046306ede43091ad894 to your computer and use it in GitHub Desktop.
Daily Coding Problem - 28
"""
This problem was asked by Palantir.
Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified.
More specifically, you should have as many words as possible in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any, distributed starting from the left.
If you can only fit one word on a line, then you should pad the right-hand side with spaces.
Each word is guaranteed not to be longer than k.
For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you should return the following:
["the quick brown", # 1 extra space on the left
"fox jumps over", # 2 extra spaces distributed evenly
"the lazy dog"] # 4 extra spaces distributed evenly
"""
def justify(text, max_line_width):
lines = []
i = 0
while i < len(text):
current_line = []
remaining_line_width = max_line_width
# Check if the word can fit into current line
while i < len(text) and len(text[i]) <= remaining_line_width:
current_line.append(text[i])
remaining_line_width -= len(text[i]) + 1# Mandatory space
i += 1
# Last word does not need mandatory space
total_space = remaining_line_width + 1
# extra spaces distributed as equal spaces between words
equal_space = total_space//(len(current_line)-1)
# Unequal spaces distributed from left to right
unequal_space = total_space%(len(current_line)-1)
for j in range(0, unequal_space):
current_line[j] += " "
# Adding the final result to a list
lines.append((" " + equal_space*" ").join(current_line))
return lines
text = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
print(justify(text, 16))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment