0

I am totally new to programming, and I have written this function function to take a matrix and maps each nonzero element to its inverse and zero to zero in python. Here is my code:

def question_1_c(arr):
    new_arr = []
    for i in range(len(arr)):
        row_arr = []
        for j in range(len(arr[i])):
            row_arr.append(1/ arr[i][j])
        new_arr.append(row_arr)
    return new_arr

question_1_c([[70,0,13,67],[90,48,57,26],[43,45,67,89],[88,65,44,23]])

For some reason it gives an error. Can anyone help?

4

2 回答 2

1

我得到的错误是除以零,这是有道理的,因为您从不检查零值。你也在做整数除法——这不会像你期望的那样做。

此外,在 Python 中,您可以迭代集合。我已经重写了您的代码,这应该可以满足您的期望。

def question_1_c(arr):
    new_arr = []
    for row in arr:
        row_arr = []
        for val in row:
            if val:
                row_arr.append(1.0/val)
            else:
                row_arr.append(val)
        new_arr.append(row_arr)
    return new_arr
于 2013-10-30T17:06:50.773 回答
0

数组有一个 0 值,在 [0,1] 位置......所以在

1/ arr[i][j] 程序执行:1/0,并且抛出异常。

你必须考虑这种情况做这样的事情:

if arr[i][j]==0:
    ...
else:
    row_arr.append(1/ arr[i][j])
于 2013-10-30T17:12:29.983 回答