I'm solving a matrix problem in Python3 where the input is of the form:
110
001
110
The following code:
for i in range(0,n):
mat.append([int(j) for j in input().strip().split()])
print(mat)
works if the input is of the form:
1 1 0
0 0 1
1 1 0
What modifications should be done for taking input in the required format (no spaces)?
CodePudding user response:
You can do just this:
for i in range(0,n):
mat.append([int(j) for j in input().strip()])
print(mat)
string.split(par)
splits string into a list based on the parameter given and if there is nothing mentioned, it splits using whitespace as parameter. Now, in your case '110' doesn't have whitespace so split()
won't work as you are expecting. Also, your input is a string, so directly indexing it would do the the job for you.
CodePudding user response:
In that case, what I would do:
input = "110\n001\n110".split("\n") # Simply reproducing your input here
mat = [[int(j) for j in line.strip()] for line in input]
print(mat)
CodePudding user response:
To deal with matrices, the best option usually is to use a library such as numpy
, which allows you to easily manipulate and handle matrices.
If you want to deal with pure python instead without any imports, you would want to replace the .strip()
to a .replace()
, such as:
for i in range(0,n):
mat.append([int(j) for j in input().replace(" ","").split("\n")[n]])
Ofcourse, that is assuming you have your string in the correct structure with new lines.