Issue
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
Solution
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])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.