Skip to content

Commit 3b63857

Browse files
jasper256cclauss
authored andcommitted
added automated doctest to decimal_to_hexadecimal.py in conversions (#1071)
* added automated doctest to decimal_to_hexadecimal.py in conversions * improved error handling and added more test cases in decimal_to_hexadecimal.py * implemented 0x notation and simplified AssertionError * fixed negative notation and added comparison test against Python hex function
1 parent 46bc673 commit 3b63857

File tree

1 file changed

+45
-14
lines changed

1 file changed

+45
-14
lines changed

conversions/decimal_to_hexadecimal.py

+45-14
Original file line numberDiff line numberDiff line change
@@ -21,23 +21,54 @@
2121
}
2222

2323
def decimal_to_hexadecimal(decimal):
24-
""" take decimal value, return hexadecimal representation as str """
24+
"""
25+
take integer decimal value, return hexadecimal representation as str beginning with 0x
26+
>>> decimal_to_hexadecimal(5)
27+
'0x5'
28+
>>> decimal_to_hexadecimal(15)
29+
'0xf'
30+
>>> decimal_to_hexadecimal(37)
31+
'0x25'
32+
>>> decimal_to_hexadecimal(255)
33+
'0xff'
34+
>>> decimal_to_hexadecimal(4096)
35+
'0x1000'
36+
>>> decimal_to_hexadecimal(999098)
37+
'0xf3eba'
38+
>>> # negatives work too
39+
>>> decimal_to_hexadecimal(-256)
40+
'-0x100'
41+
>>> # floats are acceptable if equivalent to an int
42+
>>> decimal_to_hexadecimal(17.0)
43+
'0x11'
44+
>>> # other floats will error
45+
>>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS
46+
Traceback (most recent call last):
47+
...
48+
AssertionError
49+
>>> # strings will error as well
50+
>>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS
51+
Traceback (most recent call last):
52+
...
53+
AssertionError
54+
>>> # results are the same when compared to Python's default hex function
55+
>>> decimal_to_hexadecimal(-256) == hex(-256)
56+
True
57+
"""
58+
assert type(decimal) in (int, float) and decimal == int(decimal)
2559
hexadecimal = ''
60+
negative = False
61+
if decimal < 0:
62+
negative = True
63+
decimal *= -1
2664
while decimal > 0:
27-
remainder = decimal % 16
28-
decimal -= remainder
65+
decimal, remainder = divmod(decimal, 16)
2966
hexadecimal = values[remainder] + hexadecimal
30-
decimal /= 16
67+
hexadecimal = '0x' + hexadecimal
68+
if negative:
69+
hexadecimal = '-' + hexadecimal
3170
return hexadecimal
3271

33-
def main():
34-
""" print test cases """
35-
print("5 in hexadecimal is", decimal_to_hexadecimal(5))
36-
print("15 in hexadecimal is", decimal_to_hexadecimal(15))
37-
print("37 in hexadecimal is", decimal_to_hexadecimal(37))
38-
print("255 in hexadecimal is", decimal_to_hexadecimal(255))
39-
print("4096 in hexadecimal is", decimal_to_hexadecimal(4096))
40-
print("999098 in hexadecimal is", decimal_to_hexadecimal(999098))
41-
4272
if __name__ == '__main__':
43-
main()
73+
import doctest
74+
doctest.testmod()

0 commit comments

Comments
 (0)