The folder structure should now look like this;
├── blackjack
│ ├── __init__.py
│ └── common.py
├── setup.py
└── tests
├── __init__.py
└── test_blackjack.py
The __init__.py
files should be empty.
blackjack/common.py
def card_score(cards):
if not isinstance(cards, str):
raise ValueError("The input for `card_score` needs to be a string.")
if len(cards) < 2:
raise ValueError("The `card_score` function requires at least 2 cards.")
numbers = [c for c in cards if c in "23456789"]
faces = [c for c in cards if c in "JQK"]
n_aces = sum([1 for c in cards if c == "A"])
score = sum([int(i) for i in numbers]) + len(faces) * 10
while n_aces > 0:
score += 1 if score + 11 > 21 else 11
n_aces -= 1
return score if score <= 21 else 0
tests/test_blackjack.py
import pytest
from blackjack.common import card_score
@pytest.mark.parametrize("cards,score", [('JK', 20), ('KKK', 0), ('AA', 12), ('AK', 21)])
def test_simple_usecase(cards, score):
assert card_score(cards) == score
To be able to work on the package in developer mode you'll need to run;
python setup.py develop
And from here you can safely run pytest again.
pytest