Skip to content

Commit d66a93c

Browse files
committed
8/17/23 - slow day
I think I'm going to switch to focusing on just Python again; feeling like there's too much room for embarassing error when jumping between them. - convert_base.py
1 parent a777150 commit d66a93c

File tree

2 files changed

+48
-7
lines changed

2 files changed

+48
-7
lines changed

elements-of-programming-interviews/problem_mapping.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ problem_mapping = {
504504
"total": 20001
505505
},
506506
"Python: convert_base.py": {
507-
"passed": 0,
507+
"passed": 20001,
508508
"total": 20001
509509
}
510510
},

elements-of-programming-interviews/python/convert_base.py

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,58 @@
11
from test_framework import generic_test
22

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+
342

443
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
748

49+
num_base_10 = to_base_ten(num_as_string, b1)
50+
num_b2 = to_new_base(num_base_10, b2)
851

9-
if __name__ == '__main__':
52+
return ("-" if neg else "") + num_b2
1053

11-
assert convert_base("1234", 10, 2) == bin(1234)
1254

13-
"""
55+
if __name__ == '__main__':
1456
exit(
1557
generic_test.generic_test_main('convert_base.py', 'convert_base.tsv',
1658
convert_base))
17-
"""

0 commit comments

Comments
 (0)