Solution to problem 17 in Python

This commit is contained in:
David Doblas Jiménez 2023-11-30 16:27:58 +01:00
parent e690ae9260
commit 144be11c26

60
src/Year_2015/P17.py Normal file
View File

@ -0,0 +1,60 @@
# --- Day 17: No Such Thing as Too Much ---
# The elves bought too much eggnog again - 150 liters this time. To fit it all
# into your refrigerator, you'll need to move it into smaller containers. You
# take an inventory of the capacities of the available containers.
# For example, suppose you have containers of size 20, 15, 10, 5, and 5 liters.
# If you need to store 25 liters, there are four ways to do it:
# 15 and 10
# 20 and 5 (the first 5)
# 20 and 5 (the second 5)
# 15, 5, and 5
# Filling all containers entirely, how many different combinations of containers
# can exactly fit all 150 liters of eggnog?
from itertools import combinations
with open("files/P17.txt") as f:
containers = [int(c) for c in f.read().strip().split()]
def part_1():
total = 0
for i, _ in enumerate(containers):
for combination in combinations(containers, i):
if sum(combination) == 150:
total += 1
print(f"There are {total} different combinations")
# --- Part Two ---
# While playing with all the containers in the kitchen, another load of eggnog
# arrives! The shipping and receiving department is requesting as many
# containers as you can spare.
# Find the minimum number of containers that can exactly fit all 150 liters of
# eggnog. How many different ways can you fill that number of containers and
# still hold exactly 150 litres?
# In the example above, the minimum number of containers was two. There were
# three ways to use that many containers, and so the answer there would be 3.
def part_2():
minimum = 0
for i, _ in enumerate(containers):
for combination in combinations(containers, i):
if sum(combination) == 150:
minimum += 1
if minimum:
break
print(f"The minimum number of containers is {minimum}")
if __name__ == "__main__":
part_1()
part_2()