Ok I am making unit converter and I have attached temperature conversion code below. The problem with this code I think is that I have written function for each and every single unit to convert to another unit.
So in code below there is one function to covert Celsius into Fahrenheit, Kelvin, Renkien and Newton. Then another function to convert Fahrenheit to Celsius,Kelvin, Renkien and Newton.
Now I do understand that every unit is related to one another. But I just can't think of a way if this conversion can be done using single function such that first you choose your source and then destination and using that without using five different function I can just finish in one.
Another way I thought of this was I can may be use dictionaries rather then using so many if else conditions but I would like know which one is more optimized in terms of both time and space complexity.
class TempConv:
def __init__(self,source,dest,val):
self.frm=source
self.to=dest
self.x=val
self.ans=0
def setFrm(self,arg):
self.frm=arg
def setTo(self,arg):
self.to=arg
def setX(self,arg):
self.x=arg
def calculate(self):
if self.x is "celc":
self.ans=self.celcToAny()
elif self.x is "farh":
self.ans=self.farhToAny()
elif self.x is "kel":
self.ans=self.kelToAny()
elif self.x is "renk":
self.ans=self.renkToAny()
elif self.x is "newt":
self.ans=self.newtToAny()
else:
self.ans=self.x
#Celcius to Any
def celcToAny(self):
if self.to is "farh":
return (float(self.x)*1.8)+32
elif self.to is "kel":
return float(self.x)+273.15
elif self.to is "renk":
return (flaot(self.x)+273.15)*1.8
elif self.to is "newt":
return float(self.x)*0.33
else:
return self.x
#Fahrenheit to Any
def fahrToAny(self):
if self.to is "celc":
return (float(self.x)-32)*0.555555556
elif self.to is "kel":
return (float(self.x)+459.67)*0.555555556
elif self.to is "renk":
return float(self.x)+459.67
elif self.to is "newt":
return (float(self.x)-32)*0.183333333
else:
return self.x
#Kelvin to Any
def kelToAny(self):
if self.to is "farh":
return (float(self.x)*1.8)-459.67;
elif self.to is "celc":
return float(self.x)-273.15
elif self.to is "renk":
return float(self.x)*1.8
elif self.to is "newt":
return (float(self.x)-273.15)*0.33
else:
return self.x
#Rankine to Any
def renkToAny(self):
if self.to is "farh":
return float(self.x)-459.67;
elif self.to is "celc":
return (float(self.x)-491.67)*0.555555556
elif self.to is "kel":
return float(self.x)*0.555555556
elif self.to is "newt":
return (float(self.x)-491.67)0.183333333
else:
return self.x
#Newton to Any
def newtToAny(self):
if self.to is "farh":
return (float(self.x)*5.454545455)+32
elif self.to is "kel":
return (float(self.x)*3.030303030)+273.15
elif self.to is "renk":
return (flaot(self.x)*5.454545455)+491.67
elif self.to is "celc":
return float(self.x)*3.030303030
else:
return self.x