Convert two loops to a list comprehension

Viewed 118

I am trying to write a list comprehension for lines 3-6 of the function. It returns the relevant restaurant(s) depending on the choice in guests_diet. The result should be the string "Sorry, no restaurants meet your restrictions". The function works but I'm being challenged to do the list comprehension. I came up with the code below but I'm getting an incorrect result. Can anyone help?

Tried code producing incorrect results -

ans = [restaurant.append(key) for key, value in rest_names.items()\
                  for x in range(len(cuisine)) if cuisine[x] in value]

Code -

def no_you_pick(rest_names, cuisine):
    restaurant = []
    for key, value in rest_names.items():
        for x in range(len(cuisine)):
            if cuisine[x] in value:
                restaurant.append(key)
    restaurant.sort()
    if len(restaurant) == 0:
        return "Sorry, no restaurants meet your restrictions"
    elif len(restaurant) == 1:
        return ' '.join(restaurant)
    return ', '.join(restaurant)

grading_scale = {"blossom": ["vegetarian", "vegan", "kosher", "gluten-free", "dairy-free"], \
             "jacob's pickles": ["vegetarian", "gluten-free"], \
             "sweetgreen": ["vegetarian", "vegan", "gluten-free", "kosher"]}
guests_diet = ["buttered-lobster"]
print(no_you_pick(grading_scale, guests_diet))

2 Answers

The following code will work -

def no_you_pick(rest_names, cuisine):
    restaurant = [key for key,value in rest_names.items() for x in range(len(cuisine)) if cuisine[x] in value]
    restaurant.sort()
    if len(restaurant) == 0:
        return "Sorry, no restaurants meet your restrictions"
    elif len(restaurant) == 1:
        return ' '.join(restaurant)
    return ', '.join(restaurant)

grading_scale = {"blossom": ["vegetarian", "vegan", "kosher", "gluten-free", "dairy-free"], \
             "jacob's pickles": ["vegetarian", "gluten-free"], \
             "sweetgreen": ["vegetarian", "vegan", "gluten-free", "kosher"]}
guests_diet = ["buttered-lobster"]
print(no_you_pick(grading_scale, guests_diet))
print(no_you_pick(grading_scale, ['vegan']))

OUTPUT :

Sorry, no restaurants meet your restrictions
blossom, sweetgreen

You don't need to append to the restaurant .

ans = [restaurant.append(key) for key, value in rest_names.items() for x in range(len(cuisine)) if cuisine[x] in value]

Since you are using list comprehension, you can directly build your list - restaurant and only the keys that match the given condition would be added in the list. Here, instead of writing restaurant.append(key), you can easily directly append keys using list comprehension on restaurant as done in the above code

You can replace this with the following list comprehension:

restaurant = [key for key, value in rest_names.items()\
              if any(item in cuisine for item in value)]

And no need to declare restaurant to be an empty list above it.

Related