gpt4 book ai didi

python - 在Python中获取最长的递增子序列

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:50 25 4
gpt4 key购买 nike

谁能告诉我为什么这段代码不产生每个递增的子序列?我使用动态编程来解决这个问题,但我不明白为什么这段代码会失败。参数 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.你假设列表是不可变的,但它们不在 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)

关于python - 在Python中获取最长的递增子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27324717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com