0

Why do we use this to deal with minimum value? Please, explain someone.

lowest_path_cost = float('inf')
maciejwww
  • 1,067
  • 1
  • 13
  • 26

1 Answers1

0

Let's say you have a deck of cards, and you want to find the one with the minimum value. What would you do? You probably remember the lowest card you have see so far while looking at each card. At the end that number is the minimum.

Example

  1. At the beginning you have no minimum number in mind, because you have seen no cards. min = nothing.
  2. You draw a card, it's a 6. Is it lower than the minimum card you have found so far? Yes, since you have seen no cards so far. min = 6.
  3. You draw another card, it's a 10. Well, this card is useless as it is not lower than the minimum card you have found so far. You just forget about it. min = 6
  4. You draw a 3. This card is lower than the 6 you previously found. So you don't care about the 6 anymore, and you're gonna remember only the 3. min = 3
  5. You find a -10000000. This is the lower number you have found so far, so it's time to forget 3 and keep in mind only -10000000. min = -10000000
  6. And so on and so forward, until you check all the cards.

You can code this reasoning in the following way:

deck = [6, 10, 3, -10000000, .....]

min = nothing

for card in deck:
    if card < min:
        min = card

print('The minimum card is', min)

This of course does not work, because 'nothing' does not exist in python. Could you write min = 0? Not really, because when you find the 6 it's not lower than 0, so you would forget about it. The important thing is to use a number which is bigger than the first card of your deck, so that if card < min is true and you correctly remember the first card.

But you do not know a priori (in general) what is the first card of your deck. It could be 1000000000 or -5 or 0 etc. So you must use a number that is bigger than any other number (again, this is necessary to make the first if card < min be always true). What is bigger than any other number? Infinity!!

deck = [6, 10, 3, -10000000, ...]

min = float('inf')

for card in deck:
    if card < min:
        min = card

print('The minimum card is', min)
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50