From a776b253a48ece09fad885aa19c111971ae2fda4 Mon Sep 17 00:00:00 2001 From: Simon Jakobi Date: Tue, 18 Mar 2014 05:34:18 +0100 Subject: [PATCH] python matrix added. --- EXERCISES.txt | 1 + matrix/example.py | 8 ++++++++ matrix/matrix_test.py | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 matrix/example.py create mode 100644 matrix/matrix_test.py diff --git a/EXERCISES.txt b/EXERCISES.txt index 04726f1fb5..8ab5e8b1dc 100644 --- a/EXERCISES.txt +++ b/EXERCISES.txt @@ -1,5 +1,6 @@ bob rna-transcription +matrix word-count anagram beer-song diff --git a/matrix/example.py b/matrix/example.py new file mode 100644 index 0000000000..2fc6e2d0df --- /dev/null +++ b/matrix/example.py @@ -0,0 +1,8 @@ +class Matrix(object): + def __init__(self, s): + self.rows = [[int(n) for n in row.split()] + for row in s.split('\n')] + + @property + def columns(self): + return map(list, zip(*self.rows)) diff --git a/matrix/matrix_test.py b/matrix/matrix_test.py new file mode 100644 index 0000000000..e901aebccc --- /dev/null +++ b/matrix/matrix_test.py @@ -0,0 +1,36 @@ +try: + from matrix import Matrix +except ImportError: + raise SystemExit('Could not find matrix.py. Does it exist?') + +import unittest + + +class MatrixTest(unittest.TestCase): + def test_extract_a_row(self): + matrix = Matrix("1 2\n10 20") + self.assertEqual([1, 2], matrix.rows[0]) + + def test_extract_same_row_again(self): + matrix = Matrix("9 7\n8 6") + self.assertEqual([9, 7], matrix.rows[0]) + + def test_extract_other_row(self): + matrix = Matrix("9 8 7\n19 18 17") + self.assertEqual([19, 18, 17], matrix.rows[1]) + + def test_extract_other_row_again(self): + matrix = Matrix("1 4 9\n16 25 36") + self.assertEqual([16, 25, 36], matrix.rows[1]) + + def test_extract_a_column(self): + matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n 8 7 6") + self.assertEqual([1, 4, 7, 8], matrix.columns[0]) + + def test_extract_another_column(self): + matrix = Matrix("89 1903 3\n18 3 1\n9 4 800") + self.assertEqual([1903, 3, 4], matrix.columns[1]) + + +if __name__ == '__main__': + unittest.main()