Skip to content

Instantly share code, notes, and snippets.

@SeijiEmery
Last active August 29, 2015 14:07
Show Gist options
  • Save SeijiEmery/c781b140b60d38a4be7f to your computer and use it in GitHub Desktop.
Save SeijiEmery/c781b140b60d38a4be7f to your computer and use it in GitHub Desktop.
Unit Converter (python)
class UnitConverter (object):
def __init__ (self):
self.conv = {}
def connect (self, a, b, k):
self.conv[a][b] = k
self.conv[b][a] = 1.0 / k
for c in self.conv[a].keys():
if c != b and c not in self.conv[b].keys():
self.connect(c, b, self.conv[c][a] * self.conv[a][b])
for d in self.conv[b].keys():
if d != a and d not in self.conv[a].keys():
self.connect(d, a, self.conv[d][b] * self.conv[b][a])
def addConversion (self, a, b, k):
if a not in self.conv:
self.conv[a] = {}
if b not in self.conv:
self.conv[b] = {}
self.connect(a, b, k)
def convert (self, from_, to):
return self.conv[from_][to]
def printConversion (self, from_, to, value):
try:
return "%s %s = %s %s"%(value, from_, self.conv[from_][to] * value, to)
except KeyError:
return "Cannot convert %s to %s"%(from_, to)
if __name__ == '__main__':
uc = UnitConverter()
uc.addConversion('m', 'cm', 100.0)
uc.addConversion('cm', 'mm', 10.0)
uc.addConversion('km', 'm', 1000.0)
uc.addConversion('ft', 'in', 12.0)
uc.addConversion('mi', 'ft', 5280.0)
uc.addConversion('in', 'cm', 2.54)
print("Conversions:")
print('\n'.join(['\t%s: %s'%(k, v) for k, v in uc.conv.iteritems()]))
print(uc.printConversion('cm', 'm', 50))
print(uc.printConversion('m', 'mm', 45))
print(uc.printConversion('mm', 'm', 35))
print(uc.printConversion('m', 'ft', 1))
print(uc.printConversion('km', 'mi', 10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment