Home > Net >  How to create an array given n-rows and k-columns, with a starting number x and step size y in pytho
How to create an array given n-rows and k-columns, with a starting number x and step size y in pytho

Time:11-15

So let's say I ask for some input of n-rows and k-columns:

rows = n
columns = k

What I want to do is to create an array of dimensions (rows, columns) and then populate said array with a set of numbers starting from some number x with some step size y such that no matter the inputs for rows and columns it would be able to create an array of said dimensions with the "last"/bottom right element of the array then being some yet to be determined number z.

As an example input I could have:

rows = 4
columns = 3

# Starting number
x = 1

# Step size
y = 2

The expected output would then be:

array = [[ 1  3  5]
         [ 7  9 11]
         [13 15 17]
         [19 21 23]]

As the array changes dimensions, then so would the numbers inside it, determined by the dimensions of the array, the starting number and step size.

CodePudding user response:

Yes you can do that like this:

import numpy
rows = 4
columns = 3
# Starting number
x = 1
# Step size
y = 2

array = np.arange(x, (rows*columns)*y x, y).reshape(rows, columns)

Please look at https://numpy.org/doc/stable/reference/generated/numpy.arange.html and https://numpy.org/doc/stable/reference/generated/numpy.reshape.html

CodePudding user response:

A very slow but simple method could be

start = 1
increment = 2
rows = 4
cols = 3

array = np.zeros(shape=(rows, cols))

for i in range(rows):
    for j in range(cols):
        array[i][j] = start
        start  = increment

CodePudding user response:

rows = 4
columns = 3

# Starting number
x = 1

# Step size
y = 2

array = []
num = 1

for i in range(rows):
    list = []
    for j in range(columns):
        list.append(num)

        num  = y

    array.append(list)

print(array)
  • Related