-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitch_base.py
More file actions
31 lines (28 loc) · 963 Bytes
/
switch_base.py
File metadata and controls
31 lines (28 loc) · 963 Bytes
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
def switch_base(n,base=2):
""" (int) -> str
Precondition: 1 < base < 11
Convert an integer (base 10) into a base integer (base two is default).
Not currently implemented for any base that requires letters, but returns
a string, anticipating one day to do bases requiring letters.
>>> switch_base(16)
'10000'
>>> switch_base(17)
'10001'
"""
assert 1 < base < 11, ('currently not implemented for bases less than 2 or'
'greater than 10, you used base {}'.format(base))
if (n == 0):
return '0'
newnum = []
while n:
rem = n % base
n = n // base
# string or number? logic easier as string, and if base includes
# letters, would need to anyway, but of course then we would have
# to lookup the letters...
newnum.append(str(rem))
newnum.reverse()
return ''.join(newnum)
if __name__ == '__main__':
import doctest
doctest.testmod()