Python: How do I fix array of arrays returning none?

Question:

This is my first post, and I am also new to programming, so I am sorry if I am doing anything atrociously wrong here.

I am trying to create a function that takes in an array and returns an array of arrays, with each inside array being two (or three) in length. (i.e. [1, 2, 3, 4, 5] returns [[1, 2], [3, 4, 5]])

Here is my code:

def split(array):
    newArray = []
    if len(array[0]) == 2:
        return array

    for i in range(len(array)):
        newArray.append(array[i][:len(array[i])//2])
        newArray.append(array[i][len(array[i])//2:])

    split(newArray)

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(split([array]))

When I run it everything works fine until the return statement, which returns None, printing nothing (I was able to pinpoint the problem using PyCharm’s debugger).

Is there something wrong with returning an array of arrays?

Asked By: Mark Apinis

||

Answers:

You are missing a return statement at the end of your function:

def split(array):
    newArray = []
    if len(array[0]) == 2:
        return array

    for i in range(len(array)):
        newArray.append(array[i][:len(array[i])//2])
        newArray.append(array[i][len(array[i])//2:])

    return split(newArray) # return this

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(split([array]))

>>> [[1, 2], [3, 4, 5], [6, 7], [8, 9, 10]]
Answered By: Bahrom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.