So I was toying around with this code:
def cheapest_shark(prices: List, sharks: List ) -> Tuple:
shp = zip(sharks, prices)
sharkprices = tuple(shp)
print(sharkprices)
My input is
cheapest_shark([230, 180, 52, 390, 520], [1, 0, 0, 1, 1])
(Each number is connected to each other in the output: (230, 1) (180, 0) etc, etc.)
I am trying to make the function in such a way that it always returns me the smallest item in the tuple (but it needs to have a 1 in it). So in this case the output needs to be (230,1). I tried converting it to a dict and then making a for loop which checks if there is a 1 as a value and then takes the lowest sum of the remaining items but that did not work out for me. Does anyone have any suggestions on how I could make this function work?
CodePudding user response:
Try to filter the tuples (keep only values where the shark is 1) and use min()
:
def cheapest_shark(prices, sharks):
shp = ((p, s) for p, s in zip(prices, sharks) if s == 1)
return min(shp, default=None)
x = cheapest_shark([230, 180, 52, 390, 520], [1, 0, 0, 1, 1])
print(x)
Prints:
(230, 1)
Note: If there isn't any tuple with value 1 the default=
value is returned (in this case None
). Without default=
parameter the exception is thrown.