Compare commits

...

2 Commits

Author SHA1 Message Date
pre-commit-ci[bot]
eedc5935ad [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2023-08-13 05:53:56 +00:00
Navanit Nandakumar
b8b3b8c593
Update octal_to_binary.py
Made the code more efficient
2023-08-13 11:22:31 +05:30

View File

@ -59,30 +59,16 @@ def octal_to_binary(octal: str) -> str:
oct_string = str(octal).strip()
if not oct_string:
raise ValueError("Empty string was passed to the function")
is_negative = oct_string[0] == "-"
is_negative = oct_string.startswith("-")
if is_negative:
oct_string = oct_string[1:]
binary_num = "-0b"
else:
binary_num = "0b"
if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string):
raise ValueError("Non-octal value was passed to the function")
decimal_number = 0
for char in oct_string:
decimal_number = 8 * decimal_number + int(char)
if is_negative:
decimal_number = -decimal_number
# Converting Decimal to Binary
if decimal_number == 0:
return "0b0"
negative = False
if decimal_number < 0:
negative = True
decimal_number = -decimal_number
binary: list[int] = []
while decimal_number > 0:
binary.insert(0, decimal_number % 2)
decimal_number >>= 1
if negative:
return "-0b" + "".join(str(e) for e in binary)
return "0b" + "".join(str(e) for e in binary)
binary_num += str(bin(int(oct_string, 8)))[2:]
return binary_num
if __name__ == "__main__":