Help with python functions?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 23 23:15:23 EDT 2013


On Mon, 23 Sep 2013 15:55:53 -0700, kjakupak wrote:


> As for the next one, so far I've gotten: def comp(T1, u1, T2, u2):
>     if u1 > u2:
>         return -1
>     elif u2 > u1:
>         return 1
>     else:
>         return 0


That is only comparing the units, not the temperatures. Since the units 
are characters, you're essentially saying that any temperature in Kelvin 
is always greater than any temperature in Celsius, since "K" > "C". 
Worse, you're saying that any two temperatures with the same unit are 
automatically equal, so that -50°F == 50000°F.

Instead, you need to convert both temperatures into a common unit, say, 
Kelvin, then compare the two temperatures:

* convert T1 from u1 to Kelvin;
* convert T2 from u2 to Kelvin;
* compare T1 and T2.

You don't have to use Kelvin. You could use any temperature scale, so 
long as it is the same for both temperatures.


-- 
Steven



More information about the Python-list mailing list