Convert a given positive decimal integer to base 'base'. Where 'base' ranges from 2 to 36. Examples: >>> int_to_base(0, 21) '0' >>> int_to_base(23, 2) '10111' >>> int_to_base(58, 5) '213' >>> int_to_base(167, 16) 'A7' >>> # bases below 2 and beyond 3
(number: int, base: int)
| 6 | |
| 7 | |
| 8 | def int_to_base(number: int, base: int) -> str: |
| 9 | """ |
| 10 | Convert a given positive decimal integer to base 'base'. |
| 11 | Where 'base' ranges from 2 to 36. |
| 12 | |
| 13 | Examples: |
| 14 | >>> int_to_base(0, 21) |
| 15 | '0' |
| 16 | >>> int_to_base(23, 2) |
| 17 | '10111' |
| 18 | >>> int_to_base(58, 5) |
| 19 | '213' |
| 20 | >>> int_to_base(167, 16) |
| 21 | 'A7' |
| 22 | >>> # bases below 2 and beyond 36 will error |
| 23 | >>> int_to_base(98, 1) |
| 24 | Traceback (most recent call last): |
| 25 | ... |
| 26 | ValueError: 'base' must be between 2 and 36 inclusive |
| 27 | >>> int_to_base(98, 37) |
| 28 | Traceback (most recent call last): |
| 29 | ... |
| 30 | ValueError: 'base' must be between 2 and 36 inclusive |
| 31 | >>> int_to_base(-99, 16) |
| 32 | Traceback (most recent call last): |
| 33 | ... |
| 34 | ValueError: number must be a positive integer |
| 35 | """ |
| 36 | |
| 37 | if base < 2 or base > 36: |
| 38 | raise ValueError("'base' must be between 2 and 36 inclusive") |
| 39 | |
| 40 | digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 41 | result = "" |
| 42 | |
| 43 | if number < 0: |
| 44 | raise ValueError("number must be a positive integer") |
| 45 | |
| 46 | while number > 0: |
| 47 | number, remainder = divmod(number, base) |
| 48 | result = digits[remainder] + result |
| 49 | |
| 50 | if result == "": |
| 51 | result = "0" |
| 52 | |
| 53 | return result |
| 54 | |
| 55 | |
| 56 | def sum_of_digits(num: int, base: int) -> str: |
no outgoing calls
no test coverage detected