Skip to content

Instantly share code, notes, and snippets.

@maduck
Last active March 22, 2018 09:47
Show Gist options
  • Save maduck/094cb36a4d862b4348aa6bb759bbd5d2 to your computer and use it in GitHub Desktop.
Save maduck/094cb36a4d862b4348aa6bb759bbd5d2 to your computer and use it in GitHub Desktop.
Unit formatting python OOP kata.
#!/usr/bin/env python3
import math
class BaseFormatter(object):
"""
Provides a generic formatting class.
Just inherit from it, define your units,
and then use pretty_format with any number.
"""
@staticmethod
def one_number_format(number, unit):
unit_abbreviation = unit[0]
return u"{:,}{}".format(number, unit_abbreviation)
def __init__(self):
if not hasattr(self, "units"):
raise NotImplementedError("Please implement some units to handle")
def pretty_format(self, number):
current_number = number
result = []
for unit in self.units:
limit = unit[1]
if current_number > limit:
reduced_number = current_number % limit
result.append(self.one_number_format(reduced_number, unit))
current_number = current_number // limit
else:
result.append(self.one_number_format(current_number, unit))
break
result.reverse()
return " ".join(result)
class TimeFormatter(BaseFormatter):
units = (
('ms', 1000),# Millisecond
('s', 60), # Second
('m', 60), # Minute
('h', 24), # Hour
('d', 365), # Day
('y', math.inf), # Year
)
class DistanceFormatter(BaseFormatter):
units = (
('mm', 10),
('cm', 100),
('m', 1000),
('km', 30856775800000),
('pc', math.inf),
)
if __name__ == "__main__":
FORMATTER1 = TimeFormatter()
print("time:", FORMATTER1.pretty_format(1623956))
FORMATTER2 = DistanceFormatter()
print("distance:", FORMATTER2.pretty_format(67652345343528349039278))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment