Splitting arrays in unequal chunks using np.array_split: overcomplicating?

67 Views Asked by At

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)
1

There are 1 best solutions below

2
Shisui Otsutsuki On

Does this work? Try running it in an instant interpreter such as Google Colab

CODE:

import numpy as np

def decode(code):
  if isinstance(code, str):
    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)

INPUT:

str1 = input('Enter octals:') #23 240 1
decode(str1)

OUTPUT:

19 160 1

EXTRAS:

  1. If you copy code make sure to adjust tabs because that could lead to multiple errors.
  2. Also, you could put an else statement to raise error if function does not receive a string array. OR, you could add multiple if...else statements to handle different data formats like: str, int, list, tuple, etc.