mardi 31 août 2021

How to check multiple parameters without a mess of 'if' statements?

I'm writing a program for myself that makes a meal plan. I want to make the meal plan customizable, so I have this method:

def getRestrictedMeals(meals):
    restrictions = []
    mealsR = []

In the method, I ask the user questions that customize the code and I save their answer in a list (The getRestHelp method just saves some answers as boolean.):

    print("Would you like only foods you aren't allergic to?")
    print("1. Yes")
    print("2. No")
    user = int(input("Please choose an option: "))
    print()
    restrictions.append(getRestHelp(user))

    print("Would you like only healthy foods?")
    print("1. Yes")
    print("2. No")
    user = int(input("Please choose an option: "))
    print()
    restrictions.append(getRestHelp(user))

    print("Would you like only Gluten Free foods?")
    print("1. Yes")
    print("2. No")
    user = int(input("Please choose an option: "))
    print()
    restrictions.append(getRestHelp(user))

    print("Would you like only Vegitarian foods?")
    print("1. Yes")
    print("2. No")
    user = int(input("Please choose an option: "))
    print()
    restrictions.append(getRestHelp(user))

    print("What is the longest cook time you want?")
    print("Please enter 1000 for any cook time.")
    user = int(input())
    restrictions.append(user)

Next I grab the information from each meal:

facts = []
for x in meals:
    facts.append(x.getAllergy())
    facts.append(x.getHealthy())
    facts.append(x.getGluten())
    facts.append(x.getVegitarian())
    facts.append(x.getCookTime())

This is where I'm stuck. I know I need to compare the lists the add the meal to mealR if it meets the restrictions, but I'm not sure how to do that without getting into a mess of 'if' statements. I can't make sure the lists match each other because if the user answers 'No' to a question, then any meal can be added.

If the user input is Allergies = No and Healthy = Yes, I want to avoid something like this (because I would have to go deeper and deeper for each parameter):

if(restrictions[0] == 0):
    if(restrictions[1] == 0):
        # I would continue going here for other parameters.
    else:
        if(x.getHealthy()):
            # I would continue going here for other parameters.
            mealsR[i] = x
            i+=1

    else:
       if(!x.getAllergy()):
           # I would continue going here for other parameters.

Aucun commentaire:

Enregistrer un commentaire