1

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?

  • Does this answer your question? [Finding max value in the second column of a nested list?](https://stackoverflow.com/questions/4800419/finding-max-value-in-the-second-column-of-a-nested-list) – Seon Nov 14 '22 at 22:27
  • 1
    Hi @Seon not really since I first have to remove some items out of the tuple and then get the smallest one and that thread does not help me unfortunately. – moon knight Nov 14 '22 at 22:29

1 Answers1

1

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.

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Thank you! I dont get how you change a tuple though... I thought tuples were immutable. Im new to to python so could u maybe explain the p, s part also a bit if that isnt a problem for u? Thanks and also thanks in advance!! – moon knight Nov 14 '22 at 23:38