octal_to_decimal converter (#2399)

* Create octal_to_decimal

octal to decimal converter

* Update octal_to_decimal

* Update conversions/octal_to_decimal

Co-authored-by: Christian Clauss <cclauss@me.com>

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
mohammadreza490 2020-09-10 09:37:29 +01:00 committed by GitHub
parent 4d0a8f2355
commit 696cd47e15
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,37 @@
def oct_to_decimal(oct_string: str) -> int:
"""
Convert a octal value to its decimal equivalent
>>> oct_to_decimal("12")
10
>>> oct_to_decimal(" 12 ")
10
>>> oct_to_decimal("-45")
-37
>>> oct_to_decimal("2-0Fm")
ValueError: Non-octal value was passed to the function
>>> oct_to_decimal("")
ValueError: Empty string value was passed to the function
>>> oct_to_decimal("19")
ValueError: Non-octal value was passed to the function
"""
oct_string = str(oct_string).strip()
if not oct_string:
raise ValueError("Empty string was passed to the function")
is_negative = oct_string[0] == "-"
if is_negative:
oct_string = oct_string[1:]
if 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
return decimal_number
if __name__ == "__main__":
from doctest import testmod
testmod()