Open In App

Python Input Methods for Competitive Programming

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. In online coding platforms, if the C/C++ limit provided is x. Usually, in Java time provided is 2x, and in Python, it’s 5x. To improve the speed of code execution for input/output intensive problems, languages have various input and output procedures. In this article, we are going to see various Python input methods for competitive programming.

Example Problem 

Consider a question of finding the sum of N numbers inputted from the user. 
Input a number N
Input N numbers are separated by a single space in a line. 

Example

Input: 
5
1 2 3 4 5
Output:
15

Input Methods for Competitive Programming in Python

Below are the methods by which we can take faster input in Python:

  • Normal Method
  • Faster Method using Inbuilt Function
  • Taking User Input Given in a Single Line in Separate Variables
  • Taking User Inputs of List of Integers
  • Taking String Input from the User
  • Adding a buffered pipe io (Python 2.7) 

Normal Method Python (Python 2.7)

  • raw_input() takes an optional prompt argument. It also strips the trailing newline character from the string it returns. 
  • print is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls the write function of a given object. 

Python3




# input N
n = int(input())
 
# input the array
arr = [int(x) for x in input().split()]
 
# initialize variable
summation = 0
 
# calculate sum
for x in arr:
    summation += x
     
# print answer
print(summation)


Faster Method Using Inbuilt stdin, stdout (Python 2.7)

  • sys.stdin on the other hand is a File Object. It is like creating any other file object one could create to read input from the file. In this case, the file will be a standard input buffer. 
  • stdout.write(‘D\n’) is faster than print ‘D’
  • Even faster is to write all once by stdout.write(“”.join(list-comprehension)) but this makes memory usage dependent on the size of the input.  

Python3




from sys import stdin, stdout
 
# suppose a function called main() and
# all the operations are performed
def main():
 
    # input via readline method
    n = stdin.readline()
 
    # array input similar method
    arr = [int(x) for x in stdin.readline().split()]
 
    #initialize variable
    summation = 0
     
    # calculate sum
    for x in arr:
        summation += x
 
    # could use inbuilt summation = sum(arr)
 
    # print answer via write
    # write method writes only
    # string operations
    # so we need to convert any
    # data into string for input
    stdout.write(str(summation))
 
# call the main method
if __name__ == "__main__":
    main()   


Difference in Time

Timing summary (100k lines each) 
——————————– 
Print : 6.040 s 
Write to file : 0.122 s 
Print with Stdout : 0.121 s

As we have seen till now that taking input from the standard system and giving output to the standard system is always a good idea to improve the efficiency of the code which is always a need in Competitive programming. But wait! would you like to write these long lines every time when you need them? Then, what’s the benefit of using Python. 
Let’s discuss the solution to this problem. What we can do is let’s create separate functions for taking inputs of various types and just call them whenever you need them. 

Taking User Input Given in a Single Line in Separate Variables

Suppose the input is of the following form 

5 7 19 20

We want separate variables to reference them. What we want is given below

a = 5
b = 7
c = 19
d = 20

To do this, we can create a function named as get_ints() as given below in the code

Python3




import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
 
a,b,c,d = get_ints()


Now we don’t need to write this line again and again. You just have to call the get_ints() function in order to take input in this form. In the function get_ints we are using the map function.

Taking User Inputs of List of Integers

Suppose the input is of the following form 

1 2 3 4 5 6 7 8

Now, we want that a single variable will hold the whole list of integers. What we want is given below.

Arr = [1, 2, 3, 4, 5, 6, 7, 8]

Here we will create a function named get_list() as given below.

Python3




import sys
def get_ints(): return list(map(int, sys.stdin.readline().strip().split()))
 
Arr = get_ints()


Now you don’t have to write this line again and again. You just have to call the get_ints() function in order to take input in this form 

Taking String Input from the User

Suppose the input is of the following form  

GeeksforGeeks is the best platform to practice Coding.

Now, we want that a single reference variable will hold this string. What we want is given below

string = "GeeksforGeeks if the best platform to practice coding."

Here we will create a function named get_string() as given below in the code. 

Python3




import sys
def get_string(): return sys.stdin.readline().strip()
 
string = get_string()


Now you don’t have to write this line again and again. You just have to call the get_string() function in order to take input in this form

Adding a buffered pipe io (Python 2.7) 

  • Simply, adding the buffered IO code before your submission code to make the output faster. 
  • The benefit of io.BytesIO objects is that they implement a common interface (commonly known as a ‘file-like’ object). BytesIO objects have an internal pointer and for every call to read(n) the pointer advances. 
  • The atexit module provides a simple interface to register functions to be called when a program closes down normally. The sys module also provides a hook, sys.exitfunc, but only one function can be registered there. The atexit registry can be used by multiple modules and libraries simultaneously.  

Python3




# import libraries for input/ output handling
# on generic level
import atexit, io, sys
 
# A stream implementation using an in-memory bytes
# buffer. It inherits BufferedIOBase.
buffer = io.BytesIO()
sys.stdout = buffer
 
# print via here
@atexit.register
def write():
    sys.stdout.write(buffer.getvalue())
 
#####################################
# template ends
 
n = int(input())
 
# input the array
arr = [int(x) for x in input().split()]
 
# initialize variable
summation = 0
 
# calculate sum
for x in arr:
    summation += x
 
# print answer
print(summation)


Summary

While handling a large amount of data usually, the normal method fails to execute within the time limit. Method 2 helps in maintaining a large amount of I/O data. Method 3 is the fastest. Usually, handling of input data files greater than 2 or 3 MBs is helped via methods 2 and 3.
Note: above mention codes are in Python 2.7, to use in Python 3.X versions. Simply replace the raw_input() with Python 3.X’s input() syntax. Rest should work fine.

References



Previous Article
Next Article

Similar Reads

Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Input/Output from external file in C/C++, Java and Python for Competitive Programming
In Competitive Programming, most of the time we need to enter input for checking our code manually. But it would become cumbersome if we have a questions like Graphs, strings, or bulky entry of input data because it will definitely time out or the chances of typing incorrect data would be increased. We can easily get rid of problem by simply saving
4 min read
Input/Output from external file in C/C++, Java and Python for Competitive Programming | Set 2
Prerequisites : Input/Output from external file in C/C++, Java and Python for Competitive Programming In above post,  we saw a way to have standard input/output from external file using file handling. In this post, we will see a very easy way to do this. Here we will compile and run our code from terminal or cmd using  input and output streams. Win
3 min read
Efficiently Reading Input For Competitive Programming using Java 8
As we all know, while solving any CP problems, the very first step is collecting input or reading input. A common mistake we all make is spending too much time on writing code and compile-time as well. In Java, it is recommended to use BufferedReader over Scanner to accept input from the user. Why? It is discussed in one of our previous articles he
6 min read
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile(). Syntax: int getchar_unlocked(void); Example:
2 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Top Programming Languages For Competitive Programming
Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are almost more than 700 programming languages which are the most popular ones and this number will increase day by day. But, you don't need to learn all of them. Having a good command of anyone is enough for you to grow your
13 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
Practice Tags :