Open

0

# Data Science - Reshape

Task Given a list of numbers and the number of rows (r), reshape the list into a 2-dimensional array. Note that r divides the length of the list evenly. Input Format First line: an integer (r) indicating the number of rows of the 2-dimensional array Next line: numbers separated by the space Output Format An numpy 2d array of values rounded to the second decimal. Sample Input 2 1.2 0 0.5 -1 Sample Output [[ 1.2 0. ] [ 0.5 -1. ]] import numpy as np r = int(input()) lst = [float(x) for x in input().split()] arr = np.array(lst) print(np.round(arr.reshape(r, 2), decimals=2))

13 Answers

0

The note that r DIVIDES THE LENGTH of the list evenly tells you that the 2D array will always have enough elements to fill r rows evenly (no empty spots).
Therefore you have to have the number of columns in which r rows creates an acceptable 2D array.

+ 12

try
r = int(input())
lst = [float(x) for x in input().split()]
arr = np.array(lst)
arr_new=arr.reshape(r,-1) #-1 stands for any value that numpy founds suitable.
print(arr_new)

+ 2

#library import
import numpy as np
#input and create list
row = int(input())
lst = [round(float(x), 2) for x in input().split()]
#number of columns
column = len(lst)//row
#reshape numpy array
arr = np.array(lst)
arr_2d = arr.reshape(row, column)
print(arr_2d)

+ 1

hack with `.reshape(r,-1)` works but it didn't explained in the course :)

0

This is 15 code project (in data science course)
I Think that I don't understand this:
"Note that r divides the length of the list evenly."
of the task.
The 2 first tests are o.k. but the next 3 tests are wrong.

0

Please help. Thank you.

0

Josiah Mathieu and what am I missing?

0

I solved it. Thank you.

0

Can somebody explain why reshape(r,2) doesn`t work?

0

The inputs of Next line(lst) are not divisible by 2 in all the tests

0

import numpy as np
r = int(input())
lst = [float(x) for x in input().split()]
arr = np.array(lst)
p=np.array(lst)+np.array(arr)
k=p.size//r
print((p/2).reshape(r,k))

0

import numpy as np
r = int(input())
lst = [float(x) for x in input().split()]
arr = np.array(lst)
arr=arr.reshape(r,-1)
print(arr)

0

import numpy as np
r = int(input())
lst = [float(x) for x in input().split()]
arr = np.array(lst)
print(np.reshape(arr, (r, int(len(lst) / r))))