Is there a better way to insert, one by one, elements in an array
to all posible positions (n+1 positions).
E.g inserting [1]
to [6 7 8 9]
should produce:
[1 6 7 8 9]
[9 1 6 7 8]
[8 9 1 6 7]
[7 8 9 1 6]
[6 7 8 9 1]
So if I insert A = [1 2 3]
one by one to B = [6 7 8 9]
it should produce:
[1 6 7 8 9]
[9 1 6 7 8]
[8 9 1 6 7]
[7 8 9 1 6]
[6 7 8 9 1]
--------------------
[2 6 7 8 9]
[9 2 6 7 8]
[8 9 2 6 7]
[7 8 9 2 6]
[6 7 8 9 2]
--------------------
[3 6 7 8 9]
[9 3 6 7 8]
[8 9 3 6 7]
[7 8 9 3 6]
[6 7 8 9 3]
--------------------
Currently I use numpy.roll
like this:
import numpy as np
import timeit
A = np.array([1, 2, 3, 4, 5])
B = np.array([6, 7, 8, 9])
def inject_one(Ad, Bd):
for i, _ in enumerate(Ad):
C = np.append(Ad[i], Bd)
for _ in range(len(C) - 1):
C = np.roll(C, 1)
t = timeit.Timer(lambda: inject_one(A, B))
print("{:.3f}secs for 1000 iterations".format(t.timeit(number=1000)))
# > 0.160 secs