I'm trying to re-write some code that looks like it was written by a FORTRAN programmer to make it more Pythonic/readable. Below is the code snippet of interest. The overall behavior of the code is to store the first three elements of Z into Zstart so long as the values are less than 1, and also store the last three values of Z into Zend as long as they are less than 1 as well.
import numpy as np
nbpoints = 3
Z = np.linspace(0,1.0,10)
Zstart = np.ones(nbpoints)
Zend = np.ones(nbpoints)
Zpts = np.size(Z)
for j in range(nbpoints):
if Z[j] < Zstart[j]:
Zstart[j] = Z[j]
if Z[Zpts - 1 - j] < Zend[nbpoints - 1 - j]:
Zend[nbpoints - 1 - j] = Z[Zpts - 1 - j]
The counter moving access of Zstart and Zend from both ends is tripping me up a bit. My current solution is the following.
import numpy as np
nbpoints = 3
Z = np.linspace(0,1.0,10)
Zstart = np.ones(nbpoints)
Zend = np.ones(nbpoints)
Zpts = np.size(Z)
for j in range(nbpoints):
if Z[j] < Zstart[j]:
Zstart[j] = Z[j]
if Z[-(j+1)] < Zend[-(j+1)]:
Zend[-(j+1)] = Z[-(j+1)]
Sample output from this code is:
Z = [ 0.0 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
0.66666667 0.77777778 0.88888889 1.0 ]
Zstart = [ 0.0 0.11111111 0.22222222]
Zend = [ 0.77777778 0.88888889 1.0 ]
My solution feels like I'm still just re-writing poorly written code e.g. rearranging chairs on the deck of the Titanic. Is there a more Pythonic way to perform this operation?