[Tutor] range question
Steven D'Aprano
steve at pearwood.info
Thu Sep 22 17:08:27 CEST 2011
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
More information about the Tutor
mailing list