# First attempt at a Python prog (Chess)

Oscar Benjamin oscar.j.benjamin at gmail.com
Sat Feb 16 15:39:11 CET 2013

```On 15 February 2013 15:49, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Feb 16, 2013 at 2:36 AM, Tim Golden <mail at timgolden.me.uk> wrote:
>> How true. This last time, my team split into two: one half
>> to handle the display, the other working on the algorithm. We
>> ended up having to draw a really simple diagram on the back of
>> an envelope with the x,y pairs written out and pass it back
>> and forth as *everyone* kept forgetting which went first.
>
> I'm sorry, I don't follow. People forgot that x comes before y, like
> it does in everything algebraic? Or is it that people lost track of
> which axis you called 'x' and which you called 'y'?

When you have a flat array and need to do a[x*N + y] to get an
element, the order is irrelevant. What matters is which of the
coordinates you multiply and what dimension of the array you multiply
it by. There are two equally good ways to do this, row-major and
column-major order:
http://en.wikipedia.org/wiki/Row-major_order

Any time you call into an API that expects a flattened array
representing a multidimensional array you need to check what order the
API expects. Typically a language has a convention such as C
(row-major) or Fortran (column-major). (According to that Wikipedia
page Python uses row-major, but I'm not really sure what that is
referring to).

Numpy allows you to specify the order when creating an array:
>>> import numpy as np
>>> aC = np.array([['a', 'b'], ['c', 'd']], dtype=str, order='C')
>>> aF = np.array([['a', 'b'], ['c', 'd']], dtype=str, order='F')
>>> aC
array([['a', 'b'],
['c', 'd']],
dtype='|S1')
>>> aF
array([['a', 'b'],
['c', 'd']],
dtype='|S1')

The different order in the two arrays above is transparent to Python
code that doesn't directly refer to the underlying memory arrangement:

>>> aC[0, 1]
'b'
>>> aF[0, 1]
'b'
>>> aC.strides
(2, 1)
>>> aF.strides
(1, 2)
>>> str(buffer(aC))
'abcd'
>>> str(buffer(aF))
'acbd'

This is useful when interfacing with linked Fortran and C libraries
(as is the case in scipy).

I find keeping track of what order I'm using when accessing the
elements of an array to be a pointless distraction. I would much
rather use an abstraction over the linear memory (such as a numpy
array) that enables me to forget all about it.

Oscar

```