简体   繁体   中英

How to check if the input is within the first column of the matrix

I have created a matrix called rix .

rix = [[1,2,3],[4,5,6][7,8,9]]

And as an input I have variable put which is a single list of length 2 which represents the position of the matrix. The part that I'm struggling in, is how do I check that the variable put represents one of the positions in the first column?

Design your function to be generic; it should take the argument row_n ( row number ) that represents which row you want to check its bounds. Check if the row_n exists in your rix 's list. Then, do a comparison between your put 's second element ( that represents the expected row length ) with the original row_n length in the rix list.

According to your case, you should compare if the put 's second element is less than or equal to the rix 's row_n length and then return your booleans.

You use len(rix) to evaluate the number of rows and len(rix[0]) to evaluate the number of columns your matrix has

so

if len(rix) <= put[0]:
    return false
elif len(rix[0]) <= put[1]:
    return false
else:
    return true

You also have to consider negative indices.

def in_first_col(put, list2D):
    row_idx, col_idx = put

    # return False if we can't get the row
    try:
       row = list2D[row_idx]
    except IndexError:
       return False

    # return False if row is empty
    # return False if col_idx does not refer to first element of row
    return row and (col_idx == 0 or col_idx == -len(row))

Demo:

>>> rix = [[1,2,3],[4,5,6],[7,8,9]]
>>> in_first_col([1,1], rix)
>>> False
>>> in_first_col([2,0], rix)
>>> True
>>> in_first_col([5,0], rix)
>>> False
>>> in_first_col([-2,-3], rix)
>>> True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM