Skip to content
Advertisement

How to make recursive function hold it’s original parameter value?

I’m trying to write a function that calculates the determinant of a square matrix using recursion.

The parameter of the oldest function – the first one called – changes to the matrix returned by scale_down() and I don’t know why.

def la_place(matrix):
    if len(matrix) == 2:
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]

    g = -1
    det = 0
    for i in range(len(matrix)):
        g *= -1
        var = scale_down(matrix, i)
        det += g*matrix[0][i]*la_place(var)
    return det


def scale_down(matrix, i):
    var = matrix
    if len(var) > 2:
        var.pop(0)
        for x in range(len(var)):
            var[x].pop(i)
    return var



a =      [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]
print(la_place(a))

I tried substituting “matrix” with “var” in order not to use it directly, but it amounted to nothing.

The code would work fine, I think, if after every for loop iteration in the oldest la_place call, the parameter “matrix” would still equal the original 3×3 matrix. That was my original idea.

Advertisement

Answer

I figured it out. It turns out that var = matrix does not make var independent of matrix. I imported the “copy” library and used var = copy.deepcopy(matrix) to make var independent of matrix. Here is the solution:

import copy


def la_place(matrix):
    var = copy.deepcopy(matrix)
    if len(var) == 2:
        return var[0][0] * var[1][1] - var[0][1] * var[1][0]

    g = -1
    det = 0

    for i in range(len(var)):
        g *= -1
        det += g * matrix[0][i] * la_place(scale_down(var, i))
    return det


def scale_down(matrix, i):
    var = copy.deepcopy(matrix)
    if len(var) > 2:
        var.pop(0)
        for x in range(len(var)):
            var[x].pop(i)
    return var


a = [[9, 4, 2, 1, 1, 7],
     [1, 3, 2, 2, 2, 5],
     [9, 9, 9, 3, 3, 6],
     [9, 9, 9, 4, 5, 7],
     [1, 2, 3, 5, 4, 5],
     [2, 6, 7, 9, 4, 1]]
print(la_place(a))

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement