Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- BASE_LABELS = {
- 2: "Binary",
- 3: "Ternary",
- 4: "Quaternary",
- 5: "Quinary",
- 6: "Senary",
- 7: "Septenary",
- 8: "Octal",
- 9: "Nonary",
- 10: "Decimal",
- 11: "Undecimal",
- 12: "Duodecimal",
- 13: "Tridecimal",
- 14: "Tetradecimal",
- 15: "Pentadecimal",
- 16: "Hexadecimal",
- }
- DIGIT_VALUES = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- def char_to_value(char: str) -> int:
- return DIGIT_VALUES.index(char.upper())
- def value_to_char(value: int) -> str:
- return DIGIT_VALUES[value]
- def is_valid_number(number: str, base: int) -> bool:
- valid_digits = DIGIT_VALUES[:base]
- return all(char.upper() in valid_digits for char in number)
- def convert(number: str, orig_base: int, new_base: int) -> str:
- if new_base == orig_base: # if base is the same, just return the original number
- return number
- if not is_valid_number(number, orig_base):
- raise ValueError(f"{number} is not valid in {BASE_LABELS[orig_base]}.")
- result = 0
- result_str = ""
- if orig_base != 10: # convert the original number to base 10 before converting
- # `enumerate` gives the index AND value in an iterable (in our case a string)
- # `[::-1]` reverses an iterable using "slice notation"
- for place, digit in enumerate(number[::-1]):
- result += (orig_base**place) * char_to_value(digit)
- else:
- result = int(number)
- if new_base == 10: # if the new base is already 10, the process is done
- return str(result)
- while result > 0:
- result, remainder = divmod(result, new_base)
- result_str = value_to_char(remainder) + result_str
- return result_str or "0"
- if __name__ == "__main__":
- print("=" * 32)
- print(f"{'Base Converter':^32}")
- print("=" * 32)
- orig_base = int(input("Input the original base: "))
- new_base = int(input("Input the new base: "))
- if any(base < 2 or base > 36 for base in (orig_base, new_base)):
- print("Bases must be between 2 and 36!")
- sys.exit(1)
- number = input("Input your number: ")
- try:
- converted = convert(number, orig_base, new_base)
- print(
- f"{number} ({BASE_LABELS.get(orig_base, f'Base {orig_base}')})"
- " = "
- f"{converted} ({BASE_LABELS.get(new_base, f'Base {new_base}')})"
- )
- except ValueError as ve:
- print(ve)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement