finding sublists

mail@pastecode.io avatar
unknown
python
2 years ago
1.6 kB
2
Indexable
Never
list_nums = [1, 2, 5, 7, 9, 19, 23, 4, 3, 2, 2, 6, 7, 8]


def find_sublists(list_nums):
    """
    Return list of sublists and index start and end for each sublist.
    Find sublists that start with 1,2,3 but no entry should exceed 10.
    Example:
    list_nums = [1,2,5,7,9,19,23,4,3,2,2,6,7,8]
    Output:
    - sub_lists = [[1,2,5,7,9],[3,2,2,6,7,8]]
    - sub_lists_index = [(0,4),(8,13)]
    """
    sub_lists = []
    sub_lists_index = []

    new_sub_list = []
    new_sub_list_index = []

    for i in range(len(list_nums)):
        if list_nums[i] == 1 or list_nums[i] == 2 or list_nums[i] == 3:
            if len(new_sub_list) == 0:
                new_sub_list.append(list_nums[i])
                new_sub_list_index.append(i)
            else:
                new_sub_list.append(list_nums[i])
        elif list_nums[i] > 10:
            if len(new_sub_list) > 0:
                new_sub_list_index.append(i - 1)
                sub_lists.append(new_sub_list)
                sub_lists_index.append(new_sub_list_index)
                new_sub_list = []
                new_sub_list_index = []
            else:
                continue
        else:
            if len(new_sub_list) > 0:
                new_sub_list.append(list_nums[i])
        if i == len(list_nums) - 1:
            if len(new_sub_list) > 0:
                new_sub_list_index.append(i)
            sub_lists.append(new_sub_list)
            sub_lists_index.append(new_sub_list_index)

    return sub_lists, sub_lists_index


ans = find_sublists(list_nums)
print(ans[0])
print(ans[1])