0

I'm reposting my question because someone closed my question when it wasn't answered correctly and I can't reopen it myself.

I'm trying to convert a list of words to a 2D array without using any of the numpy and any of the extension methods. I want to figure it out without the extra methods, but I'm very stuck.

def __init__(self, array = [], row, col):
    self.row = row
    self.col = col
    self.array = array

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.

['apple', 'banana', 'dog', 'spider', 'koala']

should be

[['apple,' 'banana', 'dog'], ['spider', 'koala', None]]

when rows = 3 and cols = 3. I'm also trying to implement other methods, but need to first convert the list to a 2D array.

To clarify, a 2 row 3 column array would look like:

[['apple', 'banana'], ['dog', 'spider'], ['koala', None]]
2
  • If rows and cols are both 3, shouldn't you have a third row of [None, None, None] ? Commented Apr 28, 2017 at 23:58
  • I agree it should, but based on the OP's example, it does not… Commented Apr 29, 2017 at 0:02

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I'll look more into what you said about manipulating classes.
As a rule of thumb, always remember simpler is better.
0

A quick version using generators:

def gen_array(data, count):
    for i, v in enumerate(data):
        if i == count:  # Shorten too long arrays
            break
        yield v
    for c in range(count - len(data)):  # Extend if needed
        yield None

def matrix(array, row, col):
    l = list(gen_array(array, row * col))
    for i in range(0, len(l), col):
        yield l[i:i + col]

mat = list(matrix([1, 2, 3, 4, 5], 3, 4))

Can take empty lists, too short and too long lists. The code can probably also be simplified even more.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.