How can i print matrix[i][j] in python? - python

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])

Related

Rearrange the rows of the given matrix so that arrange them in descending order of the sum of their negative pairs

The task was to rearrange the rows of a given matrix in the created matrix so that
arrange them in descending order of the sum of their negative pairs (as i mentioned in the title)
Here is what i tried:
import numpy as np
import random
rows = int(input('\nInput the number of rows: '))
cols = int(input('Input the number of cols: '))
def AutoFill(rows, cols):
rand_arr = []
for k in range(rows):
arr = []
for v in range(cols):
a = random.randint(-5, 5)
arr.append(a)
rand_arr.append(np.array(arr))
return np.array(rand_arr)
arr = AutoFill(rows, cols)
PrintArr(arr)
def Rearrange(arr, rows, cols):
sum = 0
for i in range(0, rows+1):
if (arr[i] < 0) and (arr[i] % 2 == 0):
sum += arr[i]
When i tried to run i've got an error:
if (arr[i] < 0) and (arr[i] % 2 == 0):
ValueError: The truth value of an array with more than one element is ambiguous. Use
a.any() or a.all()
I'll be very grateful for your help
Update: larger test case: 4x4 matrix
If I understand the proglem, this code should andwer your question:
import numpy as np
import random
def AutoFill(rows, cols):
rand_arr = []
for k in range(rows):
arr = []
for v in range(cols):
a = random.randint(-5, 5)
arr.append(a)
rand_arr.append(np.array(arr))
return np.array(rand_arr)
def reducer(row):
# Return the value calculated as pwe the "negative pairs" specification
total = 0
for i in range(len(row)):
if i%2 == 0 and row[i] < 0:
total += row[i]
return -total # NOTE the negative sign. It contols the row order.
def Rearrange(arr):
# Return the array sorted by the desired "value" of each row.
return np.array(sorted(arr, key=lambda row: reducer(row)))
#rows = int(input('\nInput the number of rows: '))
#cols = int(input('Input the number of cols: '))
# So that we get repeatable results
random.seed(2)
rows = 4
cols = 4
arr = AutoFill(rows, cols)
print(arr)
print(Rearrange(arr))
Output:
[[-5 -4 -4 0]
[-3 5 -1 -1]
[ 4 -2 4 -5]
[ 4 5 -3 1]]
[[-5 -4 -4 0]
[-3 5 -1 -1]
[ 4 5 -3 1]
[ 4 -2 4 -5]]

python program for printing boundary elements of matrix

My code :
R = int(input("Enter the Size of Square Matrix : "))
matrix = []
print("\nEnter the entries row-wise : ")
for i in range(R):
a = []
for j in range(R):
a.append(int(input()))
matrix.append(a)
print("\nMatrix : \n")
for i in range(R):
for j in range(R):
print(matrix[i][j], end=" ")
print()
print("\n")
print("\nBoundary Matrix\n")
for i in range(R):
for j in range(R):
if (i == 0):
print(matrix[i][j])
elif (i == R - 1):
print(matrix[i][j])
elif (j == 0):
print(matrix[i][j])
elif (j == R - 1):
print(matrix[i][j])
else:
print(" "),
print()
output :
Boundary
Matrix
1
2
3
4
6
7
8
9
I'm not able to print the boundary elements in form of a matrix. the output is in form of a straight line.
Please help me to do so.
Note: I have tried changing the position of print() but that didn't help much.
print("\nBoundary Matrix\n")
for i in range(R):
print(
"{}{}{}".format(
"\t".join(map(str, matrix[i])) if i in (0, R - 1) else matrix[i][0],
"" if i in (0, R - 1) else (" \t" * (R - 1)),
"" if i in (0, R - 1) else matrix[i][R - 1],
)
)
Matrix :
1 2 3 4
5 6 7 8
9 10 11 12
13 1 4 15
Boundary Matrix
1 2 3 4
5 8
9 12
13 1 4 15

Convert Matrix to lower triangular without using numpy

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()

How to input element in 2d array

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)

Creating a "snake" counter

I'm just trying to get the logic straight and using Python to help me do it. Ultimately, I need to solve this problem using ImageJ macro language.
I have no idea if I'm using the right term, but I'd like to create a "snake" counter.
x = 1
number = 12
maxVal = 3
minVal = 1
for i in xrange(number):
%do something
x = incrementSnakeCounter(x, maxVal, minVal)
print("i = ", i)
print("x = ", x)
The "snake" part is making the counter go up only to the maxVal, repeating that number on the next iteration, counting down to the minVal, repeating that value on the next iteration, and repeating the process.
For instance, in the above
I'd like the following to happen :
i = 0
x = 1
i = 1
x = 2
i = 2
x = 3
i = 3
x = 3
i = 4
x = 2
i = 5
x = 1
i = 6
x = 1
i = 7
x = 2
i = 8
x = 3
i = 9
x = 3
i = 10
x = 2
i = 11
x = 1
You will find some useful utils in itertools:
from itertools import chain, cycle
def snake(lower, upper):
return cycle(chain(range(lower, upper+1), range(upper, lower-1, -1)))
> s = snake(1,3)
> [next(s) for _ in range(10)]
[1, 2, 3, 3, 2, 1, 1, 2, 3, 3]
Here's a silly mathematical solution:
def snake(low, high, x):
k = (high-low+1)
return k - int(abs(x % (2*k) + low - k - 0.5))
[snake.snake(1,3,x) for x in range(8)]
[1, 2, 3, 3, 2, 1, 1, 2]
Add a conditional to determine if x should be increasing or decreasing at any given point within the loop.
x = 1
number = 12
maxVal = 3
minVal = 1
for i in xrange(number):
%do something
if(xIsIncreasing)
x = incrementSnakeCounter(x, maxVal, minVal)
else
x = decrementSnakeCounter(x, maxVal, minVal)
print("i = ", i)
print("x = ", x)
Then inside your incrementSnakeCounter() change the value of xIsIncreasing to false when x == maxVal and inside your decrementSnakeCounter() to true when x == minVal (you'll have to do some work to make sure that you're staying at the same value twice in a row, I don't have time right now to solve that part for you).
You can write a little custom generator.
The key is to create a list of the pattern you want to repeat [1, 2, 3, 3, 2, 1] and then index that with the modulo of the length to get the repeating behavior:
def snake(x, max_v=3, min_v=1):
cnt=0
sn=list(range(min_v, max_v+1,1))+list(range(max_v, min_v-1,-1))
while cnt<x:
yield cnt, sn[cnt%len(sn)]
cnt+=1
Then:
for i,x in snake(12):
print("i=",i)
print("x=",x)
print()
Prints:
i= 0
x= 1
i= 1
x= 2
i= 2
x= 3
i= 3
x= 3
i= 4
x= 2
i= 5
x= 1
i= 6
x= 1
i= 7
x= 2
i= 8
x= 3
i= 9
x= 3
i= 10
x= 2
i= 11
x= 1

Categories