One test case is showing time limit exceeded.Why? - python

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.

Related

how can i do vector-matrix multiplication in python without numpy?

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

Transpose of a matrix showing same results as original

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

Fill only the elements in the top and bottom row with zeroes

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)

Program terminated due to time out

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)

Python Program to define a function for matrix and obtain values of matrices separately in as lists

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.

Categories