[Tutor] another for loop question - latin square
Steven D'Aprano
steve at pearwood.info
Mon Dec 31 01:27:22 CET 2012
On 31/12/12 10:59, Brandon Merritt wrote:
> I am having trouble figuring out a solution after a couple hours now of
> playing with the code. I'm trying to make a latin square 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)
>
> count = 0
> while count< 8:
> for i in firstrow:
> print i
> count += 1
> firstrow[i+1]
>
>
> -----------------------------------------------------------------------
>
> 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?
Absolutely none. I don't understand your question. What's a latin square?
Is it the same as a magic square? What do you mean, "make the for loop work"?
The for loop already works: it iterates over the range topleft to scaleorder
inclusive. You say "that obviously is not a solution", but a solution to
what? What is it supposed to do?
I think that you need to think a bit more carefully about what you are
trying to accomplish. Probably the most valuable piece of advice I ever
received was that *writing code* should be the last thing you do when
trying to solve a problem. When I have a tricky problem to accomplish,
I will sometimes spend hours designing my code with pencil and paper
before writing my first line of code.
Can YOU solve a latin square using pen and paper? If you can't, how do you
expect to write a program to do it?
Start by writing down the steps that you would take to make a latin square.
I suggest with starting with a fixed size, say, 5x5:
* pick a number for the top left corner, say, 3
* write down the first row: 3 ? ? ? ?
[you need to come up with a rule for making the row]
* write down the second row: ? ? ? ? ?
[again, you need to come up with a rule for making the next row]
... and so on for the other three rows. Now you have an algorithm for
making 5 x 5 latin squares.
Now you can write some code to do that!
Once that is working, you can start thinking about changing from fixed
5 x 5 squares to arbitrary N x N sizes.
--
Steven
More information about the Tutor
mailing list