0
arr= [1,2,3,4]
k = 4 (can be different)

so result will be 2 d array. How to do this without using any loop? and can't hard code k. k and arr can vary as per input. Must use numpy.pad

[[1,2,3,4,0,0,0], #k-1 zeros
 [0,1,2,3,4,0,0],
 [0,0,1,2,3,4,0],
 [0,0,0,1,2,3,4]]


0

2 Answers 2

2

If you really have to do it without a loop (for educational purposes)

np.pad(np.tile(arr,[k,1]), [(0,0),(0,k)]).reshape(-1)[:-k].reshape(k,-1)
Sign up to request clarification or add additional context in comments.

Comments

1

Using list comprehension as a one liner :

import numpy as np

arr= np.array([1,2,3,4])
k = 4

print( np.array( [ np.pad(arr, (0+i , k-1-i ) ) for i in range(0,k)] ) )

Out :

[[1 2 3 4 0 0 0]
 [0 1 2 3 4 0 0]
 [0 0 1 2 3 4 0]
 [0 0 0 1 2 3 4]]

3 Comments

In real world your answer would have been perfect. But the question is no for or while loops or even list comprehension. Hidden loops are ok . @Osamoele
@Grafins Is there a reason you would refuse to work with any loop ? If it is for speed, you should consider making a dedicated function in cython, using foor loop as you wish there, and it will be faster than in python. At least not slower than the numpy C-implemented functions, that use SIMD and loops internally. Else, i see no real valid reason except for entertainment purposes but should be your challenge in that case ;)
its part of my programming assignment. So no loops. please understand

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.