Arrays vs slices

bearophile bearophileHUGS at lycos.com
Tue Jun 9 13:22:39 PDT 2009


Once the language tells apart arrays and slices, the arrays may have a third field that represents the capacity, and the slices may have a third field that represents the stride (that defaults to 1).
Python slices with strides specified:

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::2]
[0, 2, 4, 6, 8]
>>> a[::3]
[0, 3, 6, 9]
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[::-2]
[9, 7, 5, 3, 1]
>>> a[::2] = [10, 20, 30, 40, 50]
>>> a
[10, 1, 20, 3, 30, 5, 40, 7, 50, 9]


A simple example of stride usage, a true FFT (cmath contains functions that work on complex numbers):

from cmath import exp, pi

def fft(x):
    N = len(x)
    if N <= 1: return x
    e = fft(x[0 : : 2])
    o = fft(x[1 : : 2])
    return [e[k] + exp(-2j * pi / N * k) * o[k] for k in xrange(N // 2)] + \
           [e[k] - exp(-2j * pi / N * k) * o[k] for k in xrange(N // 2)]

t = fft([1.0] * 4 + [0.0] * 4)
print t[len(t)//2 :], "\n", t[: len(t)//2]


The output:
[0j, (0.99999999999999989+0.41421356237309492j), 0j, (0.99999999999999967+2.4142135623730949j)] 
[(4+0j), (1-2.4142135623730949j), 0j, (1-0.41421356237309492j)]

Bye,
bearophile



More information about the Digitalmars-d mailing list