Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all possible sublists of a list

Tags:

python

Let's say I have the following list

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

I want to find all possible sublists of a certain lenght where they don't contain one certain number and without losing the order of the numbers.

For example all possible sublists with length 6 without the 12 are:

[1,2,3,4,5,6]
[2,3,4,5,6,7]
[3,4,5,6,7,8]
[4,5,6,7,8,9]
[5,6,7,8,9,10]
[6,7,8,9,10,11]
[13,14,15,16,17,18]

The problem is that I want to do it in a very big list and I want the most quick way.

Update with my method:

oldlist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
newlist = []
length = 6
exclude = 12
for i in oldlist:
   if length+i>len(oldlist):
       break
   else:
       mylist.append(oldlist[i:(i+length)]
for i in newlist:
    if exclude in i:
       newlist.remove(i)

I know it's not the best method, that's why I need a better one.

like image 823
Tasos Avatar asked Jun 12 '13 09:06

Tasos


1 Answers

A straightforward, non-optimized solution would be

result = [sublist for sublist in 
        (lst[x:x+size] for x in range(len(lst) - size + 1))
        if item not in sublist
    ]

An optimized version:

result = []
start = 0
while start < len(lst):
    try:
        end = lst.index(item, start + 1)
    except ValueError:
        end = len(lst)
    result.extend(lst[x+start:x+start+size] for x in range(end - start - size + 1))
    start = end + 1
like image 147
georg Avatar answered Oct 01 '22 01:10

georg