1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Can I improve my Numpy solution to an exercise?

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024 às 10:12.

  1. Stack

    Stack Membro Participativo

    I have been asked to use the following set of column indices: y = np.array([3, 0, 4, 1])

    to turn into 1 all the elements in the following matrix: x = np.zeros(shape = (4, 5)) that have y as starting column and rows given by the position of y. Just to be clear.

    The final result has to be the following:

    [[0. 0. 0. 1. 1.] [1. 1. 1. 1. 1.] [0. 0. 0. 0. 1.] [0. 1. 1. 1. 1.]]

    For example:

    y[0] = 3,

    then row 0, columns 3 and 4 need to be equal to 1.

    I did it like this:

    for (idx, num) in enumerate(y): x[idx, num:] = 1

    Can this result be written differently and/or improved by using other Numpy functions (for example, using vectorization)?

    Continue reading...

Compartilhe esta Página