Skip to content

Instantly share code, notes, and snippets.

@xiaket
Created May 29, 2017 01:38
Show Gist options
  • Save xiaket/78cc4180fe37a4fa1f2c1e2d4e2e9d41 to your computer and use it in GitHub Desktop.
Save xiaket/78cc4180fe37a4fa1f2c1e2d4e2e9d41 to your computer and use it in GitHub Desktop.
generic number class builder
# For this codewar question: https://www.codewars.com/kata/54baad292c471514820000a3
import math
def create_number_class(bases):
base = len(bases)
def __init__(self, value):
self.value = value
def to_int(self):
_sum = 0
for i, ch in enumerate(self.value):
_sum += bases.index(ch) * (self.base ** (len(self.value) - i - 1))
return _sum
@classmethod
def from_int(kls, int_):
if int_ == 0:
return kls.bases[0]
digits = math.floor(math.log(int_)/math.log(kls.base)) + 1
chars = []
value = int_
for i in range(digits):
index = value // (kls.base ** (digits - i - 1))
chars.append(kls.bases[index])
value -= index * (kls.base ** (digits - i - 1))
return kls(''.join(chars))
def convert_to(self, klass):
return klass.from_int(self.to_int())
def __str__(self):
return self.value
def __add__(self, obj):
return self.__class__.from_int(self.to_int() + obj.to_int())
def __sub__(self, obj):
return self.__class__.from_int(self.to_int() - obj.to_int())
def __floordiv__(self, obj):
return self.__class__.from_int(self.to_int() // obj.to_int())
def __mul__(self, obj):
return self.__class__.from_int(self.to_int() * obj.to_int())
klass = type(
'klass', (object, ),
dict(
base=base,
bases=bases,
from_int=from_int,
to_int=to_int,
convert_to=convert_to,
__init__=__init__,
__add__=__add__,
__sub__=__sub__,
__mul__=__mul__,
__floordiv__=__floordiv__,
__str__=__str__,
),
)
return klass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment