Create A Base 12 Calculator With Different Limits At Diferent Digits With Python
I want o create a calculator that can add (and multiply, divide, etc) numbers in base 12 and with different limits at the different digits. Base 12 sequence: [0,1,2,3,4,5,6,7,8,9,'
Solution 1:
You can define two converters:
classBase12Convert:
d = {hex(te)[2:].upper():te for te inrange(0,12)}
d.update({val:key for key,val in d.items()})
d["-"] = "-" @staticmethoddeftext_to_int(text):
"""Converts a base-12 text into an int."""ifnotisinstance(text,str):
raise ValueError(
f"Only strings allowed: '{text}' of type '{type(text)}' is invalid")
t = text.strip().upper()
ifany (x notin Base12Convert.d for x in t):
raise ValueError(
f"Only [-0123456789abAB] allowed in string: '{t}' is invalid")
if"-"in t.lstrip("-"):
raise ValueError(f"Sign '-' only allowed in front. '{t}' is invalid")
# easy wayreturnint(t,12)
# self-calculated way# return sum(Base12Convert.d[num]*12**idx for idx,num in enumerate(t[::-1])) @staticmethoddefint_to_text(num):
"""Converts an int into a base-12 string."""
sign = ""ifnotisinstance(num,int):
raise ValueError(
f"Only integer as input allowed: '{num} of type {type(num)}' is invalid")
if num < 0:
sign = "-"
num *= -1# get highest possible number
p = 1while p < num:
p *= 12# create string
rv = [sign]
whileTrue:
p /= 12
div = num // p
num -= div*p
rv.append(Base12Convert.d[div])
if p == 1:
breakreturn''.join(rv)
Then you can use them to convert what you want:
text = "14:54:31" # sometime
# converteachintof the timeinto base12 -joinwith| again
base12 ='|'.join(Base12Convert.int_to_text (int(t)) for t in text.split(":"))
# split base12 at|, converttoint, make str fromintandjoinwith| again
base10 ='|'.join(map(str,(Base12Convert.text_to_int (b12) for b12 in base12.split("|"))))
# print all3
print(text,base12,base10,sep="\n")
Output:
14:54:31
12|46|27
14|54|31
and enforce whatever restrictions you have on your "digits" using normal ints. You should split up your "digits" of a clock ... 14b
(203 in base 10) does not make sense, 1:4b
might if you mean 1:59 hours/minutes.
Post a Comment for "Create A Base 12 Calculator With Different Limits At Diferent Digits With Python"