简体   繁体   中英

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

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:

[3, 5, 6, 7]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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