Search code examples
pythonpython-2.7optimizationcvxopt

how to get truth value in for loop with if statement


I am unable to get the correct value for the conditional if statement nested with for loop.Here is an example written in code,

# Input data
d11 = np.matrix([[3,6,1],[6,8,1],[1,1,1],[5,8,9]])
qp1 = np.matrix([[1],[3],[5]])
h1 = np.matrix([[5],[40],[100],[5]])

I need that row of d11 matrix whose value on multiplying with qp1 is less than the corresponding value in h1 i.e d11[i] * qp < h[i].The code for this is,

for x in range(len(d11)):
    if d11[x] * qp1 < h1[x]:
        a = d11[x]
    else:
        a = []

when we multipy d11 and qp1 we get the values as [26,35 , 9 ,22].Thus if we compare with h1, we find the condition is True for 2nd row i.e 35< 40 and 3rd row i.e9 < 100 .So the answer is [[6,8,1],[1,1,1]].But i am unable to get the answer.Please suggest me the correct way..


Solution

  • Your if statement is checking whether or not the list created by the list comprehension
    [aa[i] > 10 for i in range(len(a))] (ie the list [False, False, False, False]) is empty.

    Since it is not empty the if statement is evaluated to True.

    Instead, consider using any:

    aa = [1, 4, 5, 6]
    if any(num > 10 for num in aa):
        c = aa[i],'t'  # as (correctly) pointed out in the comments below,
                       # i is not defined here since we are no longer using an index
                       # to iterate over the list's elements.
                       # You'll need to decide what you want to do in case an element
                       # IS larger than 10.
    else:
        c = 0
    

    Your code has another bug: by the time the list comprehension is done, i will always be the last index.