I am working on a code that will minimize the number of ingredients necessary to make some dishes.
Each dish can be prepared in an arbitrary large number of ways, with combinations of two ingredients. The result is a tuple of recipes.
I have a code that works, but if there are a large number of items, it is very slow and causes "memory errors" in Python 3.9 on a laptop that has 32Go of RAM.
Here's a simple example, with 3 dishes:
import itertools as it
salty_egg = (("egg", "salt"), ("egg", "soy sauce"), ("egg", "mountain salt"))
meat_starter = (("egg", "ham"), ("carrot", "ham"), ("ham", "salt"))
soy_carrot = (("carrot", "soy sauce"), ("pink carrot", "soy sauce"))
recipes = (salty_egg, meat_starter, soy_carrot)
recipe_and_sizes = [(len(set(it.chain(*x))), x) for x in it.product(*recipes)]
recipes = min(recipe_and_sizes)[1]
print(recipes)
(('egg', 'soy sauce'), ('carrot', 'ham'), ('carrot', 'soy sauce'))
Any idea how to speed this up or maybe another approach to solve the problem?