1
votes

I'm trying to use itertools to create pairs of all possible combinations of three coin tosses, e.g., ['HHH', 'TTT'], ['HHH', 'THH'] .. [TTT', 'HTH'], .. , etc. I want to access the pairs as individual strings, and so far I have this; which doesn't seem very optimal?

from itertools import *

combs = []

combs.extend([list(x) for x in combinations(product('HT', repeat = 3), 2)])

for l in combs:
    (one, two) = l
    print ''.join(one), ''.join(two)

==edit==

Not sure whether it's ok to edit the original question - but here goes ..

What's the best way to remove duplicates, e.g., the pair (THT, THT) and reversed pairs - duplicates in reverse, e.g., (HHH, TTT) and (TTT, HHH)?

Thank you.

4
Just to be clear, your code won't produce HHH HHH. Is that what you want? - DSM
Why are you going for pairs? - ATOzTOA

4 Answers

4
votes

Generate all 3-tosses, then from that list generate all pairs.

import itertools

toss3 = map(''.join, itertools.product('HT', repeat=3))
toss3_pairs = list(itertools.product(toss3, repeat=2))
0
votes
>>> combs.extend([''.join(y) for x in combinations(product('HT', repeat = 3), 2) for y in x])
>>> combs
['HHH', 'HHT', 'HHH', 'HTH', 'HHH', 'HTT', 'HHH', 'THH', 'HHH', 'THT', 'HHH', 'TTH', 'HHH', 'TTT', 'HHT', 'HTH', 'HHT', 'HTT', 'HHT', 'THH', 'HHT', 'THT', 'HHT', 'TTH', 'HHT', 'TTT', 'HTH', 'HTT', 'HTH', 'THH', 'HTH', 'THT', 'HTH', 'TTH', 'HTH', 'TTT', 'HTT', 'THH', 'HTT', 'THT', 'HTT', 'TTH', 'HTT', 'TTT', 'THH', 'THT', 'THH', 'TTH', 'THH', 'TTT', 'THT', 'TTH', 'THT', 'TTT', 'TTH', 'TTT']
0
votes

Try this code:

#without itertools

def tosses(N):
    L = [''] 
    for i in range(0,N):
        L=[l+'H' for l in L]+[l+'T' for l in L]
    return L

print tosses(4)
-1
votes

Try this:

import itertools

combs = []

combs.extend([y for y in itertools.combinations([''.join(x) for x in itertools.product('HT', repeat = 3)], 2)])

print combs

Output:

[('HHH', 'HHT'), ('HHH', 'HTH'), ('HHH', 'HTT'), ('HHH', 'THH'), ('HHH', 'THT'), ('HHH', 'TTH'), ('HHH', 'TTT'), ('HHT', 'HTH'), ('HHT', 'HTT'), ('HHT', 'THH'), ('HHT', 'THT'), ('HHT', 'TTH'), ('HHT', 'TTT'), ('HTH', 'HTT'), ('HTH', 'THH'), ('HTH', 'THT'), ('HTH', 'TTH'), ('HTH', 'TTT'), ('HTT', 'THH'), ('HTT', 'THT'), ('HTT', 'TTH'), ('HTT', 'TTT'), ('THH', 'THT'), ('THH', 'TTH'), ('THH', 'TTT'), ('THT', 'TTH'), ('THT', 'TTT'), ('TTH', 'TTT')]
>>>