简体   繁体   English

一个升序最长有序序列的程序

[英]A Program for Longest ordered Sequence in Ascending Order

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?怎么了?

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:])使用 python 3.10 itertools.pairwise函数可以代替zip(lst, lst[1:])
  • itemgetter can be replaced by a comprehension itemgetter可以被理解替换

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)

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:您的 if 条件正在检查索引 i 处选择的数字是否大于以下任何数字,这意味着在给定列表上,例如:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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