Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from string import digits, ascii_uppercase, ascii_lowercase
- # every character except the dash (-) is allowed as a digit
- DIGITS = tuple(digits + ascii_uppercase + ascii_lowercase)
- DIGITS_TO_DECIMAL = dict((c, i) for i, c in enumerate(DIGITS))
- BASE = len(DIGITS)
- def base_decode(string, base=BASE, digits_to_decimal=DIGITS_TO_DECIMAL):
- """
- Decodes a number with a custom base (in form of a string) to a decimal.
- By default the digits are 0-9, A-Z, a-z and thus the base is 62.
- You need to supply the base and a dictionary that maps every digit to a
- decimal.
- >>> base_decode('0')
- 0
- >>> base_decode('z')
- 61
- >>> base_decode('10')
- 62
- >>> base_decode('-y')
- -60
- """
- factor = 1
- if string.startswith("-"):
- string = string[1:]
- factor = -1
- number = 0
- for c in string:
- number = number * base + digits_to_decimal[c]
- return factor * number
- def base_encode(number, base=BASE, digits=DIGITS):
- """
- Encodes a decimal to a number with a custom base in form of a string.
- By default the digits are 0-9, A-Z, a-z and thus the base is 62.
- You need to supply the base and the digits.
- >>> base_encode(0)
- '0'
- >>> base_encode(61)
- 'z'
- >>> base_encode(62)
- '10'
- >>> base_encode(-60)
- '-y'
- """
- if not number:
- return digits[0]
- prefix = ""
- if number < 0:
- prefix = "-"
- number = abs(number)
- string = ""
- while number:
- number, rem = divmod(number, base)
- string = digits[rem] + string
- return prefix + string
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement