Home > Enterprise >  Print consecutive pair of subsets with increasing size from a given list of numbers
Print consecutive pair of subsets with increasing size from a given list of numbers

Time:02-18

Example 1,

Input: [a,b,c,d]

Output: [[a],[a,b],[b,c],[c,d],[a,b,c],[b,c,d],[a,b,c,d]]

Example 2,

Input: [1,2,3,4,5]

Output: [[1],[1,2],[2,3],[3,4],[4,5],[1,2,3],[2,3,4],[3,4,5],[1,2,3,4],[2,3,4,5],[1,2,3,4,5]]

In the same way, the number of elements in the pair starting from 1 increases till 'n'(size of the given list)

Is there a possible way of handling, a given list of any size (If possible in Python)

Extra Info:

I have tried this code, which returns pair of 3 elements in the output but I want to return first 1 element, next with 2 elements, till n-1 elements as I mentioned above in the example

Input:

listA = [51,23,11,45]
res = [[listA[i], listA[i   1],listA[i   2]] for i in range(len(listA) - 2)]
print("List with paired elements: \n",res)

Output:

List with paired elements: [[51, 23, 11], [23, 11, 45]]

CodePudding user response:

I am a bit confused about the output requirement, but here is something that produces the result I think you are looking for:

def get_list_of_size(l, n):
    return [l[i:i n] for i in range(len(l)-n 1)]

def get_consecutive_ss(l):
    output=[]
    for i in range(len(l)):
        output =get_list_of_size(l, i 1)
    return [output[0]] output[len(l):]


l = [1,2,3,4,5]
l2=['a','b','c','d']

print(get_consecutive_ss(l))
print(get_consecutive_ss(l2))

Output:

[[1], [1, 2], [2, 3], [3, 4], [4, 5], [1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3, 4], [2, 3, 4, 5], [1, 2, 3, 4, 5]]
[['a'], ['a', 'b'], ['b', 'c'], ['c', 'd'], ['a', 'b', 'c'], ['b', 'c', 'd'], ['a', 'b', 'c', 'd']]

CodePudding user response:

Fisrt way

You can do it automatically using a package more_itertools.substrings:

import more_itertools
list(more_itertools.substrings([2,3,5,7,11]))

Output:

[(2,), (3,), (5,), (7,), (11,), (2, 3), (3, 5), (5, 7), (7, 11), (2, 3, 5), (3, 5, 7), (5, 7, 11), (2, 3, 5, 7), (3, 5, 7, 11), (2, 3, 5, 7, 11)]

You could also check a source code of implementation of this method or make it yourself as an exercise.

Second way

It allows you to achieve exactly what you expect using more_itertools.sliding_window:

from itertools import chain
from more_itertools import sliding_window

x = [2,3,5,7,11]
first_part = [(x[0],)]
second_part = [sliding_window(x, n) for n in range(2, len(x) 1)]
list(chain(first_part, *second_part))

Output:

[(2,), (2, 3), (3, 5), (5, 7), (7, 11), (2, 3, 5), (3, 5, 7), (5, 7, 11), (2, 3, 5, 7), (3, 5, 7, 11), (2, 3, 5, 7, 11)]
  • Related