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
#2
You cannot call each add() function because you only have one add() function, the one function, the last add() function. If you want to call all the add() functions you need them to all have different names.

To run your test you could import the add function you want to test and name it add. In your test file:
from add import add1 as add
What you are trying to do is an odd use case, so don't be surprised that unittest is an awkward tool for your testing. I think unittest is an awkward tool period, and much prefer pytest.
Reply
#3
As mention you most name function wih unique name eg add1 add2.
# file: add_functions.py
# solution1
def add1(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 add2(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
Now to give a example using pytest
A better tool than unittest as deanhystad mention.
# file: test_add.py
import pytest
from add_functions import add1, add2

test_cases = [
    (add1, [[[5]], [[-2]]], [[3]]),
    (add2, [[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[6, 8], [10, 12]]),
]

@pytest.mark.parametrize('add_func, input_matrices, expected_output', test_cases)
def test_add(add_func, input_matrices, expected_output):
    actual_output = add_func(input_matrices[0], input_matrices[1])
    print(f"\nRunning {add_func.__name__} with input {input_matrices}:")
    print(f"Output: {actual_output}")
    assert actual_output == expected_output, (
        f"Expected {expected_output}, got {actual_output}."
    )
So if add -s it will also show output,and not just passed or failed.
Output:
G:\div_code\matx λ pytest -v -s =========test session starts ============ platform win32 -- Python 3.11.3, pytest-7.4.2, pluggy-1.3.0 -- C:\python311\python.exe cachedir: .pytest_cache rootdir: G:\div_code\matx collected 2 items test_add.py::test_add[add1-input_matrices0-expected_output0] Running add1 with input [[[5]], [[-2]]]: Output: [[3]] PASSED test_add.py::test_add[add2-input_matrices1-expected_output1] Running add2 with input [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]: Output: [[6, 8], [10, 12]] PASSED
akbarza likes this post
Reply
#4
(Feb-12-2024, 05:43 PM)snippsat Wrote: As mention you most name function wih unique name eg add1 add2.
# file: add_functions.py
# solution1
def add1(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 add2(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
Now to give a example using pytest
A better tool than unittest as deanhystad mention.
# file: test_add.py
import pytest
from add_functions import add1, add2

test_cases = [
    (add1, [[[5]], [[-2]]], [[3]]),
    (add2, [[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[6, 8], [10, 12]]),
]

@pytest.mark.parametrize('add_func, input_matrices, expected_output', test_cases)
def test_add(add_func, input_matrices, expected_output):
    actual_output = add_func(input_matrices[0], input_matrices[1])
    print(f"\nRunning {add_func.__name__} with input {input_matrices}:")
    print(f"Output: {actual_output}")
    assert actual_output == expected_output, (
        f"Expected {expected_output}, got {actual_output}."
    )
So if add -s it will also show output,and not just passed or failed.
Output:
G:\div_code\matx λ pytest -v -s =========test session starts ============ platform win32 -- Python 3.11.3, pytest-7.4.2, pluggy-1.3.0 -- C:\python311\python.exe cachedir: .pytest_cache rootdir: G:\div_code\matx collected 2 items test_add.py::test_add[add1-input_matrices0-expected_output0] Running add1 with input [[[5]], [[-2]]]: Output: [[3]] PASSED test_add.py::test_add[add2-input_matrices1-expected_output1] Running add2 with input [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]: Output: [[6, 8], [10, 12]] PASSED

hi
thanks for reply
i copied and runned the two your codes in idle and Thonny. no error message has been displayed but also nothing in output has been displayed.
then i went in cmd( also i did in Thonny>>tools>>open system shell). in cmd, i wrote the below commands and got the mentioned output:
( i renamed your pytest.py to pytest_usage_for_test.py)
>> pytest_usage_for_test.py
output was: nothing
>>python pytest_usage_for_test.py
output was : nothing
>>pytest_usage_for_test.py -v -s
output was : nothing
>>pytest_usage_for_test -v -s
output was : nothing
>>python pytest_usage_for_test.py -v -s
output was : nothing
>>python pytest_usage_for_test -v -s
output was : python: can't open file 'D:\\Desktop\\pythonmorsels_add\\pytest_usage_for_test': [Errno 2] No such file or directory

why can't see your output?
thanks
Reply
#5
pytest should be used from command line,not at all from any Editor/Ide(even if can get it do work with some effort).
Also as you use Windows get a better terminal sell eg cmder.
[Image: aIdQxC.png]
Make a error,see that if will give full diff of where the error is.
[Image: KHNGcr.png]
Reply
#6
(Feb-13-2024, 10:06 AM)snippsat Wrote: pytest should be used from command line,not at all from any Editor/Ide(even if can get it do work with some effort).
Also as you use Windows get a better terminal sell eg cmder.
[Image: aIdQxC.png]
Make a error,see that if will give full diff of where the error is.
[Image: KHNGcr.png]

please see below:


Output:
D:\Desktop\pythonmorsels_add λ ls __pycache__/ add.py add_functions.py add_solution.pdf akb_add.py hello.py pytest_usage_for_test.py test_add.py D:\Desktop\pythonmorsels_add λ pytest -v -s ==================================================================== test session starts ================================ platform win32 -- Python 3.11.5, pytest-7.4.3, pluggy-1.3.0 -- C:\python_3_11_5\python.exe cachedir: .pytest_cache rootdir: D:\Desktop\pythonmorsels_add plugins: anyio-3.7.1 collected 9 items pytest_usage_for_test.py::test_add[add1-input_matrices0-expected_output0] Running add1 with input [[[5]], [[-2]]]: Output: [[3]] PASSED pytest_usage_for_test.py::test_add[add2-input_matrices1-expected_output1] Running add2 with input [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]: Output: [[6, 8], [10, 12]] PASSED test_add.py::AddTests::test_any_number_of_matrixes XFAIL test_add.py::AddTests::test_different_matrix_size XFAIL test_add.py::AddTests::test_input_unchanged PASSED test_add.py::AddTests::test_single_items PASSED test_add.py::AddTests::test_two_by_three_matrixes PASSED test_add.py::AddTests::test_two_by_two_matrixes PASSED test_add.py::AddTests::test_zreturn_instead_of_print PASSED =============================================================== 7 passed, 2 xfailed in 1.22s ============================
it is ok?
but when in cmder wrote: pytest_usage_for_test.py,again nothing occured.
buran write Feb-14-2024, 06:48 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#7
(Feb-14-2024, 06:56 AM)akbarza Wrote:
(Feb-13-2024, 10:06 AM)snippsat Wrote: pytest should be used from command line,not at all from any Editor/Ide(even if can get it do work with some effort).
Also as you use Windows get a better terminal sell eg cmder.
[Image: aIdQxC.png]
Make a error,see that if will give full diff of where the error is.
[Image: KHNGcr.png]

please see below:


Output:
D:\Desktop\pythonmorsels_add λ ls __pycache__/ add.py add_functions.py add_solution.pdf akb_add.py hello.py pytest_usage_for_test.py test_add.py D:\Desktop\pythonmorsels_add λ pytest -v -s ==================================================================== test session starts ================================ platform win32 -- Python 3.11.5, pytest-7.4.3, pluggy-1.3.0 -- C:\python_3_11_5\python.exe cachedir: .pytest_cache rootdir: D:\Desktop\pythonmorsels_add plugins: anyio-3.7.1 collected 9 items pytest_usage_for_test.py::test_add[add1-input_matrices0-expected_output0] Running add1 with input [[[5]], [[-2]]]: Output: [[3]] PASSED pytest_usage_for_test.py::test_add[add2-input_matrices1-expected_output1] Running add2 with input [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]: Output: [[6, 8], [10, 12]] PASSED test_add.py::AddTests::test_any_number_of_matrixes XFAIL test_add.py::AddTests::test_different_matrix_size XFAIL test_add.py::AddTests::test_input_unchanged PASSED test_add.py::AddTests::test_single_items PASSED test_add.py::AddTests::test_two_by_three_matrixes PASSED test_add.py::AddTests::test_two_by_two_matrixes PASSED test_add.py::AddTests::test_zreturn_instead_of_print PASSED =============================================================== 7 passed, 2 xfailed in 1.22s ============================
it is ok?
but when in cmder wrote: pytest_usage_for_test.py,again nothing occured.

hi
the running of pytest is strange:
in cmd or cmder, I have to go to the folder where my .py file is there, and then in cmd(or cmder) I have write pytest -v -s to take results. if I call Python file, nothing is displayed
Reply
#8
(Feb-14-2024, 07:14 AM)akbarza Wrote: the running of pytest is strange:
in cmd or cmder, I have to go to the folder where my .py file is there, and then in cmd(or cmder) I have write pytest -v -s to take results. if I call Python file, nothing is displayed
It's working,as i mention pytest should always be used from commad line(cmder).
Can look at this post where i expalin(pytest_args) how to run pytest from eg a editor(i never do this).

Also look at cmder Shortcut to open Cmder in a chosen folder
Then can go directly from file explorer(right click) to any folder.
In general get better with command line usage is a important part of programming.
akbarza likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  writing and running code in vscode without saving it akbarza 1 396 Jan-11-2024, 02:59 PM
Last Post: deanhystad
  the order of running code in a decorator function akbarza 2 535 Nov-10-2023, 08:09 AM
Last Post: akbarza
  Code running many times nad not just one? korenron 4 1,376 Jul-24-2022, 08:12 AM
Last Post: korenron
  Error while running code on VSC maiya 4 3,776 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,515 Apr-06-2022, 03:41 PM
Last Post: Gribouillis
  Why is this Python code running twice? mcva 5 5,296 Feb-02-2022, 10:21 AM
Last Post: mcva
  Python keeps running the old version of the code quest 2 3,789 Jan-20-2022, 07:34 AM
Last Post: ThiefOfTime
  My python code is running very slow on millions of records shantanu97 7 2,588 Dec-28-2021, 11:02 AM
Last Post: Larz60+
  I am getting ValueError from running my code PythonMonkey 0 1,481 Dec-26-2021, 06:14 AM
Last Post: PythonMonkey
  rtmidi problem after running the code x times philipbergwerf 1 2,433 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