How to improve the following code?
1 )-> pass a 1-dimensional array of length 2**n
2 )-> for every index of the array get the binary representation
3 )-> reverse the binary represenation and use it as new integer index for the corresponding value
EXAMPLE:
[56,209,81,42]
[00,01,10,11] (binary representation of the indices)
-> REVERSE:[00,10,01,11]
-> BECOMES:[56,81,209,42]
Code:
def order_in_reversed_bits(data: np.ndarray) -> np.ndarray:
tobinary = lambda t: np.binary_repr(t, width=len(np.binary_repr(data.shape[0]-1)))[::-1]
func = np.vectorize(tobinary)
a = func(np.arange(0,data.shape[0]))
t = np.zeros(data.shape,dtype='float64')
for i,k in enumerate(a):
t[int(k,2)] = data[i]
return t
Which built-in functionality of Numpy or Python is handy?
vectorizeisn't going make applyingnp.binary_reprany faster. It still generates one string per number.np.vectorizecauses a lot of misunderstandings. It does operate on whole arrays, but not in idealized the way that produces 10x speedups. Others usevectorizeto mean using multiprocessing and and fast hardware engines. Your accepted answer gains speed simply because'{:b}'.formatis faster thannp.binary_repr.np.binary_repris Python code, which we can study and potentially modify. The core action isbin(n), which produces a string like '0b10001'. It just cleans it up and adjusts for width.