Antonio Rodriguez schreef:
> I'm trying to modify some programs I've done in Java to better
> understand Python. One problem I'm encountering here is Python's lack of
> explicit arrays.
>
> Take a square array (n x n) of Java ints, only containing 0's and 1's:
> int[][] twisted = [[0, 1, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0,
> 1]];
> // 0 1 0 0
> // 0 1 0 0
> // 1 0 0 0
> // 0 0 0 1
>
> The function I had turns the array 90 degrees counterclockwise so that
> the above array turns into:
>
> // 0 0 0 1
> // 0 0 0 0
> // 1 1 0 0
> // 0 0 1 0
>
> In Java the function goes something like this:
>
> private int[][] twist(int[][] in)
> {
> // since array is square,
> // size serves as both length and width
>
> int size = in.length;
> int[][] out = new int[size][size];
>
> for(int i=0; i<size; i++)
> {
> for(int j=0; j<size; j++)
> {
> out[i][j] = in[j][size-i-1];
> }
> }
>
> return(out);
> }
>
> However, I'm having a dickens of a time trying to do the same in Python,
> using lists of lists
One solution is to build the list of lists one step at a time:
def twist1(input):
output = []
# we assume that m is square, so size == width == height
size = len(input)
for row in range(size):
newrow = []
for col in range(size):
newrow.append(input[col][size - row - 1])
output.append(newrow)
return output
Another solution is to build the output list with the correct dimensions
beforehand, after which you can fill it in with the right values the
same way as you did in Java:
def twist2(input):
size = len(input)
output = [range(size) for i in range(size)]
for row in range(size):
for col in range(size):
output[row][col] = input[col][size - row - 1]
return output
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)]
> and extracting the individual values to do some string
> processing after the rotation.
You can access the values using the same syntax as Java:
>>> print twisted
[[0, 0, 0, 1], [0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0]]
>>> print twisted[0][3]
1
>>> print twisted[2][2]
0
--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton
Roel Schroeven
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor