-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrep_in_base.py
More file actions
41 lines (34 loc) · 1.07 KB
/
Copy pathrep_in_base.py
File metadata and controls
41 lines (34 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'''
represent numbers in given base
'''
import string
def rep_in_base(num: int, base: int = 10) -> str:
'''
represent `num` in base of `base`
'''
if base not in range(2, 37):
raise ValueError(
f'base: {base}',
'base has to be between 2 and 36 inclusive')
if num == 0:
return '0'
def inner(ent: int, base: int) -> tuple[int, str]:
'''
returns `denominator`, `reminder`
'''
_match = {
**{i: i for i in range(10)},
**
{index + 10: char for index, char
in enumerate(string.ascii_lowercase)}, }
return ent // base, _match[rem] if(
rem := ent % base) in _match.keys() else str(rem)
denominator, reminder = inner(num, base)
digits = [reminder]
while denominator:
denominator, reminder = inner(denominator, base)
digits.insert(0, reminder)
return ''.join(map(str, digits))
print(rep_in_base(23, 16))
print(rep_in_base(232, 36))
print(rep_in_base(10, 2))