Python求列表的最大連續區間

題目
連續區間爲公差爲1的等差數列。
輸入:

[1, 2, 99, 3, 4, 5, 6, 5, 4, 4, 2, 6, 3, 1, 8, 5, 3, 6, 1, 2, 3, 2, 3, 4, 5, 6]

輸出:

[2, 3, 4, 5, 6]

def get_continue_seq(str_list):
    ls = eval(str_list)
    len_ls = len(ls)
    index_count = {}
    for x in range(len_ls):
        key = index_count.keys()
        if key:
            diff_x1 = ls[x]-ls[x-1]
            if diff_x1==1:
                index_count[max(key)].append(ls[x])
            else:
                index_count[x] = [ls[x]]
        else:
            index_count[x] = [ls[x]]
    res = index_count[max(index_count, key=lambda x: len(index_count[x]))]
    return index_count

str_list = input()
print(get_continue_seq(str_list))
[1, 2, 99, 3, 4, 5, 6, 5, 4, 4, 2, 6, 3, 1, 8, 5, 3, 6, 1, 2, 3, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章