Xyzzel
Xyzzel

Reputation: 115

How to merge all the elements of a list

I have a task to print out all the combinations of 'D' and 'E' in 4 character. What i have:

x = product(['D', 'E'], repeat=4)
p = ''.join(str(s) for s in x)
lxx = []
lxx.append(p)
f = ''.join(lxx)
print(f)

What i get:

('D', 'D', 'D', 'D')('D', 'D', 'D', 'E')('D', 'D', 'E', 'D')('D', 'D', 'E', 'E')('D', 'E', 'D', 'D')('D', 'E', 'D', 'E')('D', 'E', 'E', 'D')('D', 'E', 'E', 'E')('E', 'D', 'D', 'D')('E', 'D', 'D', 'E')('E', 'D', 'E', 'D')('E', 'D', 'E', 'E')('E', 'E', 'D', 'D')('E', 'E', 'D', 'E')('E', 'E', 'E', 'D')('E', 'E', 'E', 'E')

What i need:

DDDD
DDDE
DDED
DDEE
DEDD
DEDE
DEED
DEEE
EDDD
EDDE
EDED
EDEE
EEDD
EEDE
EEED
EEEE

Upvotes: 3

Views: 81

Answers (3)

jtagle
jtagle

Reputation: 302

In case you need something "less magical", I think you are looking for something like this:

def product(items, repeat, currentstring="", ret = None):
    if ret == None:
        ret = list()
    if len(currentstring) == repeat:
        ret.append(currentstring)
        print(currentstring)
    else:
        for letter in items:
            product(items, repeat, currentstring + letter, ret)
    return ret

product(['D', 'E'], repeat=4)

Other answers seems to work to. So, use this just in case you wanted to practice recursion or something. Good thing about it, is that is allows to receive more letters. Like, you could try

product(['D', 'E', 'F', 'G'], repeat=4)

Upvotes: 0

briancaffey
briancaffey

Reputation: 2559

from itertools import product
x = product(['D', 'E'], repeat=4)
for word in ["".join(x) for x in list(x)]: print(word)

DDDD
DDDE
DDED
DDEE
DEDD
DEDE
DEED
DEEE
EDDD
EDDE
EDED
EDEE
EEDD
EEDE
EEED
EEEE

Upvotes: 1

jpp
jpp

Reputation: 164613

This will work:

from itertools import product

list(product(['D', 'E'], repeat=4))

For pretty printing:

for i in product(['D', 'E'], repeat=4):
    print(''.join(i))

# DDDD
# DDDE
# DDED
# DDEE
# DEDD
# DEDE
# DEED
# DEEE
# EDDD
# EDDE
# EDED
# EDEE
# EEDD
# EEDE
# EEED
# EEEE

Upvotes: 4

Related Questions