Is it possible to get all combinations of elements in case they are neighbours?
Here is the example:
EDIT: I want to use it on strings, not only numbers. For example: [Explain,it,to,me,please]
List:
[0,1,2,3,4]
Result:
[0,1,2,3,4],
[0,1,2,3],
[1,2,3,4],
[0,1,2],
[1,2,3],
[2,3,4],
[0,1],
[1,2],
[2,3],
[3,4],
[0],
[1],
[2],
[3],
[4]
There wouldn't be for example [0,2,3]
etc. in the result because 0
and 2
are not neighbours in the sorted list above.
I tried to use itertools.combinations
but it gives all combinations.
The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.
This method takes a list and an input r as an input and return an object list of tuples which contain all possible combination of length r in a list form.
You can do:
>>> L = [0,1,2,3,4]
>>> result = [L[i:j] for i in xrange(len(L)) for j in xrange(i + 1, len(L) + 1)]
>>> pprint.pprint(result)
[[0],
[0, 1],
[0, 1, 2],
[0, 1, 2, 3],
[0, 1, 2, 3, 4],
[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
[2],
[2, 3],
[2, 3, 4],
[3],
[3, 4],
[4]]
Then, to sort by descending length and ascending values:
>>> result.sort(key=lambda x: (-len(x), x))
>>> pprint.pprint(result)
[[0, 1, 2, 3, 4],
[0, 1, 2, 3],
[1, 2, 3, 4],
[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[0],
[1],
[2],
[3],
[4]]
And for strings it would produce:
>>> L = ['Explain', 'it', 'to', 'me', 'please']
>>> result = [L[i:j] for i in xrange(len(L)) for j in xrange(i + 1, len(L) + 1)]
>>> result.sort(key=lambda x: (-len(x), x))
>>> pprint.pprint(result)
[['Explain', 'it', 'to', 'me', 'please'],
['Explain', 'it', 'to', 'me'],
['it', 'to', 'me', 'please'],
['Explain', 'it', 'to'],
['it', 'to', 'me'],
['to', 'me', 'please'],
['Explain', 'it'],
['it', 'to'],
['me', 'please'],
['to', 'me'],
['Explain'],
['it'],
['me'],
['please'],
['to']]
Here's one way using an old window
recipe from itertools
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def all_windows(seq):
for l in xrange(1, len(seq) + 1):
for w in window(seq, l):
yield w
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With