What is wrong with the conditional statement if?
I want to make a function that generates randomly a matrix which
- Has $m$-different rows and $k$ columns
- The entries in each row are in a certain range $n$ and they do not repeat
- The sum of entries in each row is an even number
I have written the following code:
def generate(n,m,k):
if (m>binomial(n,k) or k>n):
print("error")
else:
a=matrix(m,k,0)
a[0]=sample(xrange(0,n),k)
j=1
while j<m:
r=sample(xrange(0,n),k) #candidate-row
c=sum(r) #sum of entries of the candidate- row
count=0
for i in xrange(0,j-1): #here we check if the candidate-row appeared before in the matrix
if (r==a[i]):
count=count+1
if (count==0 and mod(c,2)==0): #we take r if it did not appear before
a[j]=r #and the sum of entries is even
j=j+1
print(a.str())
When I call the function I notice that the rows actually are repeating and the sum in each row is not an even number and I can't understand why. Any suggestion is appreciated!
you use
xrange(0,j-1)
in your for-loop. You might want to look at the result from [i for i in xrange(0,5-1)] to see if that does what you think it should.Are you checking that your first row has even sum?
You are right, I did not check if the sum of the first row is even. For some reason I had the impression that I should first fill in the first row in the matrix and then take care of the rest via the while loop. Now I write all the matrix within the loop and it seems to work.