Home > front end >  Inputting a function into another function
Inputting a function into another function

Time:03-08

For a homework assignment, I created this function that will only give an output if you input in the following strings: "burger", "fries", "panini", and "salad".

def createOrder(food):

    if food == 'burger':
        print(['buns', 'patty', 'lettuce', 'pickles', 'tomato', 'cheese'])

    elif food == "fries":
            print(['potato', 'salt'])

    elif food == 'panini':
        print(['bread', 'ham', 'cheese'])

    elif food == 'salad':
        print(['greens mix', 'ranch', 'tomato'])

    else:
        food != 'burger', 'fries', 'panini', 'salad'
        print("Invalid order")

Now I need to code another function that uses the createOrder() function to get the list of ingredients necessary for all the orders and return the number of each ingredient necessary to fulfill all the orders. eg. >>>gatherIngredients([‘burger’, ‘burger’, ‘panini’])

‘You need 2 buns, 2 patty, 2 lettuce, 2 pickles, 2 tomato, 3 cheese, 1 bread, 1 ham’

Here's my code so far on that:

def gatherIngredients(orders):
if len(items) == 0:
    print('No orders to complete at this time')
items = []
counts = []
for order in orders:
    order_items = createOrder(order)
    for item in order_items:
        index = -1
        for i in range(len(items)):
            if item == items[i]:
                index = i
        if index == -1:
            items.append(item)
            counts.append(1)
        else:
            counts[index]  = 1
result = 'You need'
for i in range(len(items)):
    result  = str(counts[i])
    result  = " "
    result  = items[i]
    if i < len(items) - 1:
        result  = ", "
return result

Can someone help me on this and fix my code? Only for the second function, however.

CodePudding user response:

I know you didn't ask for this, but I feel like giving best practice advice. I'd make an ingredients dict

ingredients = {
    "burger": ['buns', 'patty', 'lettuce', 'pickles', 'tomato', 'cheese'],
    "fries": ['potato', 'salt']
    #etc
}

Then the first function returns:

def createOrder(food):
    return ingredients.get(food, "Invalid Order")

And on the other function, append all the results of 'createOrder' calls to a Counter. To build the final string iterate through the Counter.

CodePudding user response:

Your first function does need a bit of a redo - specifically, there's currently no way to determine what ingredients you need just by running that function. What if you made it return the value instead, and renamed it to get_ingredients(food)?

# I also removed some extraneous whitespace for purposes of compactness,
# as this is tangential to the main question
def get_ingredients(food):
    if food == 'burger':
        return ['buns', 'patty', 'lettuce', 'pickles', 'tomato', 'cheese']
    elif food == "fries":
            return ['potato', 'salt']
    elif food == 'panini':
        return ['bread', 'ham', 'cheese']
    elif food == 'salad':
        return ['greens mix', 'ranch', 'tomato']
    else:
        print(f'Invalid food: {food}')#this is a f-string, I'll link some documentation
        return []

Now, algorithmically, you can do something like the following pseudocode:

ingredients=[]
for food in order:
    ingredients.append(get_ingredients(food))
for food in unique_ingredients:
    print(number of times food is needed)

This is the perfect use case for a list comprehension. So implementing this:

#These structures are list comprehensions
def gather_ingredients(items):
    ingredients=sum([get_ingredients(food) for food in items],[])#This gets the ingredients as a list of lists, and flattens it. I'll link the method below.
    return f'You need {", ".join(str(ingredients.count(i)) " " i for i in list(set(ingredients)))}'

The list(set(ingredients)) gets a list containing the unique ingredients, and then we iterate over that to make it into a string, which we then return.

References

  1. Format-strings

  2. List comprehensions

  3. Flattening a list of lists into a list

CodePudding user response:

This should work (I do modify the first function because it does not work as is):

def createOrder(food):
        result = []
        for i in food:
            if i == 'burger':
                result.append(['buns', 'patty', 'lettuce', 'pickles', 'tomato', 'cheese'])

            elif i == "fries":
                result.append(['potato', 'salt'])

            elif i == 'panini':
                result.append(['bread', 'ham', 'cheese'])

            elif i == 'salad':
                result.append(['greens mix', 'ranch', 'tomato'])

            else:
                i != 'burger', 'fries', 'panini', 'salad'
                result.append('Invalid Order')
        return result
        
def gatherIngredients(orders):
    items = {}
    order_items = createOrder(orders)
    for sublist in order_items:
        if sublist == 'Invalid Order':
            pass
        else:
            for item in sublist:
                if item in items.keys():
                    items[item]  = 1
                else:
                    items[item] = 1
    result = 'You need'
    for key in items:
        result  = ' '
        result  = str(items[key])
        result  = ' '
        result  = key
        result  = ','
        
        
    return result[:-1]

Output:

'You need 2 buns, 2 patty, 2 lettuce, 2 pickles, 2 tomato, 3 cheese, 1 bread, 1 ham'

If an order is invalid, nothing will be added to the result.

CodePudding user response:

You have ingredients mapped to the order item they are required for. This looks like a great place for a dictionary.

ingredients = {
  'burger': ['buns', 'patty', 'lettuce', 'pickles', 'tomato', 'cheese'],
  'fries':  ['potato', 'salt'],
  'panini': ['bread', 'ham', 'cheese'],
  'salad':  ['greens mix', 'ranch', 'tomato']
}

Now, if you have a list of food orders:

food = ['burger', 'apple', 'fries']

You can use a list comprehension and the get method on the dictionary to get a list of required ingredients for each order item, or give you 'Invalid order!' if it doesn't find it.

[ingredients.get(f, 'Invalid order!') for f in food]

Which yields:

[['buns', 'patty', 'lettuce', 'pickles', 'tomato', 'cheese'], 
 'Invalid order!', 
 ['potato', 'salt']]
  • Related