Ask Your Question

all final(optimal) values of for loop

asked 2017-03-08 08:20:07 +0200

Deepak Sarma gravatar image

updated 2017-03-08 21:48:01 +0200

I have written a program to check which matrices in a given class maximizes the determinant. But my program gives me only one such matrix, I need all those matrices which attains the maximum determinant.

 def xyz(n):
    for a in myfunction(n):
            if a.det()>m:
    print  A
edit retag flag offensive close merge delete

3 Answers

Sort by ยป oldest newest most voted

answered 2017-03-08 22:00:50 +0200

tmonteil gravatar image

updated 2017-03-08 22:07:58 +0200

Instead of storing the best matrix in a variable a, you can store all best matrices in a list (or a set), and flush the list when a better matrix is found (and update the value of the best determinant). It will look something like:

def xyz(n):
    L = []
    max_det = -infinity
    for A in myfunction(n):
            d = A.det()
            if d == max_det:
            elif d > max_det:
                L = [A]
                max_det = d
    return L

Also let me suggest you to read about the difference between print and return.

edit flag offensive delete link more


We must have answered this at the same time.

John Palmieri gravatar imageJohn Palmieri ( 2017-03-09 01:19:11 +0200 )edit

answered 2017-03-08 08:31:19 +0200

Deepak Sarma gravatar image

updated 2017-03-08 21:48:08 +0200

I have solved the problem with the following modification. But comparatively this takes a lot of time for larger $n$ as the same loop runs twice. Can we do it by running the loop only once?

def xyz(n):
    m=max([a.det() for a in myfunction(n)])
    for A in myfunction(n):
        if A.det()==m:
            print A
edit flag offensive delete link more

answered 2017-03-08 21:52:55 +0200

How about something like this:

def xyz(n):
    m = -Infinity # or some number that you know is less than the max
    matrices = []  # list of matrices with max determinant
    for A in myfunction(n):
        d = A.det()
        if d > m:
            matrices = [A]
            m = d
        elif d == m:
    return matrices
edit flag offensive delete link more


Thank you.

Deepak Sarma gravatar imageDeepak Sarma ( 2017-03-10 06:31:48 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2017-03-08 08:20:07 +0200

Seen: 429 times

Last updated: Mar 08 '17