Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' >>> decimal_to_any(5, 4) '11' >>> decimal_to_any(20, 3) '202' >>> decimal_to_any(58, 16) '3A' >>> decimal_to_any(243, 17) 'E5' >>> decimal_to_any(34923, 36) 'QY3'
(num: int, base: int)
| 6 | |
| 7 | |
| 8 | def decimal_to_any(num: int, base: int) -> str: |
| 9 | """ |
| 10 | Convert a positive integer to another base as str. |
| 11 | >>> decimal_to_any(0, 2) |
| 12 | '0' |
| 13 | >>> decimal_to_any(5, 4) |
| 14 | '11' |
| 15 | >>> decimal_to_any(20, 3) |
| 16 | '202' |
| 17 | >>> decimal_to_any(58, 16) |
| 18 | '3A' |
| 19 | >>> decimal_to_any(243, 17) |
| 20 | 'E5' |
| 21 | >>> decimal_to_any(34923, 36) |
| 22 | 'QY3' |
| 23 | >>> decimal_to_any(10, 11) |
| 24 | 'A' |
| 25 | >>> decimal_to_any(16, 16) |
| 26 | '10' |
| 27 | >>> decimal_to_any(36, 36) |
| 28 | '10' |
| 29 | >>> # negatives will error |
| 30 | >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS |
| 31 | Traceback (most recent call last): |
| 32 | ... |
| 33 | ValueError: parameter must be positive int |
| 34 | >>> # floats will error |
| 35 | >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS |
| 36 | Traceback (most recent call last): |
| 37 | ... |
| 38 | TypeError: int() can't convert non-string with explicit base |
| 39 | >>> # a float base will error |
| 40 | >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS |
| 41 | Traceback (most recent call last): |
| 42 | ... |
| 43 | TypeError: 'float' object cannot be interpreted as an integer |
| 44 | >>> # a str base will error |
| 45 | >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS |
| 46 | Traceback (most recent call last): |
| 47 | ... |
| 48 | TypeError: 'str' object cannot be interpreted as an integer |
| 49 | >>> # a base less than 2 will error |
| 50 | >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS |
| 51 | Traceback (most recent call last): |
| 52 | ... |
| 53 | ValueError: base must be >= 2 |
| 54 | >>> # a base greater than 36 will error |
| 55 | >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS |
| 56 | Traceback (most recent call last): |
| 57 | ... |
| 58 | ValueError: base must be <= 36 |
| 59 | """ |
| 60 | if isinstance(num, float): |
| 61 | raise TypeError("int() can't convert non-string with explicit base") |
| 62 | if num < 0: |
| 63 | raise ValueError("parameter must be positive int") |
| 64 | if isinstance(base, str): |
| 65 | raise TypeError("'str' object cannot be interpreted as an integer") |