Home > Back-end >  How to get multiple inputs in Python like in HackerRank
How to get multiple inputs in Python like in HackerRank

Time:07-07

I am trying to solve a challenge similar to HackerRank's challenges. But I am using my own computer's IDE to code and test.

I don't wanna cheat, so the solution I'll do myself. But I'm kinda stuck trying to think of a good way to receive the inputs. Because there's the typical multi lines inputs where each line represents something I have to use to solve the challenge.

For example:

Input Format:

  • The first line contains an integer X, the number of test cases.
  • The second line contains an integer N, the number of values.
  • The second line contains a list L, the values (len(l) == n).

Input Example

2
3
1 2 3
5
4 5 6 7 8

Normally, I would do something like this.

def main():
    n = int(input()) # Number of tests

    for _ in range(n):
        x = int(input()) # Number of values
        l = input() # Values
        # do something

But I cannot use any loop whatsoever in the code and I can only output something after all inputs has been received.

How HackerRank do this? What's the best way to store all the inputs first before starting to output the results? Using a recursive function to get all inputs and another recursive function to read them?

CodePudding user response:

If I understand what you want correctly you just need to do something like this:

def get_inputs():
   n = input()
   def fake_loop():
     nonlocal n
     if n==0: return
     else:
        #do your things
        n-=1
        fake_loop():
  fake_loop()

But it's a bit weird, can you link the challenge?

CodePudding user response:

In python array input is independent of size when they are in single line and separated by a delimiter, first use input() to get whole line as input then split it at spaces then map each element with integer finally convert it to list for convince as its flexible data structure to deal with. Simply use list(map(int,input().split()))

def main():
    n = int(input()) # Number of tests

    for _ in range(n):
        x = int(input()) # Number of values
        l = list(map(int,input().split()))
        # do something


  • Related