shortcuts in if-else condition python

Viewed 87

I have the following abbreviation of a function in my code:

s = 0.5
m = np.nonzero((velo>freq-fthrow - s*maskwidth_f))
velo_mask = np.delete(velo, m)
spec_mask = np.delete(spec, m)
if (average(velo_mask<0.9):
 s = 0.8
 m = np.nonzero((velo>freq-fthrow - s*maskwidth_f))
 velo_mask = np.delete(velo, m)
 spec_mask = np.delete(spec, m)
else:
 s = 0.5
 m = np.nonzero((velo>freq-fthrow - s*maskwidth_f))
 velo_mask = np.delete(velo, m)
 spec_mask = np.delete(spec, m)

This means that I have to compute the two arrays first based on the initial given value of s, then do the condition, based on it, I change the value of s and I want the re-run the whole previous code based on the new value of s. (I have a loop,and each time the whole data changes)

It is actually a huge code, and I don't want to re-write it 3 times, once to calculate the average, in the if condition, and in the else condition.

Is there maybe a way to tell python to re-run the whole previous part in the if-else condition.

1 Answers

Use functions to avoid code duplication. Example:

def create_mask(velo, spec, freq, fthrow, maskwidth_f, s):
    m = np.nonzero((velo > freq - fthrow - s * maskwidth_f))
    velo_mask = np.delete(velo, m)
    spec_mask = np.delete(spec, m)
    return velo_mask, spec_mask

...

s = 0.5
velo_mask, spec_mask = create_mask(velo, spec, freq, fthrow, maskwidth_f, s)

s = 0.8 if average(velo_mask < 0.9) else 0.5
velo_mask, spec_mask = create_mask(velo, spec, freq, fthrow, maskwidth_f, s)
Related