Skip to content

Commit 1584436

Browse files
authored
Raised Value Error for negative inputs
1 parent 21a703d commit 1584436

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

maths/harshad_numbers.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ def int_to_base(number: int, base: int) -> str:
88
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
99
result = ""
1010

11+
if number < 0:
12+
raise ValueError("number must be a positive integer")
13+
1114
while number > 0:
1215
number, remainder = divmod(number, base_of_interest)
1316
result = digits[remainder] + result
@@ -21,8 +24,8 @@ def int_to_base(number: int, base: int) -> str:
2124
def sum_of_digits(num: int, base: int) -> str:
2225
"""
2326
Calculate the sum of digit values in a positive integer
24-
converted to the given 'base_of_interest'.
25-
Where 'base_of_interest' ranges from 2 to 36.
27+
converted to the given 'base'.
28+
Where 'base' ranges from 2 to 36.
2629
2730
Examples:
2831
>>> sum_of_digits(103, 12)
@@ -39,17 +42,17 @@ def sum_of_digits(num: int, base: int) -> str:
3942
>>> sum_of_digits(543, 37)
4043
Traceback (most recent call last):
4144
...
42-
ValueError: 'base_of_interest' must be between 36 and 2 inclusive
45+
ValueError: 'base' must be between 36 and 2 inclusive
4346
"""
4447

45-
if (base_of_interest > 36) or (base_of_interest < 2):
46-
raise ValueError("'base_of_interest' must be between 36 and 2 inclusive")
48+
if (base > 36) or (base < 2):
49+
raise ValueError("'base' must be between 36 and 2 inclusive")
4750

48-
num_str = int_to_base(num, base_of_interest)
51+
num_str = int_to_base(num, base)
4952
res = 0
5053
for char in num_str:
51-
res += int(char, base_of_interest)
52-
res_str = int_to_base(res, base_of_interest)
54+
res += int(char, base)
55+
res_str = int_to_base(res, base)
5356
return res_str
5457

5558

0 commit comments

Comments
 (0)