Home > database >  Hwo to find sublist of increasing length in python list
Hwo to find sublist of increasing length in python list

Time:06-25

Suppose, n = 6 (length of list) lis = [3, 2, 3, 4, 3, 1] (my list)

I need list of sublists with maximum increasing length before last element. which is: [[3], [2, 3], [4, 3, 1]] (first element with length 1, second with length 2 and so on)

if the lis was of 5 elements: lis = [3, 2, 3, 4, 3] the result should be [[3], [2, 3]] because there aren't three elements ahead

CodePudding user response:

You can use:

def cut(l):
    i = 1
    pos = 0
    out = []
    while pos<len(l)-i 1:
        out.append(l[pos:pos i])
        pos  = i
        i  = 1
    return out

cut([1,2,3,4,5,6,7,8,9,10,11])

output:

[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]

variant

Other approach for fun if we do not want to test position relative to the end at each step.

The sum of the first n integers is x = n*(n 1)/2, we can calculate that, given x, n = int((math.sqrt(1 8*x)-1)/2). This enables us to directly know how many steps there are:

# function to calculate the number of steps from the list length
def nb(x):
    import math
    return int((math.sqrt(1 8*x)-1)/2)
# nb(11) -> 4

def cut(l):
    pos = 0
    out = []
    for i in range(1, nb(len(l)) 1):
        out.append(l[pos:pos i])
        pos  = i
    return out

cut([1,2,3,4,5,6,7,8,9,10,11])

CodePudding user response:

[lst[sum(range(i 1)):sum(range(i 1))   i   1] for i in range(len(lst)) if len(lst[sum(range(i 1)):])>=i]

output: [[3], [2, 3], [4, 3, 1]]

a little shorter

[lst[l:l   i   1] for i in range(len(lst)) if len(lst[(l := sum(range(i 1))):])>=i]

At first this was my answer:

[lst[i:2*i   1] for i in range(len(lst)) if len(lst[i:])>=i]

but this starts at previously used items

output: [[3], [2, 3], [3, 4, 3], [4, 3, 1]]

  • Related