1

I have 2 inputs as:

p = 7
s = [2 2 8 1 3]

I know how to get basic list subsets by itertool.combinations but want I want is contiguous sublists with each sublist with sum of their elements being less than p.

So output will be:

 [2],[2,2],[2],[1],[1,3],[3]  

Here I got 6 such sublists where for each sublist, sum(sublist) < p.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Shivkumar kondi
  • 6,458
  • 9
  • 31
  • 58

2 Answers2

4

try this :

p = 7
s = [2,2,8,1,3]
ans=[]
for i in xrange(len(s)):
    for j in xrange(i,len(s)):
        if sum(s[i:j+1])<p:
            ans.append(s[i:j+1])
print ans

output:

[[2], [2, 2], [2], [1], [1, 3], [3]]
Karan Nagpal
  • 341
  • 2
  • 10
  • which you can write as a list comprehension: `ans = [s[i:j+1] for i in xrange(len(s)) for j in xrange(i,len(s)) if sum(s[i:j+1]) < p]` – Julien Spronck Dec 01 '16 at 19:23
0

If you like one liners, you can try this:

>>> sum([[s[i:j+1] for j in range(i, len(s)) if sum(s[i:j+1])<p] for i in range(len(s))], [])
[[2], [2, 2], [2], [1], [1, 3], [3]]

The sum(list_of_lists, []) is flattening the list of lists created in the list comprehension, as shown here.

Or you can use what Julien Spronck mentioned in his comment, which is far superior.

Community
  • 1
  • 1
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
  • I have been trying to come up with a list comprehension for quite some time now, instead of going to sleep this late at night. It is 1:30AM here now. My head is definitely not in a good shape. – Sнаđошƒаӽ Dec 01 '16 at 19:37