I am trying to transpose the matrix but getting the same matrix, this seems to be happening everytime and what is more confusing is that the element of list are swapped but not on this instance.
What is problematic is that I see no change in the end result as the swapping was made for nXn times in the loop.
inp = int(input())
mat = []
for i in range(inp):
submat = list(map(int,input().split(',')))
mat.append(submat)
print(mat)
for i in range(len(mat)):
for j in range(len(mat[0])):
mat[i][j],mat[j][i] = mat[j][i],mat[i][j]
print(mat)
You need to loop in upper triangular matrix only ie from 0,1...len(mat) row wise and row+1, row+2, row+3..len(mat[0]) column wise
# your code goes here
inp = int(input())
mat = []
for i in range(inp):
submat = list(map(int,input().split(',')))
mat.append(submat)
print(mat)
for i in range(len(mat)):
for j in range(i+1, len(mat[0])):
mat[i][j],mat[j][i] = mat[j][i],mat[i][j]
Of course, you are swapping every i, j twice (i, j and later j, i).
Related
I am trying to create a 16x16 identity matrix in python by using nested for loops.
import numpy as np
total = []
for i in range(1,5):
for j in range(1,5):
row = 16*[0]
total.append(row)
mat = np.matrix(total)
How do I modify this to get an identity matrix? The ranges cannot be changed.
You can follow this. It is done here simply. Note that there are many ways to do this. You can also follow the second way I uploaded below.
import numpy as np
total =[]
for i in range(1,17):
row=[]
for j in range(1,17):
if i==j:
row.append(1)
else:
row.append(0)
total.append(row)
mat = np.array(total)
Alternative way:
matrix = np.asmatrix(np.eye(16), dtype=int)
Actually it is much easier to create your matrix as:
mat = np.asmatrix(np.eye(16), dtype=int)
But if you insist on usage of 2 nested loops, with ranges (1, 5),
you can do it as follows:
total = []
row = [1] + [0] * 15
for _ in range(1,5):
for _ in range(1,5):
total.append(row)
row = np.roll(row, 1).tolist()
mat = np.matrix(total)
Note that each loop is executed actually 4 times, so the total number
of executions is just 16.
Even i and j, which you used in your code, are not needed
(they are never used), so I put _ instead of them.
Question- Given an m x n matrix of 0s and 1s, if an element is 0, set its entire row and column to 0. Do it in place.
def value(arr):
lk=[]
ll=[]
for i in range(m):
for j in range(n):
if(arr[i][j]==0):
lk.append(i)
ll.append(j)
for ele in lk:
for j in range(n):
arr[ele][j]=0
for ele in ll:
for i in range(m):
arr[i][ele]=0
for i in range(m):
for j in range(n):
print(arr[i][j],end=' ')
print()
str=input().split()
m,n=int(str[0]),int(str[1])
arr = [[0 for j in range(n)] for i in range(m)]
value(arr)
The question is not explained very well since you haven't told what is the test case is. But it's okay since you are new to StackOverflow.
After some googling, I found this was a question in leetcode. The first thing, the code works but it is very slow. In competitive programming like leetcode, you should write a very optimized code which can solve the problem in the least amount of time.
def setZeroes(matrix):
R = len(matrix)
C = len(matrix[0])
rows, cols = set(), set()
# Essentially, we mark the rows and columns that are to be made zero
for i in range(R):
for j in range(C):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
# Iterate over the array once again and using the rows and cols sets, update the elements
for i in range(R):
for j in range(C):
if i in rows or j in cols:
matrix[i][j] = 0
As you can see this both your and proposed answer has nested loops. But the proposed answer has only two loops while your answer has 4 loops.
I hope you can understand why your code works but inefficient.
I want to improve a code where I have to sum over different indices. This is the code:
neighbors = [[1,2,4],[2,0],[1,3],[],[0]]
omega = np.random((5,5,3,3))
#Sum over indices 0 (filtered) and 2
suma = np.zeros((5,3))
for j in range(5):
for l in range(3):
suma[j,l] += np.sum(omega[neighbors[j],j,:,l])
Now I improved a little bit my code using the axis parameter of sum:
suma2 = np.zeros((5,3))
for j in range(5):
suma2[j,:] += np.sum(omega[neighbors[j],j,:,:],axis=(0,1))
I want to know how I can avoid the first loop. I tried creating an array of booleans:
neighbors_bool = np.full((5,5),False,dtype=bool)
for j in range(5):
neighbors_bool[neighbors[j],j] = True
But I don't know how to put it in the sum.
I am trying to find the sum of neighbors around an element in a matrix and wrote few functions to convert a boolean matrix to 1s and 0s and finding the neighbors. But I'm not sure why it is throwing the following error
matrix=[[True,False,False],[False,True,False],[False,False,False]]
def minesweeper(matrix):
matrix=[[1 if j==True else 0 for j in i] for i in matrix]
bin_mt = matrix.copy()
print(bin_mt)
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j]=get_neighbors(i,j,matrix, bin_mt)
print('matrix: '+str(matrix))
print('bin_mt: '+str(bin_mt))
print(matrix)
return matrix
def get_neighbors(a, b, matrix, bin_mt):
sum=0
if bin_mt[a][b]==1:
return 1
else:
for i in find_neighbor_indices(matrix,a,b):
print(bin_mt[i[0]][i[1]], end=' ')
sum=sum+bin_mt[i[0]][i[1]]
print('--')
return sum
def find_neighbor_indices(matrix, i, j, dist=1):
neighbors = []
irange = range(max(0,i-dist), min(len(matrix), i+dist+1))
if len(matrix) > 0:
jrange = range(max(0, j - dist), min(len(matrix[ 0 ]), j + dist + 1))
else:
jrange = []
for icheck in irange:
for jcheck in jrange:
if icheck != i or jcheck != j:
neighbors.append((icheck, jcheck))
return neighbors
minesweeper(matrix)
PS: I have updated the code. However I created a matrix containing 1's and 0's for comparision and sum of neighbors. But I'm not sure why it is updating the both bin_mat and actual matrix instead of just actual matrix. Could someone help me with that.
No worries. I figured it out. The issue was binary matrix is a shallow copy of actual matrix. Whatever the changes I was making in actual matrix were getting updated in binary matrix. I needed a deep copy instead of shallow.
Solved it using below code.
import copy
bin_mt = copy.deepcopy(matrix)
instead of
bin_mt = matrix.copy()
I am trying to write a Python statement for performing the following task with a table of m rows and n columns.
I have to fill only the top row and bottom row with zeros.
So far I have:
list = []
for i in range(m):
for j in range(n):
I'm not sure what to do next. How can I access just the first and last row? Thank you!
Code based on your provided information :
list = []
for x in range(0, m):
if x == 0 or x == m:
# your code for filling it with zeros
else:
# your code for "Anything can be in other cells"
You can use:
lst = [[0 if i in (0, m-1) else default_val] * n for i in range(m)]
That roughly does the same as:
lst = [] # do not shadow 'list'
for i in range(m):
lst[i] = []
for j in range(n):
lst[i].append(0 if i in (0, m-1) else default_val)