What is wrong with the conditional statement if?

asked 2016-07-04 17:48:57 -0600

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

I want to make a function that generates randomly a matrix which

  1. Has $m$-different rows and $k$ columns
  2. The entries in each row are in a certain range $n$ and they do not repeat
  3. 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!

edit retag flag offensive close merge delete

Comments

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?

nbruin gravatar imagenbruin ( 2016-07-04 23:07:32 -0600 )edit

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.

kristina gravatar imagekristina ( 2016-07-05 04:52:05 -0600 )edit