【发布时间】:2017-03-27 06:04:39
【问题描述】:
所以我正在查看这个 python 代码来查找两个字符串的最长子序列,但我不明白“#line A”为什么第三个参数是 key=len。从我学到的 len 是一个返回字符串长度的函数,但我不明白它是如何在这里使用的。
def lcs(xstr, ystr):
"""
>>> lcs('thisisatest', 'testing123testing')
'tsitest'
"""
if not xstr or not ystr:
return ""
x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]
if x == y:
return x + lcs(xs, ys)
else:
return max(lcs(xstr, ys), lcs(xs, ystr), key=len) #line A
【问题讨论】:
-
这是
max函数的命名参数:docs.python.org/2/library/functions.html#max。基本上,对lcs的 2 次递归调用的结果将提供给len,然后进行比较。这基本上返回了长度最长的结果。 -
在以后发布问题之前,请查阅一些文档。
标签: python string syntax sequence subsequence