FlamingPickle FlamingPickle - 9 months ago 48
Python Question

Have python program print out all combinations of coin flips

I am working on a python program that involves coin flips. How can I get a python program to list out all possibly combinations of 4 coin flips?

So I want the program to output:


Thanks in advance!

Answer Source

You can use itertools.product:

>>> list(itertools.product("HT", repeat=4))
[('H', 'H', 'H', 'H'),
 ('H', 'H', 'H', 'T'),
 ('H', 'H', 'T', 'H'),
 ('H', 'H', 'T', 'T'),
 ('H', 'T', 'H', 'H'),
 ('H', 'T', 'H', 'T'),
 ('H', 'T', 'T', 'H'),
 ('H', 'T', 'T', 'T'),
 ('T', 'H', 'H', 'H'),
 ('T', 'H', 'H', 'T'),
 ('T', 'H', 'T', 'H'),
 ('T', 'H', 'T', 'T'),
 ('T', 'T', 'H', 'H'),
 ('T', 'T', 'H', 'T'),
 ('T', 'T', 'T', 'H'),
 ('T', 'T', 'T', 'T')]

Then if you want a string back again, just call ''.join on each tuple