I can't figure out a hackerrank problem about numpy arrays.
You're given a list with 9 ints (from 1 to 9) with spaces and you are supposed to return a reshaped 2d array containing those numbers with 3 collumns and 3 rows.
Even tho the code I written seems to work fine for me in PyCharm, it doesn't pass the hackerrank test. I know I could just google the results and "ctrlc ctrlv" it, but I would like to know what exacly is wrong with my code.
import numpy
nums_list = []
num = input("Number: ")
for i in num:
if i == " ":
pass
else:
nums_list.append(int(i))
nums_array = numpy.array(tuple(nums_list))
nums_array = numpy.reshape(nums_array, (3, 3))
print(nums_array)
my code in PyCharm:
hackerrank:
CodePudding user response:
The problem is the prompt on the input statement:
num = input("Number: ")
This puts "Number: "
to stdout, failing your tests.
You can change it to input()
, so there is no prompt printed, and then all the tests pass.
Note that your method of converting the input text into a list of numbers is not safe unless there are only numbers 0-9 present in the input data. Consider using this method instead, and skip the intermediate list/tuple:
>>> np.fromstring('1 2 3 4 5 6 7 8 9', sep=' ', dtype=int)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
CodePudding user response:
Your code will fail if any input number is larger than 9, because you're processing each character separately. Try entering "10 11 12 13 14 15 16 17 18". You need to use .split
to chop the input up into words, then convert the words.