Calculate the sum of digit values in a positive integer converted to the given 'base'. Where 'base' ranges from 2 to 36. Examples: >>> sum_of_digits(103, 12) '13' >>> sum_of_digits(1275, 4) '30' >>> sum_of_digits(6645, 2) '1001' >>> # bases below 2 and b
(num: int, base: int)
| 54 | |
| 55 | |
| 56 | def sum_of_digits(num: int, base: int) -> str: |
| 57 | """ |
| 58 | Calculate the sum of digit values in a positive integer |
| 59 | converted to the given 'base'. |
| 60 | Where 'base' ranges from 2 to 36. |
| 61 | |
| 62 | Examples: |
| 63 | >>> sum_of_digits(103, 12) |
| 64 | '13' |
| 65 | >>> sum_of_digits(1275, 4) |
| 66 | '30' |
| 67 | >>> sum_of_digits(6645, 2) |
| 68 | '1001' |
| 69 | >>> # bases below 2 and beyond 36 will error |
| 70 | >>> sum_of_digits(543, 1) |
| 71 | Traceback (most recent call last): |
| 72 | ... |
| 73 | ValueError: 'base' must be between 2 and 36 inclusive |
| 74 | >>> sum_of_digits(543, 37) |
| 75 | Traceback (most recent call last): |
| 76 | ... |
| 77 | ValueError: 'base' must be between 2 and 36 inclusive |
| 78 | """ |
| 79 | |
| 80 | if base < 2 or base > 36: |
| 81 | raise ValueError("'base' must be between 2 and 36 inclusive") |
| 82 | |
| 83 | num_str = int_to_base(num, base) |
| 84 | res = sum(int(char, base) for char in num_str) |
| 85 | res_str = int_to_base(res, base) |
| 86 | return res_str |
| 87 | |
| 88 | |
| 89 | def harshad_numbers_in_base(limit: int, base: int) -> list[str]: |
no test coverage detected