That is easy for the single array: Just make your sequence a numpy.array
and your zigzag
function will call C code below the hood.
def zigzag(seq):
return seq[::2], seq[1::2]
seq = np.array([1,1,5,1,5,5,1,5,1,1])
result = zigzag(seq)
print(result)
Result:
(array([1, 5, 5, 1, 1]), array([1, 1, 5, 5, 1]))
For the multi dimensional case you have the problem that the length of your lists is not the same. Therefore you cannot make a nice numpy.array
out of that. I suggest that you adapt it like so:
import numpy as np
def zigzag(seq):
try:
if len(seq.shape) == 1:
return seq[::2], seq[1::2]
except AttributeError:
return [zigzag(x) for x in seq]
def main():
options = _parse_args()
seq = np.array([1,1,5,1,5,5,1,5,1,1])
seq2 = (
np.array([1, 1, 5, 1, 5, 5, 1, 5, 1, 1]),
np.array([2, 2, 2, 3, 3, 3, 3, 2, 2, 2]),
np.array([6, 3, 9, 2, 9, 4, 6, 3]),
)
print(zigzag(seq))
print()
print(zigzag(seq2))
The second sequence is just a tuple
of numpy.array
. The function checks whether your sequence has a shape
attribute, a good indicator that it is a numpy.array
. If so, it uses the NumPy slicing. In case it is a tuple, it will just call the zigzag
function for each element.
It produces the desired output for your examples:
(array([1, 5, 5, 1, 1]), array([1, 1, 5, 5, 1]))
[(array([1, 5, 5, 1, 1]), array([1, 1, 5, 5, 1])), (array([2, 2, 3, 3, 2]), array([2, 3, 3, 2, 2])), (array([6, 9, 9, 6]), array([3, 2, 4, 3]))]
This is a not a polished solution, however. You do not want to convert your Python lists and tuples to NumPy arrays all the time. As @hpaulj has pointed out in the comments, this conversion takes way longer than the splitting of the Python list
or tuple
itself. Think about where you have your data and where it makes sense to have them in NumPy arrays. Those have to have a rectangular shape. Once you have this, you can write a version of zigzag
that is appropriate.