Ok, so i know this question has been asked several times before but they all had different errors
so i am a newbie in python and we were given a Algebra practical with python for vector-matrix multpilication
and this was my code but i am getting a specific error everytime which is
list index out of range
line 20 in
d=m[i][j]*v[j]
i don't really understand what is the cause of this error!
please help
Heres my code:
r=int(input("enter rows"))
c=int(input("enter columns"))
m=[]
for i in range(r):
m.append([])
for j in range(c):
e=int(input("enter element"))
m[i].append(e)
for i in range(r):
print(m[i])
vm=input("enter vector [ vector matrix] \n v :")
v=[]
v=[int(x) for x in vm.split()]
print('vector v ',v)
print('Vector-Matrix multiplication:')
for i in range (c):
re=0
for j in range(len(v)):
d=m[i][j]*v[j]
re+=d
print('[',re,']')
um=input("enter vector[ matrix -vector ]\n u :")
u=[]
u=[int(x)for x in um.split()]
print('vector u',u)
print("matrix vector multiplication")
for i in range(r):
res=0
for j in range(len(u)):
c=m[i][j]*u[j]
res+=c
print('[',res,']')
i is indexing the row in d=m[i][j]*v[j], but your loop is over the number of columns. You could eliminate errors like that and make the code cleaner by looping directly over the rows. Instead of for i in range (c): you'd have for row in m: and d=row[j]*v[j]. You should also take advantage of the sum function to do the dot products. Combining these you end up replacing
for i in range (c):
re=0
for j in range(len(v)):
d=m[i][j]*v[j]
re+=d
print('[',re,']')
with
for row in m:
re=sum(row[j] * v[j] for j in range(v)]
print('[',re,']')
If you really need an incrementing index then enumerate is the function that can provide it, for example:
for i, row in enumerate(m):
re=sum(row[j] * v[j] for j in range(v)]
print(f'{i}. [{re}]')
Related
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).
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 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()
PROBLEM :
You are given a list of size N, initialized with zeroes. You have to perform M operations on the list and output the maximum of final values of all the elements in the list. For every operation, you are given three integers a,b and k and you have to add value to all the elements ranging from index a to b(both inclusive).
Input Format
First line will contain two integers N and M separated by a single space.
Next lines will contain three integers a,b and k separated by a single space.
Numbers in list are numbered from 1 to N.
Here is the code which I have written:
n,m=map(int,input().split())
arr=[]
for i in range(n+1):
arr.append(0)
for j in range(m):
a,b,k=map(int,input().split())
for i in range(a,b+1):
arr[i]+=k;
print(max(arr))
When I try to submit my solution I get a "TERMINATED DUE TO TIMOUT" message.Could you please suggest a strategy to avoid these kind of errors and also a solution to the problem.
Thanks in advance!
Don't loop over the list range; instead, use map again to increment the indicated values. Something like
for j in range(m):
a,b,k=map(int,input().split())
arr[a:b+1] = map(lambda <increment-by-k>, arr[a:b+1])
This should let your resident optimization swoop in and save some time.
You probably need an algorithm that has better complexity than O(M*N).
You can put interval delimiters in a list:
n,m=map(int,input().split())
intervals = []
arr = [0 for i in range(n)]
for j in range(m):
a,b,k=map(int,input().split())
intervals += [(str(a), "begin", k)]
intervals += [(str(b), "end", k)]
intervals = sorted(intervals, key=lambda x: x[0]+x[1])
k, i = 0, 0
for op in intervals:
ind = int(op[0])
if op[1] == "begin":
while ind > i:
arr[i] += k
i += 1
k += op[2]
else:
while i <= ind:
arr[i] += k
i+= 1
k -= op[2]
print(arr)
If the sorting algorithm is O(MlogM), this is O(MlogM + N)
I am trying to make a function that makes a matrix whenever called.
Problem1: When I try to make a 2x3 or 3x2 and fill it: IndexError:
list index out of range. Solved by Haminaa
def mtx():
m=int(raw_input("Rows"))
n=int(raw_input("Col"))
a=[[0 for i in range(m)]for j in range(n)]
l=[]
for i in range(m):
for j in range(n):
s=a[i][j]=int(raw_input("Fill"))
l.append(s)
for i in range(m):
for j in range(j+1):
print a[i][j], '\t',
print
You must have seen a list in the code, that is for obtaining the list of inputs.
I want to get the values of m and n separately for each matrix. And also the list.
For example, I want to get this
mtx()
m1=m
n1=n
l1=l
mtx()
m2=m
n2=n
l2=l
Problem2(a): Error that m is not defined(so are n and l).
Also, I tried to take m and n out of the definition and as a parameter. So I am able to get m and n.
def mtx(m,n):
a=[[0 for i in range(m)]for j in range(n)]
l=[]
for i in range(m):
for j in range(n):
s=a[i][j]=int(raw_input("Fill"))
l.append(s)
for i in range(m):
for j in range(j+1):
print a[i][j], '\t',
print
m1=int(raw_input("Rows"))
n1=int(raw_input("Col"))
mtx(m1,n1)
m2=int(raw_input("Rows"))
n2=int(raw_input("Col"))
mtx(m2,n2)
Problem2(b):But is it possible to get list l?
If problem2(a) is solved, there'd be no problem2(b).
You're doing your list comprehension the wrong way round. If you want m to indicate the number of rows and n to indicate the number of columns, you should do:
a=[[0 for i in range(n)]for j in range(m)]
Regarding your 2nd problem, you can make your function return list l using a return statement at the end of your function. Also the last print does not do anything in your example so I removed it:
def mtx(m,n):
a=[[0 for i in range(n)]for j in range(m)]
l=[]
for i in range(m):
for j in range(n):
s=a[i][j]=int(raw_input("Fill"))
l.append(s)
for i in range(m):
for j in range(j+1):
print a[i][j], '\t',
return l
If you then call your function:
my_list = mtx(m1,m2)
list l is now assigned to my_list.