我无法完全理解这一行代码

时间:2019-08-20 15:58:05

标签: python python-3.x readability lis

我正在解决 LIS (最长的子集)上的问题,但无法完全解决。我用谷歌搜索了一些解决方案,并在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)))

1 个答案:

答案 0 :(得分:1)

让我为您扩展代码:

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中最长的一个。

相关问题