0

Hi my question is in regards to the J.F. Sebastian code and discussion below. I am trying to print a sub array of an array. The code is below and my update is on the bottom. (It gives error messages)creating a spiral array in python?

I want to create a sub array based on a chosen entry in this array. if we choose the 04 entry,

subarray[x][y] == 04
subarray[x][y] == TheSpiral[x-1:x+2,y-1:y+2]

print_matrix(TheSpiral)  
print_matrix(subarray)

However I get an error message due to not properly defining subarray. I was expecting the print_matrix(subarray) to yield

06 01 02
05 04 03
16 15 14

which is why I used #TheSpiral[x-1:x+2,y-1:y+2]. Thanks for the help.

Community
  • 1
  • 1
Jeff Faraci
  • 403
  • 13
  • 28
  • 2
    **`I get error messages`** is hardly a good description of the problem. What are your error messages? Could you please be more specific? – Ed de Almeida Nov 20 '16 at 00:52

2 Answers2

2

The issue is that the second slice doesn't do what you think it does

  • it's a syntax error with standard list and you should use [][], however ...
  • the second indices is not slicing the individual sub arrays, a slice returns the list of lists which the second slice would also operate on

You can fix it with a list comprehension:

>>> i, j = 3, 2
>>> subarray = [row[j-1:j+2] for row in TheSpiral[i-1:i+2]]
>>> print_matrix(subarray)
06 01 02
05 04 03
16 15 14

Alternatively you can use numpy (which maybe overkill!!!) and use your original syntax:

>>> import numpy as np
>>> subarray = np.array(TheSpiral)[i-1:i+2,j-1:j+2]
>>> print_matrix(subarray)
06 01 02
05 04 03
16 15 14

To calculate the spiral coordinates:

def spiral_coord(n):
    k = int((n**0.5) // 2)
    t = 2*k
    m = (t+1)**2
    for fn in (lambda: (-k, k-(m-n)), lambda: (-k+(m-n), -k), lambda: (k, -k+(m-n))):
        if n >= m-t:
            return fn()
        m -= t
    return k-(m-n-t), k

>>> mid = (5-1)//2
>>> i, j = map(lambda x: x+mid, spiral_coord(9))
>>> subarray = np.array(TheSpiral)[i-1:i+2,j-1:j+2]
>>> print_matrix(subarray)
23 24 25
08 09 10
01 02 11
AChampion
  • 29,683
  • 4
  • 59
  • 75
1

I believe that there is a syntactical error in your subarray code. As the method "spiral" returns a 2D array(TheSpiral in your case), the way of accessing the elements of the 2D array must be

TheSpiral[i][j]

not

TheSpiral[i,j]
Nihal Rp
  • 484
  • 6
  • 15