Reputation: 3
I'm relatively new to python and coding in general, and I'm working through some practice exercises on HackerRank. In the one I'm working on right now, several lines of input are given, as follows:
(In context this is n number and length of arrays, followed by the arrays)
3
11 2 4
4 5 6
10 8 -12
I need to access all lines of this input but as I said I'm quite new to this and not sure how. When I try to print input it only gives me the first line.
I saw in another HackerRank problem with multiple lines of input that this code was used:
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
Can someone please explain to me what's going on here? It's clearly accessing all the input but I don't understand how.
Upvotes: -7
Views: 81
Reputation: 27201
Don't use one-liners unnecessarily. They look "clever" but can be difficult (especially for beginners) to understand.
It's better to break down the functionality step by step.
n = int(input())
arr = []
for _ in range(n):
line = input()
tokens = line.split()
values = [int(t) for t in tokens]
arr.append(values)
print(arr)
Notes:
There is no explicit validation here. It is implicitly assumed that all tokens can be converted to int.
The int() function is impervious to both leading and trailing whitespace. Therefore, in this case, there is no need for either str.strip() or str.rstrip()
Upvotes: -2
Reputation: 51
I will explain the solution provided by you line by line.
n = int(input().strip()) -> 'input()' allows user to enter any input. '.strip()' removes all leading and trailing characters. 'int()' ensures that the input provided is of integer type only and not some random alphabet or special character.
arr = [] -> it creates an empty list which will store the user input.
for _ in range(n): -> this will create a loop (a task that will run 'n' number of times.
arr.append(list(map(int, input().rstrip().split()))) ->
PARTS OF EXPLANATION:
4.1 You need to input a list everytime the loop runs of any length.
4.2 input() allows you to enter as many numbers as you want (eg: 1 2 3 4 5). Please remember that 'input()' by default treats all input as string type.
4.3 rstrip() makes sure you don't add any extra spaces.
4.4 split() takes all the space separated characters and forms a list. (eg -> "1" "2" "3" -> AFTER SPLIT -> ["1","2","3"].
4.5 map(int, list after split) -> converts the input from int type from string type.
4.6 arr.append(list) -> This adds the list of numbers (one row) to the main list arr.
I hope that my solution made it easier for you to understand.
(PS: Always add the question number you are referring to.)
All the best!
Upvotes: -1