定义python函数

时间:2018-03-14 13:52:04

标签: python function matrix

我试图定义一个函数,该函数将计算将字符串转换为另一个字符串所需的最小步骤数(以及步骤类型)。我有以下内容:

def cost(matrix[i][j]):

    a = matrix[i-1][j][0]+1

    b = matrix[i][j-1][0]+1

    if a[i] = b[i]:
        c = matrix[i-1][j-1][0]
    else:
        c = matrix[i-1][j-1][0] +1

    cost0 = min(a, b, c)
    if cost0 = a:
        cost1 = Operation.DELETED
    elif cost0 = b:
        cost1 = Operation.INSERTED
    else:
        cost1 = Operation.SUBSTITUTED

    return (cost0, cost1)

作为我的程序的一部分,其中a,b和c是整数,但是当我运行它时,它会抛出一个无效的语法错误,如下所示:

line 23
    def cost(matrix[i][j]):
                   ^
SyntaxError: invalid syntax

它会是什么?

1 个答案:

答案 0 :(得分:1)

定义函数时,不指定数组的尺寸,省略它们。因为变量是通过引用传递的,所以数组维度将自动传递

def cost(matrix):

    a = matrix[i-1][j][0]+1

    b = matrix[i][j-1][0]+1

    if a[i] = b[i]:
        c = matrix[i-1][j-1][0]
    else:
        c = matrix[i-1][j-1][0] +1

    cost0 = min(a, b, c)
    if cost0 = a:
        cost1 = Operation.DELETED
    elif cost0 = b:
        cost1 = Operation.INSERTED
    else:
        cost1 = Operation.SUBSTITUTED

    return (cost0, cost1)