FlamingPickle FlamingPickle - 1 month ago 7
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:

HHHH, HHHT, HHTT, etc.


Thanks in advance!

Answer

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

Comments