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
Solution 1:
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]
Solution 2:
If k is zero use None for the slice, like so:
for k inrange(start,N):
c[k] = np.sum(f[:-k if k elseNone] * f[k:])/(N-k)
Solution 3:
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 inrange(start,N):
c[k] = np.sum(f[:-k] * f[k:])/(N-k) if k !=0else np.sum(f * f[k:])/(N-k)
for k inrange(start,N):
end_in_list =-k if k !=0elseNone
start_in_list = k
c[k] = np.sum(f[:end_in_list] * f[start_in_list:])/(N-k)
Post a Comment for "How To Nicely Handle [:-0] Slicing?"