python - 我无法完全理解这行代码

标签 python python-3.x readability lis

我正在解决LIS(最长递增子集)上的问题,但我无法完全解决它。我在 google 上搜索了一些解决方案,并在 Rosettacode 上找到了几个解决方案。我喜欢这个,因为它看起来非常短且直接(所以更容易理解)。但它的编写方式让我在重写它时遇到了严重的麻烦。

for i in range(len(d)):
        l.append(max([l[j] for j in range(i)
                     if l[j][-1] < d[i]] 
                         or [[]], key=len) 
                   + [d[i]]
                )

这是我难以理解的部分。这就是我想我所理解的:

将解决方案数组中最长的数字组合追加到解决方案数组中,该组合小于我正在考虑的输入数组中的当前数字;加上您正在考虑的输入数组中的数字。(抱歉我的英语)。

我觉得我没有完全理解代码的作用。

def longest_increasing_subsequence(d):
    'Return one of the L.I.S. of list d'
    l = []
    for i in range(len(d)):
        l.append(max([l[j] for j in range(i) if l[j][-1] < d[i]] or [[]], key=len) 
                  + [d[i]])
    return max(l, key=len)

if __name__ == '__main__':
    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))

最佳答案

让我为您展开代码:

def longest_increasing_subsequence(d):
    'Return one of the L.I.S. of list d'
    l = []
    for i in range(len(d)):
        # currently the LIS is just this number
        lis_at_this_index = [d[i]]
        # for all the previous LIS
        for j in range(i):
            # if d[i] can be added to it and still be increasing
            if l[j][-1] < d[i]:

                # update the candidate LIS at this index
                lis_at_this_index = max(lis_at_this_index, l[j] + [d[i]], key=len)
        l.append(lis_at_this_index)
    # return the global maximum
    return max(l, key=len)

这个想法是,如果我们有索引 [0..i-1] 的 LIS,我们可以像这样计算索引 i 的 LIS:

  1. 对于每个 LIS [0...i-1],检查是否允许添加 d[i]
  2. 如果允许,则为索引 i 的候选 LIS
  3. 所有候选中最长的是索引 i 处的 LIS

然后返回每个索引处所有 LIS 中最长的一个。

关于python - 我无法完全理解这行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57577494/

相关文章:

python-3.x - 如何关闭 Raspberry Pi Cam 的 AWB/AGE(Raspi 4、RaspiCam V2.1、Python、OpenCV)

python - 如何在 reStructuredText 中找到标题

c - 在 for 循环的增量语句而不是 for 循环的主体中递增阶乘是一种好习惯吗?

java - 使用静态导入和代码可读性质量?

python - 通过在 pandas 中分组和添加值来展平列

python - 为什么定义了 __del__ 的循环引用对象在 Python 中是不可回收的?

python - 建立数据源的目的是什么

python - Python 中 '\0\0' 的含义?

c - 使 C 源代码中的大常量更具可读性?

python - 字符无法从主机变成从机伪终端