MCPcopy
hub / github.com/TheAlgorithms/Python / justify

Function justify

strings/text_justification.py:35–65  ·  view source on GitHub ↗
(line: list, width: int, max_width: int)

Source from the content-addressed store, hash-verified

33 words = word.split()
34
35 def justify(line: list, width: int, max_width: int) -> str:
36 overall_spaces_count = max_width - width
37 words_count = len(line)
38 if len(line) == 1:
39 # if there is only word in line
40 # just insert overall_spaces_count for the remainder of line
41 return line[0] + " " * overall_spaces_count
42 else:
43 spaces_to_insert_between_words = words_count - 1
44 # num_spaces_between_words_list[i] : tells you to insert
45 # num_spaces_between_words_list[i] spaces
46 # after word on line[i]
47 num_spaces_between_words_list = spaces_to_insert_between_words * [
48 overall_spaces_count // spaces_to_insert_between_words
49 ]
50 spaces_count_in_locations = (
51 overall_spaces_count % spaces_to_insert_between_words
52 )
53 # distribute spaces via round robin to the left words
54 for i in range(spaces_count_in_locations):
55 num_spaces_between_words_list[i] += 1
56 aligned_words_list = []
57 for i in range(spaces_to_insert_between_words):
58 # add the word
59 aligned_words_list.append(line[i])
60 # add the spaces to insert
61 aligned_words_list.append(num_spaces_between_words_list[i] * " ")
62 # just add the last word to the sentence
63 aligned_words_list.append(line[-1])
64 # join the aligned words list to form a justified line
65 return "".join(aligned_words_list)
66
67 answer = []
68 line: list[str] = []

Callers 1

text_justificationFunction · 0.85

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected