0

making a recursive program that goes through recipes for ingredients, if the ingredients of the recipe is a recipe itself it should get that recipe's ingredients recursively.

def get_prep_ingredients_recursively(quantity, menu_item_preps, prep_id, ingredients_list=dict(), **kwargs):
    # get the ingredients for the menu item that has the prep_id given from a dict of prep items
    # if the ingredient is a base (has itemtypename prep) go recursively to get the prep's ingredients
    ingredients_list_results = ingredients_list
    for Prep_item in menu_item_preps:
        if Prep_item['ID'] == prep_id:
            for prep_ingredient in Prep_item['SubItems']:
                if prep_ingredient['ItemTypeName'] == "Prep":
                    """go recursive if the ingredient has prep"""
                    ingredients_list_results = get_prep_ingredients_recursively(quantity / Prep_item['ProdQuantity'],
                                                                                menu_item_preps,
                                                                                prep_ingredient['ItemID'],
                                                                                ingredients_list_results)
                else:
                    """add the ingredients * the quantity"""
                    ingredients_list_results[prep_ingredient['ItemID']] = {
                        'Name': prep_ingredient['ItemName'],
                        'Ingredient_Amount': (prep_ingredient['UsageNet'] / Prep_item['ProdQuantity'] * quantity)
                    }
                    print(
                        f"{prep_ingredient['ItemName']} -- {(prep_ingredient['UsageNet'] / Prep_item['ProdQuantity'] * quantity)}")
    return ingredients_list_results

the code above prints the correct outputs, but the dictionary that it returns is full of a bunch of stuff that it shouldn't have

zcstover
  • 11
  • 2
  • 1
    I haven't fully read your code, but I'd be shocked if the issue was something other than the mutable default argument you're using. See [this question, and its answers](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) for more details. – Blckknght Oct 08 '21 at 21:53
  • i'm not modifying the ingredients_list in the function, i make a new dictionary based off of it. unless that dictionary maintains a reference relationship to the input dictionary i don't know how it would get messed up – zcstover Oct 08 '21 at 22:03
  • it did have something to do with mutable default arguments, when i changed the input from the origin to have an empty dictionary it was outputing the correct ingredients. don't understand why exactly – zcstover Oct 08 '21 at 22:31
  • Perhaps did you think that `ingredients_list_results = ingredients_list` made a new dictionary? It doesn't, it just creates a new reference to the same dictionary. – Blckknght Oct 08 '21 at 22:53

0 Answers0