I have this temperature converter:
def temperature_converter(scale, to_scale, temperature):
scale = scale.capitalize()
to_scale = to_scale.capitalize()
if scale == 'F' and to_scale == 'C':
return (temperature * 1.8) + 32
elif scale == 'C' and to_scale == 'F':
return (5 / 9) * (temperature - 32)
elif scale == 'K' and to_scale == 'F':
return (9 / 5) * (temperature - 273) + 32
elif scale == 'F' and to_scale == 'K':
return (5 / 9) * (temperature - 32) + 273
elif scale == 'C' and to_scale == 'K':
return temperature + 273
elif scale == 'K' and to_scale == 'C':
return temperature - 273
That is not that elegant, but gets the job done.
The task is to refactor it in a more elegant method, using enums and the relations between temperature scales.
I did some googling and i kinda get how to use enums but don't get how to do it in this situation.
This is what i have for now:
class Scales(Enum):
Celsius = 'C'
Fahrenheit = 'F'
Kelvin = 'K'
def temp_conv_2(scale, to_scale_, temp):
scale = scale.capitalize()
to_scale_ = to_scale_.capitalize()
for scale in Scales:
if scale == Scales.Celsius and to_scale_ == Scales.Fahrenheit:
return (5 / 9) * (temp - 32)
What logic should i be using to avoid so many ifs and solve this problem?