[Tutor] another for loop question - latin square

Dave Angel d at davea.name
Mon Dec 31 01:44:27 CET 2012


On 12/30/2012 06:59 PM, Brandon Merritt wrote:
> I am having trouble

Please tell us what Python version you're targeting.  It looks like 2.7,
but you really should specify it for us.

Next, you should tell us your skill level;  are you experienced at
another language and learning Python, or what?  Is this latin square an
assignment, from a tutorial or book, or just for fun?  If from a
tutorial, have you been doing the earlier problems?  Have you completed
any other Python projects which were non-trivial?  Do you realize just
how tricky a latin square is to create?

>  figuring out a solution after a couple hours now of
> playing with the code. I'm trying to make a latin square

For other readers, an nxn latin square (not a magic square) has the same
n symbols in each row and in each column, with no duplicates in any row,
nor in any column.  For a 4x4 square, one solution might be

     A B C D
     B D A C
     C A D B
     D C B A


>  using the code
> below:
>
> scaleorder = int(raw_input('Please enter a number for an n*n square: '))
>
>
> topleft = int(raw_input('Please enter the top left number for the square:
> '))
>
> firstrow = range((topleft),scaleorder+1)

You do realize that this won't necessarily create a list of the
requested size?  Specifically, if the user didn't specify a top-left of
exactly 1, then the size will be wrong.

> count = 0
>
> while count < 8:
>     for i in firstrow:
>         print i
>         count += 1
>         firstrow[i+1]

Just what did you expect the last line to accomplish?  And what was the
8 supposed to mean?

>
> -----------------------------------------------------------------------
>
> It seemed like I could make the for loop work by doing something like this:
>
> for i in firstrow:
>         print i, i+2
>
>
> but  that obviously is not a solution either. Any ideas?
>
> Thanks,
> Brandon
>
>
>

Have you constructed a latin square by hand, of any size ?  (try 4 for
your first attempt)  Do you realize that you could build 3 lines and
then discover that there is no valid fourth line for those 3?

Have you learned how and why to build functions in your code?   I
maintain this problem is too tricky to do without at least factoring
each row into a function.



-- 

DaveA



More information about the Tutor mailing list