I am trying to convert an octal number to decimal.
The inputs are a set of strings as numbers such as "23", or "23 24", or "23 24 25". My code works for inputs like this, but cannot handle say "23 240", or "23 240 1" I.e. when the inputs are of different lengths, the array splits them incorrectly.
I think I've overcomplicated it by using arrays. Is there a way to assess each input individually (i.e. "23" then "240" then "1"), and then put these back into the desired output "19 160 1"?
Code:
import numpy as np
def decode(code):
decimals = []
code = code.split()
for n in code:
p = len(n)
for digit in n:
decimal = int(digit) * (8**(p - 1))
decimals.append(decimal)
p -= 1
split_input = np.array_split(decimals, len(code))
sum_decimals = []
for number in split_input:
sum_decimal = sum(map(int, number))
sum_decimals.append(str(sum_decimal))
separate_outputs = " ".join(sum_decimals)
return str(separate_outputs)
Does this work? Try running it in an instant interpreter such as Google Colab
CODE:
INPUT:
OUTPUT:
EXTRAS:
elsestatement to raise error if function does not receive a string array. OR, you could add multipleif...elsestatements to handle different data formats like:str,int,list,tuple, etc.