0

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...

UltraInstinct
44.6k12 gold badges86 silver badges108 bronze badges
asked Sep 27, 2016 at 17:51

2 Answers 2

1

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)]
answered Sep 27, 2016 at 18:06
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, Harshit. Are there a way to control the length of line with input method
@Murad I'm not sure if there is a way to limit the length of a user input, as it's basically an interrupt that occurs and the program waits until the user is done typing before running anything else (on that thread/process of course). What Harshit has done with [: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.
0

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.

answered Jan 3, 2024 at 22:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.