-
Notifications
You must be signed in to change notification settings - Fork 0
/
dailycoding028.py
84 lines (65 loc) · 2.32 KB
/
dailycoding028.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def wordLength(wordlist):
"""Helper function to compute sum of lengths of words
"""
return sum(len(word) for word in wordlist)
def makeWordList(sentence):
"""Helper to make test case from sentence
"""
return sentence.split(" ")
def format_text(words, k):
"""Formats the words in the sentence into a sentence array
"""
wordList, sentence = [], []
for i, word in enumerate(words):
if len(wordList) == 0:
wordList.append(word)
continue
# greedily fill the word list until maximum width is reached
spacesBtwn = len(wordList) - 1
if wordLength(wordList) + spacesBtwn + len(word) >= k:
sentence.append(wordList)
wordList = []
# add next word to the wordlist
wordList.append(word)
# handle the last line
if i == len(words) - 1:
sentence.append(wordList)
wordList = []
return sentence
def format_spaces(sentenceList, k):
"""Formats the spaces needed between words in a sentence list
"""
def calculate_spaces(spaces, bins):
"""Returns list of spaces evenly distributed
"""
space_dist = [spaces // bins for _ in range(bins)]
for i in range(spaces % bins):
space_dist[i] += 1
return space_dist
spacesList = []
for sentence in sentenceList:
# available spaces to fill
spacesFree = k - wordLength(sentence)
if len(sentence) == 1:
spacesList.append([spacesFree])
else:
spacesList.append(calculate_spaces(spacesFree, len(sentence) - 1))
return spacesList
def justify(words, k):
"""Fully justifies a given list of words from a sentence
"""
sentences = format_text(words, k)
spaces = format_spaces(sentences, k)
# stitch together the sentences and spaces
return [''.join([i + j * " " for i, j in zip(s, space)]) + s[-1]
for s, space in zip(sentences, spaces)]
def main():
tests = (
(makeWordList("the quick brown fox jumps over the lazy dog"), 16),
(makeWordList("this is a stupid and hard daily coding problem"), 10),
(makeWordList("this problem was asked by the Palantir data gods"), 20)
)
for i in justify(*tests[2]):
print(i)
if __name__ == '__main__':
main()