Skip to content

Instantly share code, notes, and snippets.

@dakyskye
Last active September 27, 2023 14:20
Show Gist options
  • Save dakyskye/f176336b066c2378622053940808e523 to your computer and use it in GitHub Desktop.
Save dakyskye/f176336b066c2378622053940808e523 to your computer and use it in GitHub Desktop.
from operator import mod
import sys
# engineered at 2:57am - October 8th, Saturday
def represent_as(origin, *, base=0, new_base=0):
# let's first represent the actual number in its base
number = origin
digits = []
while number > 0:
number, digit = divmod(number, 10)
digits.append(digit)
digits = digits[::-1]
number = 0
for index, digit in enumerate(digits):
number += digit * (base ** (len(digits) - index - 1))
# now let's change the base into the new_base
rest = number
digits = []
while True:
rest, digit = divmod(rest, new_base)
digits.append(digit)
if rest == 0:
break
# let's prettify the return result as well
digits = [str(digit) for digit in digits[::-1]]
if new_base > 10:
return " ".join(digits) # an actual digit may consist of multiple digits.. hence the separation
else:
return "".join(digits)
def main():
while True:
try:
origin = input("input a number: ")
base = int(input("input the number's base: "))
into = int(input("input the new desired base for the number: "))
if base < 2 or into < 2:
raise ValueError
if base <= 36:
origin = int(origin, base)
else:
origin = int(origin)
except ValueError:
print("please input valid integers as the original and new desired bases")
print("also make sure to input proper integers (and letters) for the number")
continue
print(represent_as(origin, base=10 if base <= 36 else base, new_base=into))
return
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment