Skip to content

Commit ec9a062

Browse files
Refactor base62 functions and add tests
Refactor base62 encoding and decoding functions to use a local charset variable instead of a global CHARSET. Added a test function for base62 encoding and decoding.
1 parent c5c9572 commit ec9a062

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed

ciphers/base62.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,52 @@
1-
import doctest
21
import string
32

4-
CHARSET = string.digits + string.ascii_lowercase + string.ascii_uppercase
5-
63

74
def base62_encode(num: int) -> str:
85
"""
96
Encodes a positive integer into a base62 string.
10-
>>> base62_encode(0)
11-
'0'
12-
>>> base62_encode(123)
13-
'1z'
14-
>>> base62_encode(1000000)
15-
'4C92'
167
"""
178
if num == 0:
18-
return CHARSET[0]
9+
return "0"
1910

2011
arr = []
21-
base = len(CHARSET)
12+
base = 62
13+
charset = string.digits + string.ascii_lowercase + string.ascii_uppercase
2214
while num:
2315
num, rem = divmod(num, base)
24-
arr.append(CHARSET[rem])
16+
arr.append(charset[rem])
2517
arr.reverse()
2618
return "".join(arr)
2719

2820

2921
def base62_decode(string_val: str) -> int:
3022
"""
3123
Decodes a base62 string into a positive integer.
32-
>>> base62_decode('0')
33-
0
34-
>>> base62_decode('1z')
35-
123
36-
>>> base62_decode('4C92')
37-
1000000
3824
"""
39-
base = len(CHARSET)
25+
base = 62
26+
charset = string.digits + string.ascii_lowercase + string.ascii_uppercase
4027
strlen = len(string_val)
4128
num = 0
4229

4330
for idx, char in enumerate(string_val):
4431
power = strlen - (idx + 1)
45-
num += CHARSET.index(char) * (base**power)
32+
num += charset.index(char) * (base**power)
4633
return num
4734

4835

36+
def test_base62() -> None:
37+
"""
38+
Tests for base62_encode and base62_decode.
39+
"""
40+
assert base62_encode(0) == "0"
41+
assert base62_encode(123) == "1z"
42+
assert base62_encode(1000000) == "4C92"
43+
assert base62_decode("0") == 0
44+
assert base62_decode("1z") == 123
45+
assert base62_decode("4C92") == 1000000
46+
47+
4948
if __name__ == "__main__":
49+
import doctest
50+
5051
doctest.testmod()
52+
test_base62()

0 commit comments

Comments
 (0)