簡體   English   中英

如何為最長的漸進序列編碼

[英]How to code for longest progressive sequence

如果序列不隨時間減少,則稱該序列是漸進的。例如 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)

我認為您的代碼太短而無法檢查漸進序列,並且僅適用於您提供的一個示例。

我會試一試:

# 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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM