Like below C++ Code, how could I use Python to input elements in 2d array? Please, help in writing the same program in Python3.
int main()
{
int s = 3;
int a[s][s];
cout<<"Enter 9 Element in Square Matrix";
for(int i =0;i<s;i++)
{
for(int j =0; j<s;j++)
{
cin>>a[i][j];
}
}
cout<<"You Entered";
for(int i =0;i<s;i++)
{
for(int j =0; j<s;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
return 0;
}
Output:
Enter 9 Elements in Square Matrix
1
2
3
4
5
6
7
8
9
You Entered:
1 2 3
4 5 6
7 8 9
If there is a mistake in the program, please don't try to correct it.
Thank you.
Am gonna use list to store the 2D array here. There are many other structures you can use for storing a 2D array, but for basic needs, this will suffice.
n=int(input("Enter N for N x N matrix : ")) #3 here
l=[] #use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
for i in range(n):
row_list=[] #temporary list to store the row
for j in range(n):
row_list.append(int(input())) #add the input to row list
l.append(row_list) #add the row to the list
print(l)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
for i in range(n):
for j in range(n):
print(l[i][j], end=" ")
print() #new line
'''
1 2 3
4 5 6
7 8 9
'''
s = 3
a = [x[:] for x in [[0] * s] * s]
print("Enter 9 Element in Square Matrix")
for i in range(0, s):
for j in range(0, s):
a[i][j] = input()
print("You Entered")
for i in range(0, s):
line = ''
for j in range(0, s):
line += a[i][j] + ' '
print(line)
If you are not familiar with python, you should create a file called, for example, matrix.py and then add the following content:
matrix_size = 3
matrix = []
print("Enter {} Elements in Square Matrix:".format(matrix_size))
for i in range(0, matrix_size):
row = []
for j in range(0, matrix_size):
row.append(input())
matrix.append(row)
print("You entered:")
for i in range(0, matrix_size):
print(" ".join(matrix[i]))
After saving the file, you can execute this file this way:
python3 matrix.py
Here is a sample output:
[martin#M7 tmp]$ python3 matrix.py
Enter 3 Elements in Square Matrix:
1
2
3
1
2
3
7
5
4
You entered:
1 2 3
1 2 3
7 5 4
Say you want to create a 3*3 matrix:
Initialize the matrix as follows:
matrix = [x[:] for x in [[0] * 0] * 0]
Then take the matrix elements as input from the user:
for i in range(0,3):
row_list = []
for j in range(0,3):
row_list.append(int(input()))
matrix.append(row_list)
Related
how can i print the matrix[i][j]?
from array import *
class Sudoku :
matrix = []
x = -1
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a)
except:
matrix.append(x)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])
error is :
print(matrix[i][j])
TypeError: 'int' object is not subscriptable
You can use this code if you want to complete the code with minimum number of lines but it sure is a bit complex.
m,n=input("Enter num of rows and columns:").split()
matrix=[[int(input()) for y in range(int(n))]for x in range(int(m))]
[[[print(matrix[i][j], end=" ") for j in range(int(n))] and print(" ") ]for i in range(int(m))]
The output looks like this:
Enter num of rows and columns: 3 3
1
2
3
4
5
6
7
8
9
1 2 3
4 5 6
7 8 9
from array import *
class Sudoku:
matrix = []
x = -1 # <--- 4
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a) # <--- 11
except: # <--- 12
matrix.append(x) # <--- 13
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j]) # <--- 16
Let's look at the code. If except at L12 is catched, x, which is -1 (L4) is appended. So at L16, when matrix[i] evaluates to -1, -1[j] is an error.
There's also another problem -- L11 will never be executed, because a is always a list, not int.
matrix = [] is declaring matrix to be a list. But you are thinking of the matrix as having i,j locations like in math.
You have two options:
Option1: Map the list to a matrix
If you have a 3x3 matrix you have 9 locations, so
matrix = [0, 1, 2, 3, 4, 5, 6, 7, 8] is equivalent to
0 1 2
matrix = 3 4 5
6 7 8
so if wanted to print out this matrix you have to do some math to access the elements
for i in range(3): # i = 0, 1, 2
for j in range(3): # j = 0, 1, 2
print(matrix[3*i + j], end=" ")
print("")
Option2: Make matrix be a nested list
have matrix becomes a list of row, and each row is a list of elements
matrix = []
x = -1
for i in range(0, 10):
row = []
for j in range(0, 10):
while True:
x = int(input(f"Enter matrix[{i}][{j}]} element: "))
if (isinstance(x, int)) == True :
row.append(x)
break;
matrix.append(row)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])
My code had converted the matrix to lower Triangular Matrix but I need to eliminate the space after the last element in a row. My code is
matrix = [
[2, 9, 9],
[5, 6, 9],
[7, 6, 5]
]
n = len(matrix)
for i in range(n):
for j in range(n):
if(i<j):
print("0",end=" ")
else:
print(matrix[i][j],end=" ")
if(i!=n-1):
print()
Outut:
Expected Output Actual Output
2 0 0\n 2 0 0 \n
5 6 0\n 5 6 0 \n
7 6 5 7 6 5
Replace your inner loop with an expression that builds the row you want. You can combine the loop body into a single line, if you like.
for i in range(n):
row = ' '.join(str(matrix[i][j]) if i >= j else "0"
for j in range(n))
Note that this removes the need for your final if/print.
n=int(input())
matrix=[]
for k in range(n):
lst=list(map(int,input().split()))
matrix.append(lst)
for i in range(n):
for j in range(n):
if(i
else:
if(j==(n-1)):
print(matrix[i][j],end='')
else:
print(matrix[i][j],end=" ")
if(i!=n-1):
print()
n=int(input())
matrix=[]
for k in range(n):
lst=list(map(int,input().split()))
matrix.append(lst)
for i in range(n):
for j in range(n):
if(i<j):
if(j==(n-1)):
print("0",end='')
else:
print("0",end=" ")
else:
if(j==(n-1)):
print(matrix[i][j],end='')
else:
print(matrix[i][j],end=" ")
if(i!=n-1):
print()
I have the following code which has to print out a board with numbers according to the size the user specified (for instance 3 means a 3 x 3 board):
n = d * d
count = 1
board = []
for i in range(d):
for j in range(d):
number = n - count
if number >= 0 :
tile = number
board.append[tile]
else:
exit(1)
count += 1
print(board)
I need to get this in a grid, so that the board is 3 x 3 in size ike this:
8 7 6
5 4 3
2 1 0
What I tried to do is to get each row in a list (so [8 7 6] [5 4.. etc) and then print those lists in a grid. In order to do that, I guess I would have to create an empty list and then add the numbers to that list, stopping after every d, so that each list is the specified length.
I now have a list of the numbers I want, but how do I seperate them into a grid?
I would really appreciate any help!
Here a function that takes the square size and print it.
If you need explanation don't hesitate to ask.
def my_print_square(d):
all_ = d * d
x = list(range(all_))
x.sort(reverse=True) # the x value is a list with all value sorted reverse.
i=0
while i < all_:
print(" ".join(map(str, x[i:i+d])))
i += d
my_print_square(5)
24 23 22 21 20
19 18 17 16 15
14 13 12 11 10
9 8 7 6 5
4 3 2 1 0
By default the print() function adds "\n" to the end of the string you want to print. You can override this by passing in the end argument.
print(string, end=" ")
In this case we are adding a space instead of a line break.
And then we have to print the linebreaks manually with print() at the end of each row.
n = d * d
count = 1
max_len = len(str(n-1))
form = "%" + str(max_len) + "d"
for i in range(d):
for j in range(d):
number = n - count
if number >= 0 :
tile = number
else:
exit(1)
count += 1
print(form%(tile), end=" ")
print()
EDIT: by figuring out the maximum length of the numbers we can adjust the format in which they're printed. This should support any size of board.
You can create the board as a nested list, where each list is a row in the board. Then concatenate them at the end:
def get_board(n):
# get the numbers
numbers = [i for i in range(n * n)]
# create the nested list representing the board
rev_board = [numbers[i:i+n][::-1] for i in range(0, len(numbers), n)]
return rev_board
board = get_board(3)
# print each list(row) of the board, from end to start
print('\n'.join(' '.join(str(x) for x in row) for row in reversed(board)))
Which outputs:
8 7 6
5 4 3
2 1 0
If you want to align the numbers for 4 or 5 sized grids, just use a %d format specifier:
board = get_board(4)
for line in reversed(board):
for number in line:
print("%2d" % number, end = " ")
print()
Which gives an aligned grid:
15 14 13 12
11 10 9 8
7 6 5 4
3 2 1 0
How to insert value to matrix by user input?
I've got some code like this.
n,m = raw_input().split(' ')
matrix = [[0 for x in range(int(n))] for y in range(int(m))]
How it should looks like:
user input :
2 2 #dementions of matrix
1 2 #matrix[1][1] = 1; #matrix[2][1] = 2
3 4 #matrix[2][1] = 3; #matrix[2][2] = 4
output :
1 2 #matrix[1][1] = 1; #matrix[2][1] = 2
3 4 #matrix[2][1] = 3; #matrix[2][2] = 4
Here is the code for taking matrix input in python:
n,m=map(int,raw_input().split())
a=n*[m*[0]]
j=0
for i in range (0,n):
a[i][j]=map(int,raw_input().split())
j+=1
j=0
for i in range (0,n):
print a[i][j]
j+=1
I need to read k matrices size nxm from stdin in Python.
In the first line there must be the number of matrices (k), and then - k descriptions of matrices: in the first line 2 integer numbers for size (n and m) devided by space, then the matrix.
Here's an example:
2
2 3
4 5 6
3 1 7
4 4
5 3 4 5
6 5 1 4
3 9 1 4
8 5 4 3
Could you please tell me how I can do this?
I could have done this only without considering m (for 1 matrix):
n = int(input())
a = []
for i in range(n):
a.append([int(j) for j in input().split()])
I have found some similar questions but stdin is not used (e.g. reading from file is used) or the size of string in matrix is not set.
You are on a right way. try to break it in simple steps. Basically a n X m matrix is n rows and each row would have m elements (pretty obvious). what if we have n=1 then we have a line in which there would be m element. to take such input we would just
matrix = input().split() #read the input
matrix = [ int(j) for j in matrix] #matrix is now 1 x m list
or simplify this
matrix = [ int(j) for j in input().split() ]
now suppose we have n rows, that means we have to do this n times which is simply looping n times ,
matrix = [ [ int(j) for j in input().split() ] for i in n ]
a more pythonic way is using map,
matrix= [ list( map(int, input().split() ) ) for i in range(n) ]