Given rectangular array (matrix) MxN with integer elements. M & N are the number of rows and columns of the rectangular matrix, received from input in one line separated by speces. Next, N lines with M numbers each, separated by a space – the elements of the matrix, integers, not exceeding 100 by absolute value.
For example:
Sample Input:
2 3
1 -2 3
4 5 6
Sample Output:
[[1, -2, 3], [4, 5, 6]]
Code:
cols, rows = [int(i) for i in input().split(" ")]
l = [[list(map(int, input()))] for j in range(rows)]
With rows its clear, however, I dont know how to control line length, so it be equal to the number, receved from input as cols
Any hints will be appreciated...
2 Answers 2
First of all based on sample output, I saw that rows and cols should be interchanged and second use split by cols [:cols] as shown in the code below
rows, cols = [int(i) for i in input().split(" ")]
l = [map(int, input().split(" ")[:cols]) for i in range(rows)]
2 Comments
[:cols] is it will cap to the first cols number of integers inputted and will ignore all the rest the user has typed in, so you will result in exactly a row x cols matrix.Well you can try taking input with a loop and breaking it when you receive empty string in python3.
lis = []
val = [map(int, input().split(" ")]
lis.append(val)
while val != "":
val = [map(int, input().split(" ")]
lis.append(val)
There you have it. A matrix without predefined rows and columns.
Comments
Explore related questions
See similar questions with these tags.