0

How can i get all possible combinations of list of length n in python i have written a code for string but list i am not able to do can any one help me.

def combo(w, l):
    lst = []
    for i in range(len(w)):
        if l == 1:
            lst.append(w[i])
        for c in combo(w[i+1:], l-1):
            lst.append(w[i] + c)
    return lst

comb=map(list,combo('12345',3))

above code is to get the combinations of string it gives correct output:

['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']

3 Answers3

0

You can also just use itertools.combinations:

>>> import itertools

>>> print(["".join(x) for x in itertools.combinations('12345', 2)])
['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']

>>> print([list(x) for x in itertools.combinations(['1', '2', '3', '4', '5'], 2)])
[['1', '2'], ['1', '3'], ['1', '4'], ['1', '5'], ['2', '3'], ['2', '4'], ['2', '5'], ['3', '4'], ['3', '5'], ['4', '5']]

>>> print(["".join(x) for x in itertools.combinations(['1', '2', '3', '4', '5'], 2)])
['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
0

Are you looking for this :

import itertools


def combinations(list_1):
    split_list=[item for item in list_1[0]]
    return [''.join(sub_item) for sub_item in itertools.combinations(split_list,r=2)]

print(combinations(['12345']))

output:

['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
0

Of course, there are utils in itertools, but you can fix your function by adjusting two lines as follows:

# note the '[]' around w[i] in those lines
lst.append([w[i]]) 
# ...
lst.append([w[i]] + c)
# ...

Strings are unique sequences in the sense that their elements (chars so to speak) are strings themselves and can be concatenated by +. With most other sequence/iterable types, you have to clearly differentiate between the sequence and its elements. In this case you want to concatenate (sub)lists, not elements.

user2390182
  • 72,016
  • 6
  • 67
  • 89