Leibniz determinant formula complexity

[亡魂溺海] 提交于 2021-01-28 00:31:12

问题


I wrote some code that calculates the determinant of a given nxn matrix using Leibniz formula for determinants.

I am trying to figure out it's complexity in O-notation. I think it should be something like: O(n!) * O(n^2) + O(n) = O(n!*n^2) or O((n+2)!) Reasoning: I think O(n!) is the complexity of permutations. and O(n) the complexity of perm_parity, and O(n^2) is the multiplication of n items each iteration.

this is my code:

def determinant_leibnitz(self):
    assert self.dim()[0] == self.dim()[1] # O(1)
    dim = self.dim()[0] # O(1)
    det,mul = 0,1 # O(1)
    for perm in permutations([num for num in range(dim)]):
        for i in range(dim):
            mul *= self[i,perm[i]] # O(1)
        det += perm_parity(perm)*mul # O(n) ?
        mul = 1 # O(1)
    return det

The following functions that I wrote are also used in the calculation:

perm_parity: Given a permutation of the digits 0..n in order as a list, returns its parity (or sign): +1 for even parity; -1 for odd.

I think perm_parity should run at O(n^2) (is that correct?).

def perm_parity(lst):
    parity = 1
    lst = lst[:]
    for i in range(0,len(lst) - 1):
        if lst[i] != i:
            parity *= -1
            mn = argmin(lst[i:]) + i
            lst[i],lst[mn] = lst[mn],lst[i]
    return parity 

argmin: returns the index of minimal argument in a list. I think that argmin should run at O(n) (is that correct?)

def argmin(lst):
    return lst.index(min(lst))

and permutation: returns all the permutations of a given list. e.g: input: [1,2,3], output [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]].

I think that permutations should run at O(n!) (is that correct?)

def permutations(lst):
    if len(lst) <= 1:
        return [lst]
    templst = []
    for i in range(len(lst)):
        part = lst[:i] + lst[i+1:]
        for j in permutations(part):
            templst.append(lst[i:i+1] + j)
    return templst

回答1:


This is an old question but still deserves an answer.

The complexity you are looking for is O((n+2)!).
This is since O(n!) is the complexity of this:
for perm in permutations([num for num in range(dim)])
O(n) the complexity of theperm_parity function.
O(n^2) is the complexity of multiplying n items in each iteration.
This all gives O(n!)*O(n)*O(n^2)=O(n!n^2)=O((n+2)!)

(And as the comment stated, in your case you also even get ϴ((n+2)!))



来源:https://stackoverflow.com/questions/16527834/leibniz-determinant-formula-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!