Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem in running a code
#1
hi
in site: https://www.pythonmorsels.com/exercises/.../submit/1/
has been discussed the problem of adding two list of lists.
there, has been given several solutions. I copied and paste all solution in a .py file as below:
'''
add two list of lists.
problem: https://www.pythonmorsels.com/exercises/cb8fbdd52cf14f8cb31df4f06343cccf/submit/1/
solution by :https://www.pythonmorsels.com/exercises/cb8fbdd52cf14f8cb31df4f06343cccf/solution/
'''

# solution1
def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for i in range(len(matrix1)):
        row = []
        for j in range(len(matrix1[i])):
            row.append(matrix1[i][j] + matrix2[i][j])
        combined.append(row)
    return combined


#solution2:

def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for rows in zip(matrix1, matrix2):
        row = []
        for items in zip(rows[0], rows[1]):
            row.append(items[0] + items[1])
        combined.append(row)
    return combined

# solution3
def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for row1, row2 in zip(matrix1, matrix2):
        row = []
        for n, m in zip(row1, row2):
            row.append(n + m)
        combined.append(row)
    return combined

#solution4
def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for row1, row2 in zip(matrix1, matrix2):
        row = [
            n + m
            for n, m in zip(row1, row2)
        ]
        combined.append(row)
    return combined

#solution5
def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for row1, row2 in zip(matrix1, matrix2):
        combined.append([
            n + m
            for n, m in zip(row1, row2)
        ])
    return combined

def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for row1, row2 in zip(matrix1, matrix2):
        combined.append([n + m for n, m in zip(row1, row2)])
    return combined

def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    return [
        [n + m for n, m in zip(row1, row2)]
        for row1, row2 in zip(matrix1, matrix2)
    ]



def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    return [[n+m for n, m in zip(r1, r2)] for r1, r2 in zip(matrix1, matrix2)]

def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    return [
        [n + m for n, m in zip(row1, row2)]
        for row1, row2 in zip(matrix1, matrix2)
        ]

def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for row1, row2 in zip(matrix1, matrix2):
        row = []
        for n, m in zip(row1, row2):
            row.append(n + m)
        combined.append(row)
    return combined

#bonus1  refer to:https://www.pythonmorsels.com/exercises/cb8fbdd52cf14f8cb31df4f06343cccf/submit/1/
def add(*matrices):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for rows in zip(*matrices):
        row = []
        for values in zip(*rows):
            total = 0
            for n in values:
                total += n
            row.append(total)
        combined.append(row)
    return combined

def add(*matrices):
    """Add corresponding numbers in given 2-D matrices."""
    combined = []
    for rows in zip(*matrices):
        row = []
        for values in zip(*rows):
            row.append(sum(values))
        combined.append(row)
    return combined

def add(*matrices):
    """Add corresponding numbers in given 2-D matrices."""
    return [
        [sum(values) for values in zip(*rows)]
        for rows in zip(*matrices)
    ]
        
        
        
#bonus2  #https://www.pythonmorsels.com/exercises/cb8fbdd52cf14f8cb31df4f06343cccf/submit/1/
def add(matrix1, matrix2):
    """Add corresponding numbers in given 2-D matrices."""
    if [len(r) for r in matrix1] != [len(r) for r in matrix2]:
        raise ValueError("Given matrices are not the same size.")
    return [
        [n + m for n, m in zip(row1, row2)]
        for row1, row2 in zip(matrix1, matrix2)
    ]


def add(*matrices):
    """Add corresponding numbers in given 2-D matrices."""
    matrix_shapes = {
        tuple(len(r) for r in matrix)
        for matrix in matrices
    }
    if len(matrix_shapes) > 1:
        raise ValueError("Given matrices are not the same size.")
    return [
        [sum(values) for values in zip(*rows)]
        for rows in zip(*matrices)
    ]

from itertools import zip_longest


def add(*matrices):
    """Add corresponding numbers in given 2-D matrices."""
    try:
        return [
            [sum(values) for values in zip_longest(*rows)]
            for rows in zip_longest(*matrices)
        ]
    except TypeError as e:
        raise ValueError("Given matrices are not the same size.") from e
    
    
def get_shape(matrix):
    return [len(r) for r in matrix]


def add(*matrices):
    """Add corresponding numbers in given 2-D matrices."""
    shape_of_matrix = get_shape(matrices[0])
    if any(get_shape(m) != shape_of_matrix for m in matrices):
        raise ValueError("Given matrices are not the same size.")
    return [
        [sum(values) for values in zip(*rows)]
        for rows in zip(*matrices)
    ]

def add(*matrices):
    """Add corresponding numbers in given 2-D matrices."""
    return [
        [sum(values) for values in zip(*rows, strict=True)]
        for rows in zip(*matrices, strict=True)
    ]
the test file is :
from contextlib import redirect_stdout
from copy import deepcopy
from io import StringIO
import unittest

from add import add


class AddTests(unittest.TestCase):

    """Tests for add."""

    def test_zreturn_instead_of_print(self):
        with redirect_stdout(StringIO()) as stdout:
            actual = add([[5]], [[-2]])
        output = stdout.getvalue().strip()
        if actual is None and output:
            self.fail(
                "\n\nUh oh!\n"
                "It looks like you may have printed instead of returning.\n"
                "See https://pym.dev/print-vs-return/\n"
                f"None was returned but this was printed:\n{output}"
            )

    def test_single_items(self):
        self.assertEqual(add([[5]], [[-2]]), [[3]])

    def test_two_by_two_matrixes(self):
        m1 = [[6, 6], [3, 1]]
        m2 = [[1, 2], [3, 4]]
        m3 = [[7, 8], [6, 5]]
        self.assertEqual(add(m1, m2), m3)

    def test_two_by_three_matrixes(self):
        m1 = [[1, 2, 3], [4, 5, 6]]
        m2 = [[-1, -2, -3], [-4, -5, -6]]
        m3 = [[0, 0, 0], [0, 0, 0]]
        self.assertEqual(add(m1, m2), m3)

    def test_input_unchanged(self):
        m1 = [[6, 6], [3, 1]]
        m2 = [[1, 2], [3, 4]]
        m1_original = deepcopy(m1)
        m2_original = deepcopy(m2)
        add(m1, m2)
        self.assertEqual(m1, m1_original)
        self.assertEqual(m2, m2_original)

    # To test bonus 1, comment out the next line
    @unittest.expectedFailure
    def test_any_number_of_matrixes(self):
        m1 = [[6, 6], [3, 1]]
        m2 = [[1, 2], [3, 4]]
        m3 = [[2, 1], [3, 4]]
        m4 = [[9, 9], [9, 9]]
        m5 = [[31, 32], [27, 24]]
        self.assertEqual(add(m1, m2, m3), m4)
        self.assertEqual(add(m2, m3, m1, m1, m2, m4, m1), m5)

    # To test bonus 2, comment out the next line
    @unittest.expectedFailure
    def test_different_matrix_size(self):
        m1 = [[6, 6], [3, 1]]
        m2 = [[1, 2], [3, 4], [5, 6]]
        m3 = [[6, 6], [3, 1, 2]]
        with self.assertRaises(ValueError):
            add(m1, m2)
        with self.assertRaises(ValueError):
            add(m1, m3)
        with self.assertRaises(ValueError):
            add(m1, m1, m1, m3, m1, m1)
        with self.assertRaises(ValueError):
            add(m1, m1, m1, m2, m1, m1)


class AllowUnexpectedSuccessRunner(unittest.TextTestRunner):
    """Custom test runner to avoid FAILED message on unexpected successes."""
    class resultclass(unittest.TextTestResult):
        def wasSuccessful(self):
            return not (self.failures or self.errors)


if __name__ == "__main__":
    from platform import python_version
    import sys
    if sys.version_info < (3, 6):
        sys.exit("Running {}.  Python 3.6 required.".format(python_version()))
    unittest.main(verbosity=2, testRunner=AllowUnexpectedSuccessRunner)
I want to call each add function and see the result of it.
what I did, was I first renamed all add functions except one and the run test file, and then I saw the result of it.
for the other add function, I again renamed the add function in the before stage ( to sth other than add) and renamed one of the other add functions( rename to add) and the run test file again.
but it is very time-consuming.
do you know a better way to do that? namely, do you know any method to run each add function without renaming all? is there any way?
thanks.
Reply


Messages In This Thread
problem in running a code - by akbarza - Feb-12-2024, 01:29 PM
RE: problem in running a code - by deanhystad - Feb-12-2024, 04:41 PM
RE: problem in running a code - by snippsat - Feb-12-2024, 05:43 PM
RE: problem in running a code - by akbarza - Feb-13-2024, 07:14 AM
RE: problem in running a code - by snippsat - Feb-13-2024, 10:06 AM
RE: problem in running a code - by akbarza - Feb-14-2024, 06:56 AM
RE: problem in running a code - by akbarza - Feb-14-2024, 07:14 AM
RE: problem in running a code - by snippsat - Feb-14-2024, 02:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  writing and running code in vscode without saving it akbarza 1 536 Jan-11-2024, 02:59 PM
Last Post: deanhystad
  the order of running code in a decorator function akbarza 2 670 Nov-10-2023, 08:09 AM
Last Post: akbarza
  Code running many times nad not just one? korenron 4 1,506 Jul-24-2022, 08:12 AM
Last Post: korenron
  Error while running code on VSC maiya 4 4,151 Jul-01-2022, 02:51 PM
Last Post: maiya
  code running for more than an hour now, yet didn't get any result, what should I do? aiden 2 1,671 Apr-06-2022, 03:41 PM
Last Post: Gribouillis
  Why is this Python code running twice? mcva 5 5,609 Feb-02-2022, 10:21 AM
Last Post: mcva
  Python keeps running the old version of the code quest 2 4,059 Jan-20-2022, 07:34 AM
Last Post: ThiefOfTime
  My python code is running very slow on millions of records shantanu97 7 2,795 Dec-28-2021, 11:02 AM
Last Post: Larz60+
  I am getting ValueError from running my code PythonMonkey 0 1,553 Dec-26-2021, 06:14 AM
Last Post: PythonMonkey
  rtmidi problem after running the code x times philipbergwerf 1 2,558 Apr-04-2021, 07:07 PM
Last Post: philipbergwerf

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020