Skip to content

octal_to_decimal converter #2399

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 10, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions conversions/octal_to_decimal
Original file line number Diff line number Diff line change
@@ -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()