【问题标题】:Obtaining the longest increasing subsequence in Python获取Python中最长的递增子序列
【发布时间】:2014-12-05 21:09:05
【问题描述】:

谁能告诉我为什么这段代码不会产生每个递增的子序列? 我使用动态编程来解决这个问题,但我不知道为什么这段代码会失败。 参数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] 

【问题讨论】:

  • 为什么[0, 1, 100] 无效?
  • 无论您在内部循环中尝试做什么都不起作用,因为您总是将A 的第一项与A[i]A[i] 与自身进行比较 - (0,1) 不是在for j in (0, i): 中迭代的正确内容。我没有看到您使用 dynamic programming 的任何证据。
  • 放入一些打印语句以查看发生了什么 - 使用pprint.pprint(L) 作为函数中的最后一个语句,之后外部循环已停止.
  • @wwii 这是LIS问题的动态规划解决方案。
  • 我在 C++ 中实现了完全相同的东西并且工作正常。奇怪的 Python。

标签: python dynamic-programming


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多