Skip to content

Instantly share code, notes, and snippets.

@Victoria-Hodder
Created July 21, 2020 08:35
Show Gist options
  • Save Victoria-Hodder/cf9929613e9c0bd75df4071e310ceaac to your computer and use it in GitHub Desktop.
Save Victoria-Hodder/cf9929613e9c0bd75df4071e310ceaac to your computer and use it in GitHub Desktop.
class Matrix:
def __init__(self, matrix_string):
self.matrix_string = matrix_string
def row(self, index):
row = list(self.matrix_string.split("\n"))
return row[index]
"""
My logic is:
1. Take the string
2. Split at \n
3. Convert this into list(s) within a list
4. Access the required row with an index
What I have so far prints: 5 6 7 8
This fails the tests because it is expecting the output: [5, 6, 7, 8]
"""
def column(self, index):
pass
matrix = Matrix("1 2 3 4\n5 6 7 8\n9 8 7 6")
print(matrix.row(1))
@gotche
Copy link

gotche commented Jul 24, 2020

Is this what you need?

In [1]: matrix = '1 2 3 4\n5 6 7 8\n9 8 7 6'

In [2]: matrix.split('\n')
Out[2]: ['1 2 3 4', '5 6 7 8', '9 8 7 6']

In [3]: [l.split() for l in matrix.split('\n')]
Out[3]: [['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '8', '7', '6']]

@Victoria-Hodder
Copy link
Author

I don't think so, because the output has to be without strings, only a list of integers. Like this: [5,6,7,8]

@Victoria-Hodder
Copy link
Author

Victoria-Hodder commented Jul 27, 2020

I found a very cool solution in the community section. Now I work to understand it!!

class Matrix:
    def __init__(self, matrix_string):
        self.map = [[int(num) for num in rows.split()] for rows in matrix_string.split("\n")]

    def row(self, index):
        return self.map[index-1]

    def column(self, index):
        return [row[index-1] for row in self.map]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment