Skip to content Skip to sidebar Skip to footer

Making Sure Length Of Matrix Row Is All The Same (python3)

so I have this python 3 code to input a matrix: matrix = [] lop=True while lop: line = input() if not line: lop=False if matrix != []: if len(line.split

Solution 1:

If you want match the first row length, Try this way,

Use len(matrix[0])

for row in matrix:
    iflen(row) == len(matrix[0]):
        passelse:
       print('not same lenght')

Solution 2:

Use the builtin len() function and a break statement.

matrix = []
lop =Truewhile lop:
    line = input('Enter your line: ')
    ifnot line:
        lop=Falseif matrix != []:
        iflen(line.split()) != len(matrix[-1]):
            print("Not same length")
            break
    values = line.split()
    row = [int(value) for value in values]
    matrix.append(row)

This runs as:

bash-3.2$python3matrix.pyEnter your line:123Enter your line:456Enter your line:7890Notsamelengthbash-3.2$

Solution 3:

len(set(map(len,matrix))) == 1

Explanation:

map(len,matrix) yields the lengths of all the rows of the matrix

set(...) gives all unique / different lengths of the rows that exist.

  • If all rows have the same length, this will be a set with 1 single element.
  • Otherwise, it will have 2 or more.

Finally, len(...) == 1 returns whether what we obtained above contains 1 single element i.e. whether all rows have the same length.

Post a Comment for "Making Sure Length Of Matrix Row Is All The Same (python3)"