截至目前,我有这段代码通过提取整数的子序列来工作,这些整数按最大长度按升序排列
def sequence(n):
longSeq = []
curSeq = []
for i in range( len(n) ):
if i < len(n) - 1 and n[i] <= n[i+1]:
curSeq.append(n[i])
else:
curSeq.append(n[i])
if len(curSeq) > len(longSeq):
longSeq = curSeq
curSeq = []
print ('Longest sub-sequence of maxiumum length of integers is: ', longSeq)
sequence([1,2,4,1,2,3,2,4,7,8,10,12,1,3,4,5,6,7])
然而,当我有两个相同长度的升序子序列时,它只打印出1,如何改变它,如果有两个相同长度的子序列,它们会打印出来?任何帮助表示赞赏
所以,当我运行它时,我得到了
最大整数长度的最长子序列是:[2,4,7,8,10,12]
答案 0 :(得分:0)
有一个循环找到所有序列,跟踪最长序列的长度,然后返回该长度的所有序列。
def long_sequences(n):
long_sequences = []
cur_sequence = []
longest_sequence = 0
for ind, val in enumerate(n):
cur_sequence.append(val)
if ind < len(n)-1 and val >= n[ind+1]:
long_sequences.append(cur_sequence)
longest_sequence = max(longest_sequence, len(cur_sequence))
cur_sequence = []
long_sequences.append(cur_sequence) # to grab last one
longest_sequence = max(longest_sequence, len(cur_sequence))
return [seq for seq in long_sequences if len(seq) == longest_sequence]
>>> long_sequences([1,2,4,1,2,3,2,4,7,8,10,12,1,3,4,5,6,7])
[[2, 4, 7, 8, 10, 12], [1, 3, 4, 5, 6, 7]]