简体   繁体   English

最长递增序列的最大值

[英]Maximum of Longest Increasing Sequences

I have a code that will find all the cycles of a list, eg for [1,2,3] the cycles are [1,2,3], [2,3,1], [3,1,2]. 我有一个代码,可以找到列表的所有循环,例如,对于[1,2,3],循环为[1,2,3],[2,3,1],[3,1,2]。 I also have a code for finding the longest increasing subsequence. 我也有一个代码来查找最长的递增子序列。

What I want to do is input a list, find the longest increasing subsequence of every cycle of that list, and then return the maximum length out of all of these. 我要做的是输入一个列表,找到该列表每个循环中最长的递增子序列,然后从所有这些中返回最大长度。 how do I go from these two functions to finding the LIS of every cycle and then return the maximum? 如何从这两个函数查找每个周期的LIS,然后返回最大值?

Here is my code so far: 到目前为止,这是我的代码:

def cycles(X):

  n = len(X)

  values = []

  for i in range(0,n):
    values.append(X[i:n] + X[0:i])

  return values    



def longest_increasing_subsequence(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 len(max(l, key=len))

I'd appreciate any help. 我将不胜感激。 thanks. 谢谢。

This will do the job: 这将完成工作:

l=[1,2,3,4]
s=cycles(l)
lis=[longest_increasing_subsequence(d) for d in s]
print(lis) 
print(max(lis))

The result is 结果是

[4,3,2,3]

and

4

Try this code: 试试这个代码:

l = [3,4,5,9,8,1,2,7,7,7,7,7,7,7,6,0,1]
empty = []
one = [1]
two = [2,1]
three = [1,0,2,3]
tricky = [1,2,3,0,-2,-1]
ring = [3,4,5,0,1,2]
internal = [9,1,2,3,4,5,0]

# consider your list as a ring, continuous and infinite
def longest_increasing_subsequence(l):
    length = len(l)
    if length == 0: return 0  # list is empty
    i, tmp, longest = [0, 1, 1]
    # 1 < tmp means that ring is finished, but the sequence continue to increase
    while i < length or 1 < tmp:
        # compare elements on the ring
        if l[i%length] < l[(i+1)%length]:
            tmp += 1
        else:
            if longest < tmp: longest = tmp
            tmp = 1
        i += 1
    return longest

print("0 == " + str(longest_increasing_subsequence(empty)))
print("1 == " + str(longest_increasing_subsequence(one)))
print("2 == " + str(longest_increasing_subsequence(two)))
print("3 == " + str(longest_increasing_subsequence(three)))
print("5 == " + str(longest_increasing_subsequence(tricky)))
print("5 == " + str(longest_increasing_subsequence(internal)))
print("6 == " + str(longest_increasing_subsequence(ring)))
print("6 == " + str(longest_increasing_subsequence(l)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM