Home > Blockchain >  How to read all inputs from STDIN in Hackerrank?
How to read all inputs from STDIN in Hackerrank?

Time:08-03

I have learned some basics of Python and wanted to try easy challenges in Hackerrank.

Input format: the first line contains integer, the second line contains the space separated list of integers, and third line contains another integer.

In codding part, it says # Enter your code here. Read input from STDIN. Print output to STDOUT

I am having difficulty of reading and saving from STDIN. I want to save the first line integer as X, second line list as list and third line integer as N.

I don't understand how to do it. I have googled and tried to use some existing codes, but keep getting errors.

CodePudding user response:

You can use input:

# the first line contains integer
integer1 = int(input())

# the second line contains the space separated list of integers
int_lst = list(map(int, input().split()))

# third line contains another integer.
integer2 = int(input())
list of lists for 10 lines:
lst = [list(map(int, input().split())) for _ in range(10)]

CodePudding user response:

We can use the input() to receive the input from STDIN and cast it to int as the input() function returns the STDIN as string.

To receive an integer:

>>> x = int(input().strip())
12
>>> x
12

To convert the list of space separated integers to list:

>>> y = list(map(int,input().strip().split(' ')))
1 2 3 4 556
>>> y
[1, 2, 3, 4, 556] 

To create 2D list of integers:

>>> rows = 3
>>> array = []
>>> for i in range(rows):
...     each_line = list(map(int,input().strip().split(' ')))
...     array.append(each_line)
...
1 2 3
4 5 6
7 8 9
>>> array
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • Related