1

Python Newbie here. I'm validating the rows and columns in a square, represented by a nested list like the one below:

[[1,2,3],
 [2,3,1]
 [3,1,2]]

The rows and columns are valid if they appear 1 to n times only once. So for example if the nested list is of length 3 then numbers 1,2 and 3 should appear once in all the rows and once in all the columns in order for it to be valid. I'm checking the rows and understand how that works. Below I have defined a method called check_sequence which checks to see if number 1 to n appear in the list only once and the get_rows method gets all the rows in the list and checks them against check_sequence:

def check_sequence(mylist):
    for x in range(1, len(mylist)+1):
        print "x:" + ' ' + str(x)
        if x not in mylist:
            print "False"
            return False
        else:
            print "True"


def check_row(mylist):
    for row in mylist:
        print row
        if check_sequence(row) is False:
            print "This is False"
            return False
    print "This is True"
    return True

What I don't understand is how to check the columns in the square using for loops. So for example, if we have the same square as above:

[[1,2,3],
 [2,3,1]
 [3,1,2]]

The first column contains 1,2 and 3, the second column contains 2,3 and 1. I'm confused as to how I would gather those number together in one column and check them against my method check_sequence?

johnnewbie25
  • 149
  • 4
  • 12

1 Answers1

1

In order to obtain the i-th column of a list of lists, you can use list comprehension:

column_i = [ row[i] for row in matrix ]

So then your checking code should be:

def check_row(mylist):
    for row in mylist:
        print row
        if check_sequence(row) is False:
            print "This is False"
            return False
    for i in len(mylist):
        print row
        if check_sequence([ row[i] for row in mylist ]) is False:
            print "This is False"
            return False
    print "This is True"
    return True

Nevertheless, you can also use zip(..) to transpose the list of lists into an list of tuples:

def check_row(mylist):
    for row in mylist:
        print row
        if check_sequence(row) is False:
            print "This is False"
            return False
    for col in zip(*mylist):
        print col
        if check_sequence(col) is False:
            print "This is False"
            return False
    print "This is True"
    return True
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555