# Calculate possibilities of throwing a coin N times in Python

## The challenge

In this challenge, you will be given an integer n, which is the number of times that is thrown a coin. You will have to return an array of strings for all the possibilities (heads[H] and tails[T]). Examples:

`coin(1) should return {"H", "T"}`
`coin(2) should return {"HH", "HT", "TH", "TT"}`
`coin(3) should return {"HHH", "HHT", "HTH", "HTT", "THH", "THT", "TTH", "TTT"}`

When finished sort them alphabetically.

In C and C++ just return a `char*` with all elements separated by`,` (without space):
`coin(2) should return "HH,HT,TH,TT"`

INPUT:
`0 < n < 18`

Careful with performance!! You’ll have to pass 3 basic test (n = 1, n = 2, n = 3), many medium tests (3 < n <= 10) and many large tests (10 < n < 18)

## The solution in Python code

Option 1:

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```from itertools import product

def coin(n):
return list(map(''.join, product(*(["HT"]*n))))
```Code language: Python (python)```

Option 2:

``````def coin(n): return [x + v for x in coin(n-1) for v in 'HT'] if n - 1 else ['H','T']
```Code language: Python (python)```

Option 3:

``````memo = {1 : ["H", "T"]}
for j in range(2, 18):
b = memo[j-1]
total = set()
for i in b:
memo[j] = sorted(total)

def coin(n):
return memo[n]
```Code language: Python (python)```

## Test cases to validate our solution

``````test.describe("Basic Tests")
test.assert_equals(coin(1),["H","T"])
test.assert_equals(coin(2),["HH", "HT", "TH", "TT"])
test.assert_equals(coin(3),["HHH", "HHT", "HTH", "HTT", "THH", "THT", "TTH", "TTT"])
```Code language: Python (python)```

See also  How to Delete a Secret in Kubernetes
Tags:
Subscribe
Notify of 