pip February 2016

How to nicely handle [:-0] slicing?

In implementing an autocorrelation function I have a term like

for k in range(start,N):
    c[k] = np.sum(f[:-k] * f[k:])/(N-k)

Now everything works fine if start = 1 but I'd like to handle nicely the start at 0 case without a conditional.

Obviously it doesn't work as it is because f[:-0] == f[:0] and returns an empty array, while I'd want the full array in that case.

Answers


Wombatz February 2016

Don't use negative indices in this case

f[:len(f)-k]

For k == 0 it returns the whole array. For any other positive k it's equivalent to f[:-k]


DainDwarf February 2016

There are several ways of doing it, by testing if k==0 before applying the formula. It's up to you to find the only that looks nicer.

for k in range(start,N):
    c[k] = np.sum(f[:-k] * f[k:])/(N-k) if k != 0 else np.sum(f * f[k:])/(N-k)

for k in range(start,N):
    end_in_list = -k if k != 0 else None
    start_in_list = k
    c[k] = np.sum(f[:end_in_list] * f[start_in_list:])/(N-k)


RootTwo February 2016

If k is zero use None for the slice, like so:

for k in range(start,N):
    c[k] = np.sum(f[:-k if k else None] * f[k:])/(N-k)

Post Status

Asked in February 2016
Viewed 1,811 times
Voted 5
Answered 3 times

Search




Leave an answer