Ryan
Ryan

Reputation: 10179

Get combinations of list only if one of first element is present

Beginner question.

Given a list of N elements of K characters, all possible output strings such that ith character of output string is from the ith input string.

Example:
ex:  N=3 K=2
input = ['ab', 'xy', 'mn']
output =['axm' , 'axn', 'ayn','aym', 'bxm' ,'bxn','byn' ,'bym']

As you see the first element in the output is always from the the first string in the output.

Any suggestions would be helpful,thanks in advance.

so this is what i have

def foo(K, N, str_list):
    """ 
    K int
    N int
    str_list list[str]
    """
    start_element = str_list[0]
    rem_list = str_list[1:]

    for item in range(N):
      word = rem_list[item]
      for i in range(K):
        print(word[i])  

    return 

my approach was to take the first element as constant and then loop through other elements ,but its not quite working

Upvotes: 1

Views: 98

Answers (1)

Roy2012
Roy2012

Reputation: 12543

with itertools

Use itertools.product:

input = ['ab', 'xy', 'mn']
["".join(x) for x in itertools.product(*input)]

result:

['axm', 'axn', 'aym', 'ayn', 'bxm', 'bxn', 'bym', 'byn']

without itertools

One alternative, if one prefers not to use itertools, is to use a recursive solution:

def cross_prod(l):
    if len(l) == 1:
        return [c for c in l[0]]
    else:
        sub_prod = cross_prod(l[1:])
        res = [e + sub_res for e in l[0] for sub_res in sub_prod ]
        return res

input = ['ab', 'xy', 'mn']
print(cross_prod(input))

The result, again, is:

['axm', 'axn', 'aym', 'ayn', 'bxm', 'bxn', 'bym', 'byn']

Upvotes: 1

Related Questions