A Program for Longest ordered Sequence in Ascending Order

Question:

I am trying to write a program that shows the longest ordered sequence in ascending order and its length.

For example:

input:

  lista = [43, 27, 28, 40, 43, 23, 29, 47, 37, 2, 14, 14, 18, 4, 27, 36, 24, 31,42, 29]

Output:

The maximum length = 4
The ordered values are = [27, 28, 40, 43]

I tried:

lista = [43, 27, 28, 40, 43, 23, 29, 47, 37, 2, 14, 14, 18, 4, 27, 36, 24, 31,42, 29]
#The ordered values are = [27, 28, 40, 43]
resultado = []
for i in range(0,len(lista)-1):
    for j in range(i+1,len(lista)):
        #print(lista[i],lista[j])
        if lista[i] < lista[j]:
            resultado.append(lista[i])
            resultado.append(lista[j])
        
            break
      
        break
print(resultado )  

The result:

[27, 28, 28, 40, 40, 43, 23, 29, 29, 47, 2, 14, 14, 18, 4, 27, 27, 36, 24, 31, 31, 42]

What is wrong with the loop?

Asked By: Ed S

||

Answers:

This doesn’t answer your question, but I hope it can be helpful. I solved the problem this way:

def f(x):
    res=[]
    temp=[]
    for i in x:
        if temp:
            if i>temp[-1]:
                temp.append(i)
            else:
                res.append(temp)
                temp=[i]
        else:
            temp.append(i)
    return max(res,key=len)

Form groups by a pairwise comparison. It returns the 1st match in case of multiple maximal sequences.

from itertools import groupby
from operator import itemgetter

lista = [43, 27, 28, 40, 43, 23, 29, 47, 37, 2, 14, 14, 18, 4, 27, 36, 24, 31,42, 29]

longest_asc_seq = max((list(next(grp)) + list(map(itemgetter(1) , grp)) for check, grp in groupby(zip(lista, lista[1:]), key=lambda pair: pair[1] > pair[0]) if check), key=len)


print(f'The maximum length = {len(longest_asc_seq)}')
print(f'The ordered values are = {longest_asc_seq}')
#The maximum length = 4
#The ordered values are = [27, 28, 40, 43]

Remarks:

  • with python 3.10 itertools.pairwise function is available instead of zip(lst, lst[1:])
  • itemgetter can be replaced by a comprehension
Answered By: cards

One of the problems in your code is your comparison. Your if-condition is checking if a chosen number at index i is larger than any following number which means that on a given list like:

list = [2,4,5,3,1,2]

Your comparison will return

[2,4,5,3] because 3 > 2

as the longest sequence of ascending order instead of

[2,4,5]

You can also save some resources by skipping to the last index of a sequence.
Another problem is that for every two numbers you compare and for which the if case is true, you append the number you compare them to once.

If you need a raw algorithm for this problem, this function will return the first sequence that has the longest ascending order. It does not take into account when multiple sequences have the same length.

def longest_ascending_order(list_a):
    results = []
    right_number_index = 1
    left_number_index = 0
    # adds the start index
    cache_results = [list_a[left_number_index]]


    while right_number_index < (len(list_a)):


        #compares the two neigbour numbers. Exit condition for the ascending order
        if list_a[left_number_index] >= list_a[right_number_index]:
            # override the results if the new ascending order is longer
            if len(cache_results) > len(results):
                results = cache_results
            #reset the cache list
            cache_results = []

        # append number to the new sequence
        cache_results.append(list_a[right_number_index])

        right_number_index += 1
        left_number_index += 1

    print(results)
    return results


if __name__ == '__main__':
    list_of_numbers = [43, 27, 28, 40, 43, 23, 29, 47, 37, 2, 14, 14, 18, 4, 27, 36, 24, 31, 42, 29]
    longest_ascending_order(list_of_numbers)
Answered By: Mole
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.