Needless for
loop usage
for
loops in Python are heavy. Using for
loops needlessly leads to performance loss. For instance, rather than doing this:
for j in range(m):
if mat[i[0]-1][j]=="0" and mat[i[1]-1][j]=="0":
You could just count the number of ones using int()
, bin()
and |
as below:
orResult = int(mat[i[0] - 1], 2) | int(mat[j[0] - 1], 2)
numberOfSubjects = bin(orResult).count("1")
Confusing usage of count
Rather then counting the number of 0's
and then subtracting it from m
, you could initialize count
to m
and then decrement it each time 0's
are encountered. Then, in the end, count
would denote the number of 1's
.
Variable naming
Of course, I had to mention this. Variable names are not self-explanatory and it's difficult to understand what they represent exactly. For instance, z
means nothing meaningless to me. Please come up with better names. For instance, change
a = combinations(range(1,n+1),2)
To
indexPairs = combinations(range(1,n+1),2)
Optimised Code
from itertools import combinations
nm = input().split()
n = int(nm[0])
m = int(nm[1])
attendees=[]
for i in range(n):
attendees.append(input())
indexPairs = combinations(range(1,n+1),2)
maxNumberOfSubjects = 0
numberOfBestTeams = 0
for pair in indexPairs:
orResult = int(attendees[pair[0] - 1], 2) | int(attendees[pair[1] - 1], 2)
numberOfSubjects = bin(orResult).count("1")
if maxNumberOfSubjects == numberOfSubjects:
numberOfBestTeams += 1
elif maxNumberOfSubjects < numberOfSubjects:
maxNumberOfSubjects = numberOfSubjects
numberOfBestTeams = 1
print (maxNumberOfSubjects)
print (numberOfBestTeams)
I tested the code and it passed all the test cases.