Home > Back-end >  How can I use my helper functions to get the correct output
How can I use my helper functions to get the correct output

Time:11-22

So I created a helper function to help my main function in extracting stuff from a dictionary... and here is my code and function

def rdict(recipes):
    recipes_splitted = {}
    for r in recipes:
        recipe_name, parts = r.split(":")
        recipe_parts = {}
        for part in parts.split(','):
            product, number = part.split('*')
            recipe_parts[product] = int(number)
        recipes_splitted[recipe_name] = recipe_parts
    return recipes_splitted
def extract(recipes, data):
    result = []
    for r in recipes:
        tmp = []
        for key in data[r]:
            tmp.append(f"{key}:{data[r][key]}")
        final_string = ""
        for i in range(len(tmp)):
            if i < len(tmp) - 1:
                final_string  = tmp[i]   ", "
            else:
                final_string  = tmp[i]
        result.append(final_string)
    return result

So what I'm trying to do is make sure data in extract(recipe, data) go through rdict(data) since rdict will convert data into a dictionary, which is what I need.. However, when I tried doing for key in rdict(data[r]): the output returns Error. String is not supscriptable..

what should I do to successfully implement the changes??

Edit

So from my current code, here is a sample input..

print(extract(recipes = ['T-Bone', 'Green Salad1'],data = ["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10",
"Green Salad1:Cabbage*10,Carrot*2,Pineapple*5",
"T-Bone:Carrot*2,Steak Meat*1"]
))

and in order for my code to work, it has to be like this

print(extract(recipes = ['T-Bone', 'Green Salad1'], data = {'Pork Stew': {'Cabbage': 5, 'Carrot': 1, 'Fatty Pork': 10}, 'Green Salad1': {'Cabbage': 10, 'Carrot': 2, 'Pineapple': 5},'T-Bone': {'Carrot': 2, 'Steak Meat': 1}}))

So from the input, data should be changed from

data = ["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10",
    "Green Salad1:Cabbage*10,Carrot*2,Pineapple*5",
    "T-Bone:Carrot*2,Steak Meat*1"]

to

data = {'Pork Stew': {'Cabbage': 5, 'Carrot': 1, 'Fatty Pork': 10}, 'Green Salad1': {'Cabbage': 10, 'Carrot': 2, 'Pineapple': 5},'T-Bone': {'Carrot': 2, 'Steak Meat': 1}}

CodePudding user response:

Convert the data to dict in extract().

recipes = ['T-Bone', 'Green Salad1']

data = ["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10",
"Green Salad1:Cabbage*10,Carrot*2,Pineapple*5",
"T-Bone:Carrot*2,Steak Meat*1"]


def rdict(recipes):
    recipes_splitted = {}
    for r in recipes:
        recipe_name, parts = r.split(":")
        recipe_parts = {}
        for part in parts.split(','):
            product, number = part.split('*')
            recipe_parts[product] = int(number)
        recipes_splitted[recipe_name] = recipe_parts
    return recipes_splitted


def extract(recipes, data):
    data = rdict(data)  # convert data to dict first
    result = []
    for r in recipes:
        tmp = []
        for key in data[r]:            
            tmp.append(f"{key}:{data[r][key]}")
        final_string = ""
        for i in range(len(tmp)):
            if i < len(tmp) - 1:
                final_string  = tmp[i]   ", "
            else:
                final_string  = tmp[i]
        result.append(final_string)
    return result

print(extract(recipes, data))

Output:

['Carrot:2, Steak Meat:1', 'Cabbage:10, Carrot:2, Pineapple:5']

CodePudding user response:

  1. Reanmed rdict to parse_recipe, and modified it to return a tuple that is lighter and easier to process

  2. In extract:

    a) Build a dict of recipes: data_recipes

    b) Built result by getting the wanted recipes, with a guard against missing recipe (which be an empty dict:{} )

def parse_recipe(s):
    recipe, ings_s = s.split(':')
    ings_l = ings_s.split(',')
    
    ings_d= {}
    for ing in ings_l:
        i,q = ing.split('*')
        ings_d[i.strip()] = q.strip()

    return recipe.strip(), ings_d


def extract(recipes, data):
    data_recipes = {}
    for s in data:
        recipe, ings_d = parse_recipe(s)
        data_recipes[recipe] = ings_d

    return {r: data_recipes.get(r, dict()) for r in recipes}
  • Related