[Tutor] Rotating an array?

Alan Gauld alan.gauld at btinternet.com
Sun Nov 19 16:34:03 CET 2006


"Roel Schroeven" <rschroev_nospam_ml at fastmail.fm> wrote

> >       int[][] out = new int[size][size];
> >

If you just want an empty array as per Java you can use a
list comprehension:

out = [[0] * 4 for n in range(4)]

> >       for(int i=0; i<size; i++) {
> >          for(int j=0; j<size; j++) {
> >             out[i][j] = in[j][size-i-1];
> >             }
> >          }

      for i in range(size):
         for j in range(size):
            out[i][j] = inp[j][size-j-1]

> Or with a nested list comprehension it can even be done in one step:
>
> def twist3(input):
>     size = len(input)
>     return [[input[col][size - row - 1] for col in range(size)] for 
> row
> in range(size)]

Personally I'd go with Roel's list comprehension solution.
This exactly the kind of thing comprehensions were designed
for.

Which illustrates a danger of trying to learn one language
by just translating another. You wind up ewriting your old
language in the syntax of the new rather than learning the
new paradigms.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list