Solution to problem 4 in Python

This commit is contained in:
David Doblas Jiménez 2022-02-28 17:50:48 +01:00
parent bb777a3e12
commit 3f7ed79f0c

55
src/Year_2015/P4.py Normal file
View File

@ -0,0 +1,55 @@
# --- Day 4: The Ideal Stocking Stuffer ---
# Santa needs help mining some AdventCoins (very similar to bitcoins) to use as
# gifts for all the economically forward-thinking little girls and boys.
# To do this, he needs to find MD5 hashes which, in hexadecimal, start with at
# least five zeroes. The input to the MD5 hash is some secret key (your puzzle
# input, given below) followed by a number in decimal. To mine AdventCoins, you
# must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...)
# that produces such a hash.
# For example:
# If your secret key is abcdef, the answer is 609043, because the MD5 hash
# of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the
# lowest such number to do so.
# If your secret key is pqrstuv, the lowest number it combines with to make
# an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of
# pqrstuv1048970 looks like 000006136ef....
# Your puzzle input is yzbqklnj.
from hashlib import md5
_input = "yzbqklnj"
def part_1() -> None:
end = "9" * len(_input)
for num in range(int(end)):
testing = _input + str(num)
result = md5(testing.encode()).hexdigest()
if result.startswith("0" * 5):
print(f"The lowest positive number is {num}")
break
# --- Part Two ---
# Now find one that starts with six zeroes.
def part_2() -> None:
end = "9" * len(_input)
for num in range(int(end)):
testing = _input + str(num)
result = md5(testing.encode()).hexdigest()
if result.startswith("0" * 6):
print(f"The lowest positive number is {num}")
break
if __name__ == "__main__":
part_1()
part_2()