0

A Python code which takes 2 numbers x and y as input and generates a 2-dimensional numpy array where value in the i-th row and j

A Python code which takes 2 numbers x and y as input and generates a 2-dimensional numpy array where value in the i-th row and j-th column of the array should be (i+j)/2. Note: i=0,1,...x-1 and j=0,1....,y-1 The input will have two lines with x and y respectively. The output should be a 2D numpy array. Sample Input: 3 4 Sample Output: [[0. 0.5 1. 1.5] [0.5 1. 1.5 2. ] [1. 1.5 2. 2.5]]

22nd May 2019, 2:44 PM
Suchith Chandran
Suchith Chandran - avatar
6 Respostas
+ 1
import numpy as np x=int(input()) y=int(input()) #write your code here def d_array(r,c): array = [[(i+j)/2 for j in range(y)] for i in range(x)] a = np.matrix(array) return a print(d_array(x,y)) The Code worked for me
22nd May 2019, 3:15 PM
Suchith Chandran
Suchith Chandran - avatar
0
So what's your question?
22nd May 2019, 3:18 PM
Diego
Diego - avatar
0
Can you please simplify my code further ? I have a feel that it's more complex
22nd May 2019, 3:22 PM
Suchith Chandran
Suchith Chandran - avatar
0
Your code is as simple as it can be. What you could do is put it all in one line. import numpy as np x=int(input()) y=int(input()) def d_array(r,c): return np.matrix([[(i+j)/2 for j in range(y)] for i in range(x)]) print(d_array(x,y))
22nd May 2019, 3:26 PM
Diego
Diego - avatar
0
x=int(input()) y=int(input()) arr = [[(i+j)/2 for j in range(y)] for i in range(x)] print(np.matrix(arr))
4th Oct 2019, 10:01 AM
Mary Santhu
- 1
Please show us your attempt.
22nd May 2019, 3:14 PM
Diego
Diego - avatar