Stephan K.
Stephan K.

Reputation: 15702

Create new set of subsets out of set of subsets (python)

How would you achieve the following (in Python):

List 1: qw,wq

Now add e before the first element and behind each element of each subset

List 2: eqw, qew, qwe, ewq, weq, wqe

Needless to say this should be constructed in a general way, so that List 1 could be of any proportion.

I was thinking of a recursion, but yet my function uses many if/elses and is not too nice.

Upvotes: 0

Views: 104

Answers (2)

Using the the generator in a slightly cleaner fashion

elements = ['qw', 'wq']

def silly_op(lst, char):
    for e in lst:
        for i in range(len(e) + 1):
            yield e[:i] + char + e[i:]

print(list(silly_op(elements, 'e')))

Prints

['eqw', 'qew', 'qwe', 'ewq', 'weq', 'wqe']

No recursion, no if, just 2 nested loops + generator.

Of course if you want to get the results as a list, you can write

def silly_op(lst, char):
    rv = []

    for e in lst:
        for i in range(len(e) + 1):
            rv.append(e[:i] + char + e[i:])

    return rv

Or if the question is about permutations, as suggested by @AdamSmith,

print(list(''.join(i) for i in itertools.permutations('wq' + 'e')))

prints

['wqe', 'weq', 'qwe', 'qew', 'ewq', 'eqw']

Upvotes: 2

Hyperboreus
Hyperboreus

Reputation: 32429

This could work:

a = ['qw', 'wq', 'test']

def merge (tgt, letter):
    for i, _ in enumerate (tgt):
        yield tgt [:i] + letter + tgt [i:]
    yield tgt + letter

b = [x for tgt in a for x in merge (tgt, 'e') ]
print (b)

It prints

['eqw', 'qew', 'qwe', 'ewq', 'weq', 'wqe', 'etest', 'teest', 'teest', 'teset', 'teste']

I hope this is the expected result.


Or taking into consideration Steven's input:

def merge (tgt, letter):
    for i in range (len (tgt) + 1):
        yield tgt [:i] + letter + tgt [i:]

Upvotes: 3

Related Questions