MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / int_to_base

Function int_to_base

maths/special_numbers/harshad_numbers.py:8–53  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

6
7
8def 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
56def sum_of_digits(num: int, base: int) -> str:

Callers 3

sum_of_digitsFunction · 0.85
harshad_numbers_in_baseFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected