I am using python to sequence some numbers. I would like to create a function which allows me to input a value (4, 8, 16, 32, 64, etc.), create an array of numbers, and rearrange their sequence.
I've added figures which detail how to determine the sequence for value = 4, and 8.
For value = 4 the array (x = [0, 1, 2, 3]) should be split in two ([0,1] and [2,3]) and then combined based on the first number in each array ([0, 2 ,1 ,3]).
For value = 8 the array (x = [0, 1, 2, 3, 4, 5, 6, 7]) should be split into two ([0, 1, 2, 3] and [4, 5, 6, 7]). Both arrays should be split in two again ([0, 1, 2, 3] into [0,1] and [2,3] and [4, 5, 6, 7] into [4,5] and [6,7]). Then the arrays should be combined based on the first number in each array and the sequence of 2nd set of arrays ([0, 4, 2, 6, 1, 5, 3, 7]).
I don't know how to handle the recursion (dynamically nested for loops). I am trying to loop through each brach that is created by spliting the array. I've looked into itertools and recursion (Function with varying number of For Loops (python)), but I could not make it work. Below, I've added code to illustrate my approach thus far.
Any help is much appreciated. I am also open to other ideas to determine the sequence.
I am using python 2.7.6 and numpy.
Code:
import numpy
value = 4
a = []
x = numpy.arange(value)
y = numpy.array_split(x, 2)
for i in range(2):
for j in y:
a.append(j.tolist()[i])
print(a)
Output:
[0, 2, 1, 3]
Code:
import numpy
value = 8
a = []
x = numpy.arange(value)
y = numpy.array_split(x, 2)
for i in range(2):
for h in range(2):
for j in y:
z = numpy.array_split(j, 2)
a.append(z[h][i])
print(a)
Output:
[0, 4, 2, 6, 1, 5, 3, 7]
The output for value = 16 should be [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11 ,7 15].