Can you write the 'cheapest function' in a better way?

Can you write the cheapest function at the end in a better way and explain what you did?

def ground(weight):
  if weight <=2:
  elif weight > 2 and weight <=6:
    cost =3
  elif weight >6 and weight <=10:
  return 20 + (cost * weight)

def drone(weight):
  if weight <=2:
    cost = 4.5
  elif weight >2 and weight <=6:
    cost = 9
  elif weight > 6 and weight <= 10:
    cost = 12
    cost =14.25
  return cost*weight


def cheapest(weight):
  drone1= drone(weight)
  ground1= ground(weight)
  premium1 = PG_shipping
  if drone1 < ground1 and drone1 < premium1:
    print ('The cheapest way is to ship by drone and the cost will be ' +str(cost) )
  elif ground1 < drone1 and ground1 < premium1:
    cost= ground1
    print ("The cheapest way to ship is by ground and the cost will be " +str(cost) )
    cost = premium1
    print ('The cheapest way to ship is by premium shipping and the cost will be ' +str(cost))

cheapest (50)
  1. Why can’t I equal function to another function? I have had to put
drone1= drone(weight)
  ground1= ground(weight)
  premium1 = PG_shipping

Why could I not put:

if drone(weight) < ground(weight) and drone(weight)
 < PG_shipping:
    print ('The cheapest way is to ship by drone and the cost will be ' +str(cost) )

I know this would make the code longer but I want to know the reason as the functions come before this function.

finding the smallest of something is what min does

No idea what you mean by can’t. What did you expect to happen and what happened instead? Got a runnable version instead so that it’s possible to see it?
Keep in mind that = doesn’t mean equal, it is assignment, and it doesn’t have anything to do with functions, it sets a variable to a value.


How do you define “a better way”? This exercise comes very early in the Python 3 course. Later, after learning some more data structures, you’ll be able to do it more compactly, but here you have

  1. defined functions and made use of them within other functions, and
  2. put together a sensible if-elif-else chain

For now, that’s doing very well, indeed! Make a note to yourself to return to this exercise when you have completed the course, and you can have some fun re-doing it!

Now I think that what you are trying to do here is get rid of the intermediate variables drone1, etc., Well, yes, you definitely can do so.

One thing to remember, though: Every time that the interpreter sees drone(weight), it evaluates the function drone(); if you do have an intermediate variable drone1 = drone(weight), the function drone() is evaluated just one time. However, if you eliminate the variable drone1, then in the worst case, the function will need to be evaluated three times to get all the way to else.

The functions in this case are so simple that there is in actuality very little excess overhead, but I think you can get the idea: sometimes intermediate variables just get in the way, but they can also be quite useful.