On Thu, Sep 22, 2011 at 11:08 AM, Steven D'Aprano <st...@pearwood.info>wrote:
> 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'm not sure what you want, because the formatting is all broken in > Thunderbird. Your "magic square" looks more like a straight line. > > I'm going to take a wild stab in the dark and *guess* that you want > something like this: > > > 1 2 3 4 > 2 3 4 1 > 3 4 1 2 > 4 1 2 3 > > Look at the pattern: each row is the same as the previous row, except the > first item is moved to the end. You can move an item from the front to the > end with pop() to delete it, and append() to re-add it. > > There are the same number of rows as columns. Putting this together: > > > n = 4 # number of columns > row = range(1, n+1) > for row_number in range(n): > # print the row without commas and [] > for item in row: > print item, # note the comma at the end > print # start a new line > # Pop the first item from the list, then add it to the end. > x = row.pop(0) > row.append(x) > > > > -- > Steven > > > ______________________________**_________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > An easier way to print without the comma, assuming 2.6 or 2.7 is to add this: from __future__ import print_function and then print like this: print(*a) or if you are already using python 3.0+ you just print like that without the import.
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor