Python Forum

Full Version: list comprehension
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi! I try to modify the function below with list comprehation.
But I don't now how to write that else secvantion

This:
def cakes(recipe, available): list_value = [ ] for key,value in recipe.items(): if key in available: a = int(available[key]) // int(value) list_value.append(a) else: return 0 list_value.sort() return list_value[0] 
In this:
def cakes(recipe, available): list_value = [int(available[key]) // int(value) for key,value in recipe.items() if key in available else return 0 ].sort() return list_value[0] 
def cakes(recipe, available): values = [int(available[key]) // int(value) for key, value in recipe.items() if key in available] if len(values) > 0: values.sort() return values[0] return 0
Quote:[int(available[key]) // int(value) for key,value in recipe.items() if key in available else return 0 ].sort()

The sort method of a list, does not return the list. Instead, the list is sorted inline and returns None, which is assigned to list_value.

You can wrap around the whole list comprehension with the sorted function. The sorted function returns a new list, where the original list is not modified.

If you want to get the highest number of a sequence, use the max function.
To get the lowest number, use min.

Example:
from __future__ import annotations def cakes(recipe: dict, available: dict) -> int | None: values = [ int(available[key]) // int(value) for key, value in recipe.items() if key in available ] if values: return min(values)
Annotations: They are not mandatory, but can give you a hint, which types should be used and which types return. For example, an empty recipe will return None. A valid recipe will return an int.
You can avoid checking if values is empty by using the 'default' argument in min()
>>> min([], default=0) 0
So
def cakes(recipe, available): return min( (int(available[key]) // int(value) for key, value in recipe.items() if key in available), default=0)
@Gribouillis, thanks.

The blacked Version is easier to read:
def cakes(recipe, available): return min( ( int(available[key]) // int(value) for key, value in recipe.items() if key in available ), default=0, )
The parenthesis for the Generator Expression is not mandatory.