Home > Enterprise >  simpler(save memory) way to get all possible combinations in order of increasing length
simpler(save memory) way to get all possible combinations in order of increasing length

Time:04-20

I am trying to get all the possible combinations of listA in order of increasing length. This is easy to do, but the current code I have returns Memory error once my list goes above 1000. How do I do the same with a code that does not use as much memory.

original_list = ['1', '2', '3', '4']

#code:

modified_list= [original_list[i:j   1] for i in range(len(original_list)) for j in range(i   1, len(original_list))]

print(modified_list)

#output:

#nodified_list = [['1', '2'],['1', '2', '3'],['1', '2', '3', '4'],
                  ['2', '3'],['2', '3', '4'],['3', '4']]

I saw a similar code but this one prints all the combinations of all the elements inside the list.

import itertools
List =  []
for L in range(0, len(original_list) 1):
    for subset in itertools.combinations(original_list, L):
        subset = str(subset).replace('(','[').replace(')',']')                     #.replace(',','')
        List.append(subset)

CodePudding user response:

it's most probably that your modified list that takes up the memory... try to print the [original_list[i:j 1] without saving it in another list. that shouldn't take more memory than your original list size.

CodePudding user response:

Generator expression saves memory a lot, instead of list you can use this:

subsets = (original_list[i:j   1] for i in range(len(original_list)) for j in range(i   1, len(original_list)))

Also if you want to print, iterate through each element, do not convert to list.

for i in subsets:
    print(i)
  • Related