One thing that has frustrated me the most from the Hackerrank challenges is the part of reading inputs for the functions through stdin.
Hackerrank inputs generally have a \n delimiter, which is provided through sys.stdin. I want to know an efficient way to read the inputs and split them into a list. An example follows:
Input:
3 2
1 5 3
3 1
5 7
I want to read each line into a separate list. Below is my attempt:
import sys
arr = sys.stdin.readlines()[1].split()
arr = list(map(int, arr))
A = sys.stdin.readlines()[2].split()
A = set(map(int, A))
B = sys.stdin.readlines()[3].split()
B = set(map(int, B))
I'm getting following error:
A = sys.stdin.readlines()[2].split()
IndexError: list index out of range
Why IndexError on [2] where as [1] works? Is there a better way to read such stdin inputs using loops?
The reason that you are getting the error is that readlines is consuming all your input on the first call. That means that the second time you call it, there's nothing there.
To make a 2D list of all the inputs, you have to work with the first call:
data = [line.rstrip().split() for line in sys.stdin.readlines()]
You may as well convert to integers up front:
data = [[int(x) for x in row] for row in data]
Now
arr = data[0]
A = set(data[2])
B = set(data[3])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With