|
发表于 2019-11-22 11:57:42
|
显示全部楼层
本帖最后由 graceasyi 于 2019-11-22 13:05 编辑
为了看得清楚点,空格被我写成*了。写得有点繁。
- def fun253(words, max_width):
- words = [word + '*' for word in words]
- word_len = [len(word) for word in words]
- temp, sum_len, s = [], 0, 0
- for k, v in enumerate(word_len):
- sum_len += v
- if sum_len - 1 > max_width:
- num = k - s
- space_num = max_width - (sum(word_len[s:k]) - 1)
- if num > 1:
- sp = num - 1
- space_avg = space_num // sp
- if space_avg:
- for i in range(s, k-1):
- words[i] += '*'*space_avg
- plus = space_num - space_avg * sp
- if plus != 0:
- for j in range(plus):
- words[s+j] += '*'
- else:
- for i in range(s, k):
- words[i] += '*'*space_num
- temp.append(''.join(words[s:k]))
- s, sum_len = k, word_len[k]
- space_num = max_width - (sum(word_len[s:]) - 1)
- temp.append(''.join(words[s:]) + '*'*space_num)
- return [t[:-1] for t in temp]
- words = ["Science", "is", "what", "we", "understand", "well", "enough", "to", "explain",
- "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"]
- maxWidth = 20
- print(fun253(words, maxWidth))
复制代码 |
|