From e1755cbf442bf4cb84c5413eb56ff2c384364396 Mon Sep 17 00:00:00 2001 From: NIKITA PANDEY <113332472+nikitapandeyy@users.noreply.github.com> Date: Sun, 26 Mar 2023 23:24:53 +0530 Subject: [PATCH] Update HexToDec.py The code has a few issues: The __getDecDigit() function is unnecessarily defined as a private function. Since it is not a method of a class, it can simply be defined as a regular function. The __getDecDigit() function can be simplified by using the index() method of a list to find the index of the given digit. The hexToDec() function is not returning the decimal number, it is only printing it. It should be modified to return the value instead. The loop in the hexToDec() function is iterating over the length of the hex number in reverse order. This is unnecessary and can be simplified to a regular forward loop. --- HexToDec.py | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/HexToDec.py b/HexToDec.py index 2b289400..274f1ccb 100644 --- a/HexToDec.py +++ b/HexToDec.py @@ -1,18 +1,13 @@ -# Python Hexadecimal to Decimal Conversion +def getDecDigit(digit): + digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] + return digits.index(digit) -def __getDecDigit(digit): - digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'A', 'B', 'C', 'D', 'E', 'F'] - for x in range(len(digits)): - if digit == digits[x]: - return x - def hexToDec(hexNum): - decNum = 0 - power = 0 - for digit in range(len(hexNum), 0, -1): - decNum = decNum + 16 ** power * __getDecDigit(hexNum[digit-1]) - power += 1 - print(str(decNum)) - -hexToDec("A5") \ No newline at end of file + decNum = 0 + power = 0 + for digit in hexNum: + decNum = decNum + 16 ** power * getDecDigit(digit) + power += 1 + return decNum + +print(hexToDec("A5")) # should print 165