<jupyter_start><jupyter_text>Advent of Code 2015, Day 4> The Ideal Stocking Stuffer....- toc: true- badges: true- comments: true- categories: [adventofcode]- permalink: /2022/06/04/advent_of_code_2015_d4/  Dependencies<jupyter_code>import hashlib<jupyter_output><empty_output><jupyter_text>Functions<jupyter_code>def mine_advent_coins(key: str, n: int) -> int:
    """Return the suffix needed so md5(key + suffix).hex begins with n_zeroes.
    """
    def hex_prefix(suffix, n) -> str:
        return hashlib.md5(f'{(key + str(suffix))}'.encode()).hexdigest()[:n]

    suffix = 1
    prefix, target_prefix =  hex_prefix(suffix, n), '0' * n
    while prefix != target_prefix:
        suffix += 1
        prefix = hex_prefix(suffix, n)

    return suffix<jupyter_output><empty_output><jupyter_text>Initialise the input<jupyter_code>KEY = '<KEY>'<jupyter_output><empty_output><jupyter_text>Solution Part 1<jupyter_code>print(f'Solution = {mine_advent_coins(KEY, 5)}')<jupyter_output>Solution = 117946<jupyter_text>Part 2<jupyter_code>print(f'Solution = {mine_advent_coins(KEY, 6)}')<jupyter_output>Solution = 3938038<jupyter_text>Performance<jupyter_code>print('Part 1 =')
%timeit mine_advent_coins(KEY, 5)
print('Part 2 =')
%timeit mine_advent_coins(KEY, 6)<jupyter_output>Part 1 =
151 ms ± 1.57 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Part 2 =
5.11 s ± 71.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
{'fraction_non_alphanumeric': 0.13744740532959326, 'fraction_numerical': 0.04417952314165498, 'mean_word_length': 5.370535714285714, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '306351', 'license': 'MIT', 'n_tokens_mistral': 606, 'n_tokens_neox': 538, 'n_words': 120, 'path': '_notebooks/2022-06-04-advent_of_code_2015_day4.ipynb', 'repo_name': 'ljk233/blog', 'size': '1429'}