简体   繁体   English

如何为最长的渐进序列编码

[英]How to code for longest progressive sequence

A sequence is said to be progressive if it doesn't decrease in time Eg 1 1 2 2 is a progressive sequence but 1 2 1 is not Let S be the sequence and represented by L spaced integer Ki(where i =1,2,3.. L)now the task is to find the longest progressive sequence in S如果序列不随时间减少,则称该序列是渐进的。例如 1 1 2 2 是渐进序列,但 1 2 1 不是3.. L)现在的任务是找到S中最长的渐进序列

a= int(input()) #length of the sequence 
b=input() # sequence S
if(int(b[-1])>=int(b[-3])):
    print(b)
else:
    for i in range(a+2):
        print(b[i],end='')
 
Output 1:
4
1 1 2 1
1 1 2 
Output 2:
4
1 3 2 1
1 3 2(But correct answer is 1 3)

I think your code is too short to check for progressive sequences and works only for the one example you provided.我认为您的代码太短而无法检查渐进序列,并且仅适用于您提供的一个示例。

I'll give it a try:我会试一试:

# get some sequence here
seq = [1, 2, 4, 3, 5, 6, 7]

# store the first value
_v = seq[0]

# construct a list of lists
cnts = list()
# and store the first value into this list
cnt = [_v]

# iterate over the values starting from 2nd value
for v in seq[1:]:

    if v < _v:
        # if the new value is smaller, we have to append our current list and restart        
        cnts.append(cnt)
        cnt = [v]
    else:
        # else we append to the current list
        cnt.append(v)

    # store the current value as last value
    _v = v
else:
    # append the last list to the results
    cnts.append(cnt)

# get the longest subsequence
print(max(cnts, key=lambda x: len(x)))

Output: Output:

[3, 5, 6, 7]

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

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