我正在尝试通过MIT OCW 这里 上的课程来理解动态规划的概念。OCW视频上的解释非常好,但我感觉直到我将解释实现到代码中,我才真正理解了它。在实现过程中,我参考了一些讲义这里,特别是第3页。
问题是,我不知道如何将某些数学符号翻译成代码。这是我已经实现的部分(我认为它已经正确实现):
import math
paragraph = "Some long lorem ipsum text."
words = paragraph.split(" ")
# Count total length for all strings in a list of strings.
# This function will be used by the badness function below.
def total_length(str_arr):
total = 0
for string in str_arr:
total = total + len(string)
total = total + len(str_arr) # spaces
return total
# Calculate the badness score for a word.
# str_arr is assumed be send as word[i:j] as in the notes
# we don't make i and j as argument since it will require
# global vars then.
def badness(str_arr, page_width):
line_len = total_length(str_arr)
if line_len > page_width:
return float('nan')
else:
return math.pow(page_width - line_len, 3)
现在我不明白的是讲义中的第3到5点。我真的不理解,也不知道从哪里开始实施这些。到目前为止,我已经尝试迭代单词列表,并计算每个可能的行尾的错误程度,就像这样:
def justifier(str_arr, page_width):
paragraph = str_arr
par_len = len(paragraph)
result = [] # stores each line as list of strings
for i in range(0, par_len):
if i == (par_len - 1):
result.append(paragraph)
else:
dag = [badness(paragraph[i:j], page_width) + justifier(paragraph[j:], page_width) for j in range(i + 1, par_len + 1)]
# Should I do a min(dag), get the index, and declares it as end of line?
但是,我不知道如何继续这个函数,说实话,我也不理解这一行:
dag = [badness(paragraph[i:j], page_width) + justifier(paragraph[j:], page_width) for j in range(i + 1, par_len + 1)]
我该如何将justifier
作为一个int
返回(因为我已经决定将返回值存储在列表result
中)。我应该再创建一个函数并从那里递归吗?是否应该有任何递归呢?
您能否告诉我接下来该怎么做,并解释这是如何使用动态规划的?我真的看不出递归在哪里,子问题又是什么。
非常感谢。