0

I want to create an array with 17 elements starting with 1 and other numbers are each twice the value immediately before it.

what I have so far is:

import numpy as np


array = np.zeros(shape=17)

array[0]=1

x = 1

for i in array:
    print(x)
    x *= 2

print(array)

what I got is:

1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

and what I want is:

[1.2.4.8.16.32.64.128.256.512.1024.2048.4096.8192.16384.32768.65536]

3 Answers 3

1

There is a function for that

np.logspace(0,16,17,base=2,dtype=int)
# array([    1,     2,     4,     8,    16,    32,    64,   128,   256,
#          512,  1024,  2048,  4096,  8192, 16384, 32768, 65536])

Alternatives:

1<<np.arange(17)
2**np.arange(17)
np.left_shift.accumulate(np.ones(17,int))
np.repeat((1,2),(1,16)).cumprod()
np.vander([2],17,True)[0]
np.ldexp(1,np.arange(17),dtype=float)

Silly alternatives:

from scipy.sparse import linalg,diags
linalg.spsolve(diags([(1,),(-2,)],(0,-1),(17,17)),np.r_[:17]==0    
np.packbits(np.identity(32,'?')[:17],1,'little').view('<i4').T[0] 
np.ravel_multi_index(np.identity(17,int)[::-1],np.full(17,2))
np.where(np.sum(np.ix_(*17*((0,1),))).reshape(-1)==1)[0]
Sign up to request clarification or add additional context in comments.

Comments

0

You need to assign the value back

import numpy as np


array = np.zeros(shape=17, dtype="int")

x = 1

for i in range(len(array)):
    array[i] = x
    print(x)
    x *= 2

>>> print(array)
[    1     2     4     8    16    32    64   128   256   512  1024  2048
  4096  8192 16384 32768 65536]

Comments

0

it will be more efficient using numpy vectorization like below.

import numpy as np
n=17
triangle = (np.tri(n,n,-1, dtype=np.int64)+1)
triangle.cumprod(axis=1)[:,-1]

Explanation

np.tri(n,n, dtype=np.int64) will create triangle matrix with values 1 at and below diagonal and 0 else where

np.tri(n,n, -1, dtype=np.int64) will shift the triangle matrix by one row such that first row is all zero

np.tri(n,n, -1, dtype=np.int64)+1 will change 0s to 1s and 1s to 2s

at last step use cumprod and take last column which is our answer as it will be products of 0,1,2 ... n 2's with remaining 1s

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.