Funkcja przeskalowania macierzy

0

Zadanie:
Opis

Jako rozwiązanie kod:

def reduce(matIn, n_size):
    '''
    Function which reduces the size of matrix. Elements values are
    being calculated as average of neighbours
    :param matIn: bigger input matrix
    :param n_size: new size, has to be smaller
    :return:
    '''

    if isinstance(n_size,tuple) or isinstance(n_size, list):
        nx, ny = n_size
    elif isinstance(n_size,int):
        nx = n_size
        ny = nx
    else:
        raise Exception("New size should be tuple/list for nonsqure matrix or integer for squre matrix")


    sx = len(matIn)
    sy = len(matIn[0])


    if sx < nx or sy < ny:
        raise Exception("New size should be smaller then origin")


    nxs = sx / nx
    nys = sy / nx

    mat = [[0. for i in range(nx)] for j in range(ny)]


    for i in range(nx):
        for j in range(ny):

            x = int(i*nxs)
            y = int(j*nys)


            ids = 1
            s = matIn[x][y]
            for xi in range(-1, 2, 2):
                for yj in range(-1, 2, 2):
                    ii = x+xi
                    jj = y + yj

                    if 0 <= ii < sx and 0 <= jj < sy:
                        s += matIn[x+xi][y+yj]
                        ids += 1

            mat[i][j] = s/ids

    return mat

Tylko, że nie ma żadnych wyników. Jak to przetestować?

0

Najpierw musisz wywołać te funkcję:

reduce(arg1, arg2)

A wyświetlenie, skoro jest to macierz:

zmienna = reduce(arg1, arg2)
for wiersz in zmienna:
    for komorka in wiersz:
        print(komorka, end=" ")
    print()

Albo dziwniej i nieczytelniej w mniejszej ilości linii.

zmienna = reduce(arg1, arg2)
for wiersz in zmienna:
    print(("{:>4}"*len(wiersz)).format(*[i for i in wiersz]))
0

Chyba nie zrozumiałem...

Znalazłem jeszcze coś takiego jako test:

# Test
# m = [[float(i*j) for i in range(5)] for j in range(5)]
#
# print np.array(m)
#
# print np.array(reduce(m, (3, 3)))

Ale zwraca Invalid syntax.

Edyta mówi:

pewnie, że zwraca błąd skoro print nie jest w nawiasach.

I powinno to wyglądać tak:

# Test
#import numpy as np
#m = [[float(i*j) for i in range(5)] for j in range(5)]
#
#print (np.array(m))
#
#print (np.array(reduce(m, (3, 3))))

1 użytkowników online, w tym zalogowanych: 0, gości: 1