8000 Modified octal_to_decimal by cybov · Pull Request #3243 · TheAlgorithms/Python · GitHub
[go: up one dir, main page]

Skip to content

Modified octal_to_decimal #3243

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

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
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
Next Next commit
Added comments with some code midifications
  • Loading branch information
cybov committed Oct 12, 2020
commit 9b1dc8d5f1f3113deae76a8910bf7b8c1ae2ada5
30 changes: 22 additions & 8 deletions conversions/octal_to_decimal
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,40 @@ def oct_to_decimal(oct_string: str) -> int:
>>> oct_to_decimal("-45")
-37
>>> oct_to_decimal("2-0Fm")
Traceback (most recent call last):
...
ValueError: Non-octal value was passed to the function
>>> oct_to_decimal("")
Traceback (most recent call last):
...
ValueError: Empty string value was passed to the function
>>> oct_to_decimal("19")
Traceback (most recent call last):
...
ValueError: Non-octal value was passed to the function
"""
# Strip oct_string of whitespaces
oct_string = str(oct_string).strip()
if not oct_string:
raise ValueError("Empty string was passed to the function")
raise ValueError("Empty string value was passed to the function")

# Check if oct_string is a negative value
is_negative = oct_string[0] == "-"
if is_negative:
# Remove (-) from oct_string
oct_string = oct_string[1:]
if not all(0 <= int(char) <= 7 for char in oct_string):

# check if oct_string is an octal value and convert
if oct_string.isdecimal() and all(0 <= int(char) <= 7 for char in oct_string):
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
else:
# else raise exception
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__":
Expand Down
0