|
1 | 1 | from test_framework import generic_test |
2 | 2 |
|
| 3 | +""" |
| 4 | +- Bases can be between 2 and 16 |
| 5 | +- Can be empty? |
| 6 | +- Can exceed integer limits (not issue for python) |
| 7 | +- Negatives |
| 8 | +- num_as_string[0] is most sig fig |
| 9 | +- 0 and 1 are always valid; A = 10, ..., F = 15 |
| 10 | +
|
| 11 | +Input: string representing num in b1 |
| 12 | +Output: string representing num in b2 |
| 13 | +
|
| 14 | +- Ex: convert "12345" to int 12345 |
| 15 | + - add each digit, then multiply total by 10. |
| 16 | +""" |
| 17 | + |
| 18 | +# easier to read than ord()/chr() |
| 19 | +CHAR_AS_NUM = {str(i): i for i in range(10)} | {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15} |
| 20 | +NUM_AS_CHAR = "0123456789ABCDEF" |
| 21 | + |
| 22 | + |
| 23 | +def to_new_base(num: int, b2: int) -> str: |
| 24 | + if num == 0: |
| 25 | + return "0" |
| 26 | + val = "" |
| 27 | + while num: |
| 28 | + remainder = num % b2 |
| 29 | + val = NUM_AS_CHAR[remainder] + val # prepend the new digit |
| 30 | + num //= b2 |
| 31 | + return val |
| 32 | + |
| 33 | + |
| 34 | +def to_base_ten(num_as_string: str, b1: int) -> int: |
| 35 | + total = 0 |
| 36 | + place = 1 |
| 37 | + for c in num_as_string[::-1]: |
| 38 | + total += (CHAR_AS_NUM[c] * place) |
| 39 | + place *= b1 |
| 40 | + return total |
| 41 | + |
3 | 42 |
|
4 | 43 | def convert_base(num_as_string: str, b1: int, b2: int) -> str: |
5 | | - # TODO - you fill in here. |
6 | | - return '' |
| 44 | + if not num_as_string: |
| 45 | + return "" |
| 46 | + neg = num_as_string[0] == '-' |
| 47 | + num_as_string = num_as_string[1:] if neg else num_as_string |
7 | 48 |
|
| 49 | + num_base_10 = to_base_ten(num_as_string, b1) |
| 50 | + num_b2 = to_new_base(num_base_10, b2) |
8 | 51 |
|
9 | | -if __name__ == '__main__': |
| 52 | + return ("-" if neg else "") + num_b2 |
10 | 53 |
|
11 | | - assert convert_base("1234", 10, 2) == bin(1234) |
12 | 54 |
|
13 | | - """ |
| 55 | +if __name__ == '__main__': |
14 | 56 | exit( |
15 | 57 | generic_test.generic_test_main('convert_base.py', 'convert_base.tsv', |
16 | 58 | convert_base)) |
17 | | - """ |
|
0 commit comments