获取Python中增长最长的子序列

时间:2014-12-05 21:09:05

标签: python dynamic-programming

有谁能告诉我为什么这段代码不能产生每个增加的子序列? 我使用动态编程来解决这个问题,但我无法弄清楚为什么这个代码会失败。 参数A是一个整数序列。

def LIS(A):

    # make a list of lists
    L = list()
    for i in range(0, len(A)):
        L.append(list())

    #the first increasing subsequence is the first element in A
    L[0].append(A[0])

    for i in range(1, len(A)):
        for j in (0, i):

            # a new larger increasing subsequence found
            if (A[j] < A[i]) and ( len(L[i]) < len(L[j]) ):
                L[i] = L[j]

        L[i].append(A[i])

        # print an increasing subsequence
        print L[i]

此算法为A = [3,5,10,0,1,100,2,4,7]生成的示例输出:

[3, 5]
[3, 5, 10]
[0]
[1]
[3, 5, 10, 100]
[2]
[3, 5, 10, 100, 4]
[3, 5, 10, 100, 4, 7]
None

正确输出:

[3] 
[3, 5] 
[3, 5, 10] 
[0] 
[0, 1] 
[3, 5, 10, 100] 
[0, 1, 2] 
[0, 1, 2, 4] 
[0, 1, 2, 4, 7] 

1 个答案:

答案 0 :(得分:1)

我在你的代码中发现了两个错误

1.您认为列表是不可变的,但它们不在python中

L[i] = L[j] this is going to make L[i] point to the same list pointed by L[j]

2.for j in (0, i):

这不会将j形式0迭代到i-1,它将j形式0迭代到i。

以下是您的代码的修复版本。

def LIS(A):

    # make a list of lists
    L = list()
    for i in range(0, len(A)):
        L.append(list())

    # the first increasing subsequence is the first element in A
    L[0].append(A[0])

    for i in range(1, len(A)):
        for j in range(0, i):

            # a new larger increasing subsequence found
            if (A[j] < A[i]) and (len(L[i]) < len(L[j])):
                'throw the previous list'
                L[i] = []
                'add all elements of L[j] to L[i]'
                L[i].extend(L[j])
        L[i].append(A[i])

    for i in range(len(A)):
    # print an increasing subsequence
        print (L[i])
A = [3, 5, 10, 0, 1, 100, 2, 4, 7]
LIS(A)