well, I'd say your issue is that it looks like you've learned how to make classes, and before thinking about the problem you're trying to solve, you're writing a class.
But what you want can simply be done with a loop in a function, without any magic or external thing:
def to_matrix(array, nb_rows, nb_cols):
# initialise the matrix and a row
matrix = []
row = []
# for each item of the array, O(n)
for item in array:
# add an item to the row
row.append(item)
# if the row has reached the number of columns
if len(row) == nb_cols:
# add the row to the matrix
matrix.append(row)
# reset the row for a new iteration
row = []
# if once the loop is finished the row isn't empty
# and has less elements than the number of columns
if len(row) <= nb_cols:
# pad the row with Nones
row += [None]*(nb_cols-len(row))
# and add it to the matrix
matrix.append(row)
# return the matrix
return matrix
here's how to run it:
>>> to_matrix(['apple', 'banana', 'dog', 'spider', 'koala'], 3, 3)
[['apple', 'banana', 'dog'], ['spider', 'koala', None]]
>>> to_matrix(['apple', 'banana', 'dog', 'spider', 'koala'], 3,2)
[['apple', 'banana'], ['dog', 'spider'], ['koala', None]]
that algorithm:
- is
O(n), which means it's linear to the number of elements in the array,
- ignores empty rows,
- strip the array from overflowing elements, in case the matrix "surface" is smaller than the array's "length".
I want to convert the list within the init method, but not really sure how to do this. Would it be better to create a separate method, or should I add it to my init method? I want to be efficient.
wherever you put the function won't impact efficiency, just readability of your code, its modularity, flexibility and SOLID properties of your class.
Because you're not manipulating your class with that method (no need for self), you should simply make it a function as above, and call it where you need it. And the constructor is as good a place as any other, it's really depending on the higher order algorithm the whole fits. e.g.:
def __init__(self, array, row, col):
self.array = to_matrix(array, row, col)
[None, None, None]?