PeterMikel - 4 months ago 30

Python Question

As of now I have this piece of code which works by extracting a sub sequence of integers which go in ascending order by the largest length

`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])

However when I have two sub-sequences of ascending order which are the same length it will only print out 1, how to I change this so if there are two sub-sequences of the same length it will print out both? Any help is appreciated

So when I run it I get

Longest sub-sequence of maximum length of integers is: [2, 4, 7, 8, 10, 12]

Answer

Have a loop that finds all sequences, keep track of the length of the longest sequence, then return all sequences of that length.

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