【发布时间】:2013-05-07 08:54:46
【问题描述】:
在您认为它重复之前(有很多问题询问如何在不破坏单词的情况下拆分长字符串)请记住我的问题有点不同:顺序并不重要,我必须适合单词为了尽可能地使用每一行。
我有一组无序的单词,我想在不超过 253 个字符的情况下将它们组合起来。
def compose(words):
result = " ".join(words)
if len(result) > 253:
pass # this should not happen!
return result
我的问题是我想尽可能地填满这条线。例如:
words = "a bc def ghil mno pq r st uv"
limit = 5 # max 5 characters
# This is good because it's the shortest possible list,
# but I don't know how could I get it
# Note: order is not important
good = ["a def", "bc pq", "ghil", "mno r", "st uv"]
# This is bad because len(bad) > len(good)
# even if the limit of 5 characters is respected
# This is equivalent to:
# bad = ["a bc", "def", "ghil", "mno", "pq r", "st uv"]
import textwrap
bad = textwrap.wrap(words, limit)
我该怎么办?
【问题讨论】:
-
这是一个动态规划问题;以与攻击coin change problem 相同的方式攻击它。