On Thu, Sep 22, 2011 at 10:37 AM, Dave Angel <d...@davea.name> wrote:
> ** > On 09/22/2011 10:27 AM, Joel Knoll wrote: > > Given a range of integers (1,n), how might I go about printing them in the > following patterns: > 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 > etc., e.g. for a "magic square". So that for the range (1,5) for example I > would get > 1 2 3 42 3 4 13 4 1 24 1 2 3 > I just cannot figure out how to make the sequence "start over" within a row, > i.e. to go from 4 down to 1 in this example. > I have been grappling with this problem for 2.5 days and have gotten nowhere! > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription > options:http://mail.python.org/mailman/listinfo/tutor > > Seems like the easiest way would be to duplicate the range once (so you > have a list twice as long), and then use various slices of it. > > x = list(range(1, 5)) #could omit the list() function in python 2.x > x2 = x+x > > for the nth row, use > row = x2[n:n+n] > > > > -- > > DaveA > > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I did it like this: The trick when cycling through numbers is to use the modulo operator (%) which gives the integer remainder after division #!/usr/bin/env python """ Print magic square give range n like so: If n is 5 1234 2341 3412 4123 """ n = 5 for row in range(n): for col in range(n): print (row + col) % n + 1, print -- 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4 Joel Goldstick
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor