min() arg is an empty sequence

前端 未结 4 1164
逝去的感伤
逝去的感伤 2021-02-20 07:32

I\'m trying to find minimum element in matrix row, but there are two conditions: 1) it must be > 0 2) and this point must be not visited(is_visited[k] is False) I\'

4条回答
  •  悲&欢浪女
    2021-02-20 07:45

    There is no problem with the syntax. It's certainly unusual to have two if clauses, but it's allowed. Consider:

    print(min(x for x in range(1,300) if x % 3 == 0 if x % 5 == 0))
    

    Output:

    15
    

    However:

    print(min(x for x in range(1,300) if x % 2 != 0 if x % 2 != 1))
    

    Output:

    ValueError: min() arg is an empty sequence
    

    There are no integers that are both odd and even, so there are no values for min to see, so it throws an exception.

    I deduce that in your code, there are no values that pass both conditions. Python doesn't allow you to compute "the minimum of no values", mainly because it makes no sense.

    You have to decide what you want to do in the case where there is no minimum because there are no values greater than 0. For example, if you don't want to return k in that case then I might re-write your code something like this:

    for k in range(4):
        if k != i and is_visited[k] is False:
            if matr_sum[i][k] > 0 and matr_sum[i][k] == min(x for x in matr_sum[i] if x > 0):
                return k
    

    It might not be obvious why this helps, but assuming matr_sum[i] is a list or similar, then once we know matr_sum[i][k] > 0 then we know the generator passed to min isn't empty, so we won't get an exception. Whereas if matr_sum[i][k] <= 0, then it certainly isn't equal to the smallest positive value, so there's no need to compute the min at all. Another way to write that would be:

    if matr_sum[i][k] > 0 and not any(0 < x < matr_sum[i][k] for x in matr_sum[i])
    

    Actually, I'd normally write if not is_visited[k], but I leave it as is False since I don't know whether changing it would change the behaviour of your code.

提交回复
热议问题