FlamingPickle - 11 months ago 75

Python Question

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 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